diff --git a/.claude/skills/dependency-audit/SKILL.md b/.claude/skills/dependency-audit/SKILL.md index 631fe3f5f..6042c3fa9 100644 --- a/.claude/skills/dependency-audit/SKILL.md +++ b/.claude/skills/dependency-audit/SKILL.md @@ -6,7 +6,7 @@ description: Use to audit Rust and npm dependencies for vulnerabilities, licence # Dependency audit - Rust (from the root): `cargo deny check` — exactly what CI `security-cargo.yml` runs: advisories, licences (what GPL-3.0-only may ship, `deny.toml`), sources (crates.io alone) and bans (nothing refused by name, duplicates allowed). A new licence or source is a decision, not a line to add. `cargo-deny` is not part of the toolchain: if it is missing, say so rather than installing it, and read the job's result on the pull request. `cargo tree -d` for duplicates. -- npm (root): `npm audit --omit=dev --audit-level=high`, `npm outdated`. +- npm (`website/`, `crates/engine/sandbox/`): `npm audit --omit=dev --audit-level=high`, `npm outdated`. The Prettier compiled in is pinned in `scripts/prettier.mjs`. - Adding a dependency: justify it, check maintenance, licence and size, pin like its siblings. Prefer none. An embedded font or icon set goes in `crates/ui/assets/README.md` with its licence file beside it. - Do **not** update versions during an audit. egui and its family, the pinned Prettier and the Rust toolchain move only in deliberate, separate commits. - Report: advisory id, crate/package, reachable or not, suggested action. diff --git a/.claude/skills/verify-change/SKILL.md b/.claude/skills/verify-change/SKILL.md index 19a1e9f4f..2521980e1 100644 --- a/.claude/skills/verify-change/SKILL.md +++ b/.claude/skills/verify-change/SKILL.md @@ -11,7 +11,7 @@ Run from the repo root; pick by what changed, and report only what actually ran. | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `crates/**` | `cargo fmt --all --check`, `cargo clippy --workspace --all-targets --all-features -- -D warnings`, `cargo test --workspace --exclude e2e` | | `crates/i18n/translations/*.json` | the row above (the keys are generated and the plural corpora checked by `cargo test -p i18n`) | -| Markdown, JSON, YAML, `scripts/**`, `.github/**` | `npm run lint`, `npm run test:scripts` | +| `scripts/**`, `.github/**` | `node --test "scripts/*.test.mjs"` | | `docs/content/**` | `npm run docs` from `website/`, `cargo test -p engine docs`, `cargo test -p ui docs_quotes` | | `website/**` | from `website/`: `npm run lint`, `npm run test:scripts`, `npm test`, `npm run build`, and a look at the built page | | A user journey, anything the assembled app does | `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (or `--test NN_name` for the scenario it touches) (`desktop-e2e-testing`) | diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..94341586d --- /dev/null +++ b/.editorconfig @@ -0,0 +1,38 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true + +# As `rustfmt.toml` writes it. +[*.rs] +indent_size = 4 +max_line_length = 110 + +[*.{toml,sql,py}] +indent_size = 4 + +# Two spaces at the end of a line break it. +[*.md] +trim_trailing_whitespace = false + +# Compared byte for byte, or kept as published. +[{golden,crates/engine/tests/corpus,crates/engine/sandbox/dist,crates/text/prettier,docs/recette}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset + +[.claude/skills/{accessibility,core-web-vitals,frontend-design,rust-guidelines,seo,webapp-testing}/**] +charset = unset +end_of_line = unset +indent_size = unset +indent_style = unset +insert_final_newline = unset +trim_trailing_whitespace = unset diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 000000000..53f3281bc --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +# Commits that only reformat, left out of a blame: `git config blame.ignoreRevsFile .git-blame-ignore-revs`. +# Code formatted at 110 columns (#1851) +97af2e0fd1f0dd5a07bf0b9b69811e6778ea6d73 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index f23309c61..355952fd5 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -102,17 +102,6 @@ updates: - 'quick-xml' - 'yaml-rust2' - # Prettier alone: Node is a build tool here. - - package-ecosystem: npm - directory: / - schedule: - interval: weekly - day: monday - groups: - npm: - update-types: [minor, patch] - patterns: - - '*' # The request-script libraries, bundled into the binary: an update needs `dist/` rebuilt, # which the Script libraries job checks. - package-ecosystem: npm diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5c3646530..179f24486 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,8 +23,7 @@ env: jobs: # A pull request that touches documentation alone builds and runs nothing: a README cannot - # break the application, and a flaky scenario must not block it. Lint docs still runs, as - # Prettier checks the Markdown. The Rust side is skipped too when only `website/` changes: the + # break the application, and a flaky scenario must not block it. The Rust side is skipped too when only `website/` changes: the # site has a job of its own. The pages of `docs/content` are compiled in and held by Rust tests: # they run on them, without the scenarios. A push, to main or a milestone branch, checks everything. changes: @@ -93,16 +92,10 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc - cache: npm - - - run: npm ci + node-version-file: website/.nvmrc - # Prettier over the Markdown, JSON and YAML, this workflow file included. - - run: npm run lint - - # The release scripts run on Node's own test runner. - - run: npm run test:scripts + # The release scripts run on Node's own test runner: they have no dependency. + - run: node --test "scripts/*.test.mjs" - *stop-the-run @@ -122,7 +115,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc cache: npm cache-dependency-path: website/package-lock.json diff --git a/.github/workflows/package.yml b/.github/workflows/package.yml index afbef5d56..a70ec9626 100644 --- a/.github/workflows/package.yml +++ b/.github/workflows/package.yml @@ -110,7 +110,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 if: matrix.system == 'linux' with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc - name: Release notes for the Linux packages if: matrix.system == 'linux' diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml index 056886713..634aa9901 100644 --- a/.github/workflows/packages.yml +++ b/.github/workflows/packages.yml @@ -92,7 +92,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc - name: The updater run: cargo build -p platform --example update --release --locked diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 40c9466e8..b521ece56 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -46,8 +46,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc - cache: npm + node-version-file: website/.nvmrc - name: Read the version id: version @@ -101,9 +100,7 @@ jobs: exit 1 fi - - run: npm ci - - - run: npm run test:scripts + - run: node --test "scripts/*.test.mjs" - name: Write the section env: @@ -111,8 +108,6 @@ jobs: VERSION: ${{ steps.version.outputs.version }} run: | node scripts/release-notes.mjs generate --version "$VERSION" --write --summary "$GITHUB_STEP_SUMMARY" - npx prettier --write CHANGELOG.md - npx prettier --check CHANGELOG.md node scripts/release-notes.mjs extract --version "$VERSION" \ --out "$RUNNER_TEMP/release-notes.md" --prompt-out "$RUNNER_TEMP/prompt-notes.md" diff --git a/.github/workflows/security-npm.yml b/.github/workflows/security-npm.yml index 4756c5651..908e72077 100644 --- a/.github/workflows/security-npm.yml +++ b/.github/workflows/security-npm.yml @@ -9,8 +9,6 @@ on: pull_request: branches: [main, 'dev/**'] paths: - - 'package.json' - - 'package-lock.json' - 'crates/engine/sandbox/**' - 'website/package.json' - 'website/package-lock.json' @@ -29,25 +27,20 @@ permissions: jobs: npm-audit: - # The root keeps its name: it may be a required check. The site's lockfile is audited alike. - name: npm advisories${{ matrix.directory == '.' && '' || ' (website)' }} + name: npm advisories runs-on: ubuntu-22.04 timeout-minutes: 10 - strategy: - fail-fast: false - matrix: - directory: ['.', 'website'] defaults: run: - working-directory: ${{ matrix.directory }} + working-directory: website steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc cache: npm - cache-dependency-path: ${{ matrix.directory }}/package-lock.json + cache-dependency-path: website/package-lock.json - run: npm ci @@ -148,7 +141,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc cache: npm cache-dependency-path: crates/engine/sandbox/package-lock.json diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml index 6d97f99c9..0cd27ff7a 100644 --- a/.github/workflows/website.yml +++ b/.github/workflows/website.yml @@ -53,7 +53,7 @@ jobs: - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: - node-version-file: .nvmrc + node-version-file: website/.nvmrc cache: npm cache-dependency-path: website/package-lock.json diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 520f99759..000000000 --- a/.prettierignore +++ /dev/null @@ -1,24 +0,0 @@ -dist -node_modules -coverage -target -.angular -package-lock.json -# La feuille de recette : une page autonome, ses cas sur une ligne de données. -docs/recette/* -# The documentation is written by hand, without a formatter: its own checks read it. -docs/content/fr -docs/content/en -website/src/app/docs/generated -# Vendored skills (.claude/skills/PROVENANCE.md): kept byte-identical to their source. -.claude/skills/frontend-design -.claude/skills/webapp-testing -.claude/skills/rust-guidelines/guidelines -.claude/skills/seo -.claude/skills/core-web-vitals -.claude/skills/accessibility - -# Test data, compared byte for byte. -golden/*/ -# Prettier itself, copied by `npm run prettier`: kept as published. -crates/text/prettier diff --git a/.prettierrc.json b/.prettierrc.json deleted file mode 100644 index 3ffa1c1e2..000000000 --- a/.prettierrc.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "printWidth": 110, - "singleQuote": true, - "trailingComma": "all", - "semi": true, - "arrowParens": "always", - "endOfLine": "lf" -} diff --git a/CLAUDE.md b/CLAUDE.md index 92f2b511c..713c4908d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,7 +21,7 @@ Principles: - Run: `cargo run -p app -- --profile ` (the whole profile, logs and window geometry in ``; without it, the installed profile `com.devnotes.app`). - Cargo workspace: `cargo check|build|test --workspace`, `cargo clippy --workspace --all-targets --all-features -- -D warnings` (⚠️ `--all-features` is what compiles the `e2e` flavour), `cargo fmt --all --check`, `cargo bench -p engine` (not in CI; `autobenches = false` is load-bearing; → "Benchmarks"). Every external dependency is declared once, in the root `[workspace.dependencies]`; a crate takes it with `dep.workspace = true` and adds only its own features (D33). Toolchain pinned in `rust-toolchain.toml`; `unsafe_code` forbidden in every crate (D7), `clippy::pedantic` denied. -- Node is only a build tool: `npm install` · `npm run lint` (Prettier over Markdown, JSON, YAML; `format` writes) · `npm run test:scripts` (⚠️ test files are named one by one in `package.json`; add new ones there) · `cargo run -p app --example icons` (writes `crates/app/icons/`; ⚠️ small `.ico` sizes come from `icons/source/`) · `npm run prettier` (copies the pinned Prettier into `crates/text/prettier/`, the formatter compiled in). The request-script libraries are bundled by `crates/engine/sandbox/build.mjs`, from that folder's own `package.json`. +- No Node project at the root: the release scripts have no dependency. `node --test "scripts/*.test.mjs"` · `cargo run -p app --example icons` (writes `crates/app/icons/`; ⚠️ small `.ico` sizes come from `icons/source/`) · `node scripts/prettier.mjs` (copies the Prettier it pins into `crates/text/prettier/`, the formatter compiled in). Markdown, JSON and YAML have no formatter. The request-script libraries are bundled by `crates/engine/sandbox/build.mjs`, from that folder's own `package.json`. - Website (`website/`, Angular, devnotes.fr; its own `package.json`, outside the Cargo workspace): from `website/`, `npm ci` · `npm start` (port 4300) · `npm run build` (fetches the latest release, prerenders to `website/dist/`, checks every page and its download links) · `npm test` · `npm run lint` · `npm run test:scripts`. `website.yml` publishes it when `website/` or `docs/content/` changes on `main`, and after each release. → "The website". - E2E: `cargo build -p app --features e2e --target-dir target/e2e`, then `cargo test -p e2e` (the driver is `e2e/` at the root; all scenarios, one after the other; `--test 01_first_launch` for one; `cargo test --workspace --exclude e2e` otherwise). `01`–`35` are the WebdriverIO scenarios ported, the rest are this application's own. → "The scenarios, on the assembled window". - Release is a `workflow_dispatch` after a version bump; the version is `[workspace.package] version` in `Cargo.toml` alone (D27), so a bump touches `Cargo.toml` and `Cargo.lock` (`cargo update --workspace`); `scripts/version.mjs` refuses a release where they disagree. `release.yml` runs `prepare` (checks, changelog written, nothing pushed) → `package` (`package.yml`: a job a system, one action a format under `.github/actions/package/`, signed and checked) → `finalize` (commit, tag, atomic push, release page): ⚠️ the irreversible last, so a failed release leaves nothing to undo. `packages.yml` calls `package.yml` on pull requests, then installs and updates. ⚠️ A version branch (`dev/x.y.z`) reaches `main` by a merge commit, never a squash: the release notes read what the merge brings. → "Releasing", `docs/releasing.md`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 745ba87c4..283247600 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,15 +26,15 @@ cargo run -p app -- --profile ../devnotes-profile `--profile` keeps the run apart from an installed DevNotes: its libraries, logs and window geometry all go in that directory. -Node.js 24 (the version `.nvmrc` pins) is a build tool only, for Prettier over the docs and the -release scripts: `npm install` before `npm run lint`. +Node.js 24 runs the release scripts, which have no dependency; nothing is installed at the root. +The website has its own project in `website/`. ## What CI checks Run these before pushing; they are exactly what the pipeline runs. ```bash -npm run lint && npm run test:scripts +node --test "scripts/*.test.mjs" ``` ```bash @@ -48,9 +48,8 @@ type-checks. | Command | What it does | | ---------------------------------- | ----------------------------------------------------------- | -| `npm run lint` | Prettier check over the Markdown, JSON and YAML | -| `npm run format` | Prettier write | -| `npm run test:scripts` | `node --test` on the release scripts | +| `node --test "scripts/*.test.mjs"` | The release scripts' tests | +| `node scripts/prettier.mjs` | Copies the Prettier compiled in into `crates/text/prettier` | | `cargo bench -p engine` | The core's benchmarks (not in CI; see docs/architecture.md) | | `cargo run -p app --example icons` | Redraws `crates/app/icons/` from `devnotes.svg` | diff --git a/crates/app/build.rs b/crates/app/build.rs index 8e6f5a095..3e0e32594 100644 --- a/crates/app/build.rs +++ b/crates/app/build.rs @@ -18,8 +18,7 @@ mod windows { if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } - let manifest_dir = - env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); + let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); let manifest_dir = Path::new(&manifest_dir); let name = product_name(manifest_dir); let icon = manifest_dir.join("icons/icon.ico"); @@ -34,8 +33,7 @@ mod windows { /// The name the packages give the application, `[package.metadata.packager] product-name`; /// the version is the workspace's, which `winresource` reads from Cargo itself. fn product_name(manifest_dir: &Path) -> String { - let text = - fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); + let text = fs::read_to_string(manifest_dir.join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); manifest .get("package") diff --git a/crates/app/examples/icons.rs b/crates/app/examples/icons.rs index 9136547be..814204797 100644 --- a/crates/app/examples/icons.rs +++ b/crates/app/examples/icons.rs @@ -17,11 +17,7 @@ fn main() { let icons = Path::new(env!("CARGO_MANIFEST_DIR")).join("icons"); let master = icons.join("devnotes.svg"); for (name, size) in PNGS { - let source = if HINTED.contains(&size) { - hinted(&icons, size) - } else { - master.clone() - }; + let source = if HINTED.contains(&size) { hinted(&icons, size) } else { master.clone() }; write(&icons.join(name), &render(&source, size)); } let entries: Vec<(u32, Vec)> = HINTED @@ -38,21 +34,13 @@ fn hinted(icons: &Path, size: u32) -> PathBuf { /// The drawing at `size` × `size` px, as a PNG. fn render(source: &Path, size: u32) -> Vec { - let data = - std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); + let data = std::fs::read(source).unwrap_or_else(|error| panic!("{}: {error}", source.display())); let tree = usvg::Tree::from_data(&data, &usvg::Options::default()) .unwrap_or_else(|error| panic!("{}: {error}", source.display())); let mut pixmap = tiny_skia::Pixmap::new(size, size).expect("a non-empty size"); - #[allow( - clippy::cast_precision_loss, - reason = "an icon is a few hundred pixels wide" - )] + #[allow(clippy::cast_precision_loss, reason = "an icon is a few hundred pixels wide")] let scale = size as f32 / tree.size().width().max(tree.size().height()); - resvg::render( - &tree, - tiny_skia::Transform::from_scale(scale, scale), - &mut pixmap.as_mut(), - ); + resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut()); pixmap.encode_png().expect("a PNG of a pixmap") } @@ -70,11 +58,7 @@ fn ico(entries: &[(u32, Vec)]) -> Vec { header.extend_from_slice(&[side, side, 0, 0]); header.extend_from_slice(&1u16.to_le_bytes()); header.extend_from_slice(&32u16.to_le_bytes()); - header.extend_from_slice( - &u32::try_from(data.len()) - .expect("a small PNG") - .to_le_bytes(), - ); + header.extend_from_slice(&u32::try_from(data.len()).expect("a small PNG").to_le_bytes()); header.extend_from_slice(&u32::try_from(offset).expect("a small file").to_le_bytes()); offset += data.len(); } diff --git a/crates/app/examples/tours.rs b/crates/app/examples/tours.rs index 7cd776ca3..e23c5dee0 100644 --- a/crates/app/examples/tours.rs +++ b/crates/app/examples/tours.rs @@ -54,14 +54,7 @@ const TOURS: [(&str, &[&str]); 3] = [ ), ( "http", - &[ - "http-home", - "http-request", - "http-graphql", - "http-websocket", - "http-environments", - "http-code", - ], + &["http-home", "http-request", "http-graphql", "http-websocket", "http-environments", "http-code"], ), ]; @@ -99,14 +92,10 @@ fn write(path: &Path, frames: &[RgbaImage]) { for frame in frames { let mut reduced = frame.clone(); for pixel in reduced.pixels_mut() { - *pixel = *nearest - .entry(*pixel) - .or_insert_with(|| closest(&palette, *pixel)); + *pixel = *nearest.entry(*pixel).or_insert_with(|| closest(&palette, *pixel)); } let delay = Delay::from_saturating_duration(SHOWN); - encoder - .encode_frame(Frame::from_parts(reduced, 0, 0, delay)) - .expect("a frame"); + encoder.encode_frame(Frame::from_parts(reduced, 0, 0, delay)).expect("a frame"); } } diff --git a/crates/app/src/arguments.rs b/crates/app/src/arguments.rs index 60017d8f1..64bf68574 100644 --- a/crates/app/src/arguments.rs +++ b/crates/app/src/arguments.rs @@ -36,10 +36,7 @@ mod tests { #[test] fn a_profile_directory_is_read_after_its_flag() { - assert_eq!( - of(&["--profile", "/tmp/run-1"]).profile, - Some(PathBuf::from("/tmp/run-1")) - ); + assert_eq!(of(&["--profile", "/tmp/run-1"]).profile, Some(PathBuf::from("/tmp/run-1"))); } #[test] @@ -50,17 +47,29 @@ mod tests { #[test] fn an_action_is_read_after_its_flag() { - assert_eq!( - of(&["--action", "palette"]).action, - Some("palette".to_string()) - ); + assert_eq!(of(&["--action", "palette"]).action, Some("palette".to_string())); } #[test] fn an_unknown_argument_is_left_alone() { - assert_eq!( - of(&["--minimized", "--profile", "p"]).profile, - Some(PathBuf::from("p")) - ); + assert_eq!(of(&["--minimized", "--profile", "p"]).profile, Some(PathBuf::from("p"))); + } + + #[test] + fn both_are_read_in_any_order_and_the_last_of_each_wins() { + let read = of(&["--action", "quit", "--profile", "a", "--profile", "b", "--action", "palette"]); + + assert_eq!(read.profile, Some(PathBuf::from("b"))); + assert_eq!(read.action.as_deref(), Some("palette")); + } + + /// The one after a flag is its value, whatever it looks like. + #[test] + fn a_flag_takes_the_argument_after_it() { + let read = of(&["--profile", "--action", "palette"]); + + assert_eq!(read.profile, Some(PathBuf::from("--action"))); + assert_eq!(read.action, None); + assert_eq!(of(&["--action"]), Arguments::default()); } } diff --git a/crates/app/src/desktop.rs b/crates/app/src/desktop.rs index 85dc6668c..4d31588c1 100644 --- a/crates/app/src/desktop.rs +++ b/crates/app/src/desktop.rs @@ -9,9 +9,7 @@ use platform::dialog::FileDialog; use platform::shortcuts::Shortcuts; use platform::tray::{NoTray, Picture, Tray}; use platform::updater::Source; -use ui::inputs::{Inbox, Input}; -use ui::services::preferences::Preferences; -use ui::services::settings::Settings; +use ui::{Inbox, Input, Preferences, Settings}; /// Who sends a toast on Windows. const IDENTIFIER: &str = "com.devnotes.app"; @@ -46,28 +44,18 @@ fn start_tray(preferences: &Preferences, inbox: Inbox) -> Box { let Ok(icon) = eframe::icon_data::from_png_bytes(include_bytes!("../icons/32x32.png")) else { return Box::new(NoTray); }; - let picture = Picture { - rgba: icon.rgba, - width: icon.width, - height: icon.height, - }; + let picture = Picture { rgba: icon.rgba, width: icon.width, height: icon.height }; let language = Settings::read(preferences).locale.language(); - platform::tray::system( - picture, - &ui::services::tray::labels(language), - move |asked| { - inbox.post(ui::inputs::Input::Tray(asked)); - }, - ) + platform::tray::system(picture, &ui::tray_labels(language), move |asked| { + inbox.post(Input::Tray(asked)); + }) } /// Named in the language of the launch where a Wayland desktop lists them. #[cfg(not(feature = "e2e"))] fn take_shortcuts(preferences: &Preferences, inbox: Inbox) -> Box { let language = Settings::read(preferences).locale.language(); - platform::shortcuts::system(ui::services::global_keys::described(language), move |key| { - inbox.post(ui::inputs::Input::Shortcut(key)) - }) + platform::shortcuts::system(ui::global_keys(language), move |key| inbox.post(Input::Shortcut(key))) } /// A scenario presses no key of the machine (`--action` stands for it), and one held by a diff --git a/crates/app/src/logging.rs b/crates/app/src/logging.rs index 705fd8060..e694fe4f3 100644 --- a/crates/app/src/logging.rs +++ b/crates/app/src/logging.rs @@ -24,11 +24,7 @@ pub(crate) fn start(directory: &Path) -> Option { logger .log_to_file(file) .append() - .rotate( - Criterion::Size(5_000_000), - Naming::Numbers, - Cleanup::KeepLogFiles(3), - ) + .rotate(Criterion::Size(5_000_000), Naming::Numbers, Cleanup::KeepLogFiles(3)) .duplicate_to_stderr(Duplicate::Error) .start() }) @@ -74,11 +70,7 @@ fn notice(language: i18n::Language, logs: &Path) -> (String, String) { let app = || Value::from(engine::app_info::METADATA.name.to_owned()); let title = i18n::translate(language, keys::crash::TITLE, &[("app", app())]); let folder = Value::from(logs.display().to_string()); - let words = i18n::translate( - language, - keys::crash::BODY, - &[("app", app()), ("folder", folder)], - ); + let words = i18n::translate(language, keys::crash::BODY, &[("app", app()), ("folder", folder)]); (title, words) } @@ -87,12 +79,7 @@ fn report(info: &PanicHookInfo<'_>) -> String { let thread = std::thread::current(); let name = thread.name().unwrap_or("unnamed"); match info.location() { - Some(at) => format!( - "Panicked at {}:{}:{} on thread {name}", - at.file(), - at.line(), - at.column() - ), + Some(at) => format!("Panicked at {}:{}:{} on thread {name}", at.file(), at.line(), at.column()), None => format!("Panicked on thread {name}"), } } @@ -182,9 +169,7 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let closed = engine::Engine::new(paths, sink, runtime.handle().clone()); let patch = NotePatch { @@ -193,11 +178,9 @@ mod tests { ..Default::default() }; - let failed = engine::db::run_here(&closed, |engine| { - engine::notes::update_note(engine, "note-id", &patch) - }); - ui::services::errors::ErrorNotifier::default() - .report(i18n::keys::errors::NOTE_GONE, &failed.unwrap_err()); + let failed = + engine::db::run_here(&closed, |engine| engine::notes::update_note(engine, "note-id", &patch)); + ui::ErrorNotifier::default().report(i18n::keys::errors::NOTE_GONE, &failed.unwrap_err()); let written = written(); assert!(written.contains("errors.noteGone"), "{written}"); @@ -210,14 +193,10 @@ mod tests { logger(); let profile = tempfile::tempdir().unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = engine::Paths { - profile: profile.path().to_path_buf(), - }; + let paths = engine::Paths { profile: profile.path().to_path_buf() }; let sink = Arc::new(engine::RecordingSink::default()); let engine = engine::Engine::new(paths, sink, runtime.handle().clone()); - let draft = || engine::spaces::model::SpaceDraft { - name: "Clients Dupont-Aignan".to_owned(), - }; + let draft = || engine::spaces::model::SpaceDraft { name: "Clients Dupont-Aignan".to_owned() }; let duplicate = engine::db::run_here(&engine, |engine| { let phrase = engine::vault::secret("correct horse battery staple".to_owned()); engine::vault::create_vault(engine, phrase)?; @@ -235,7 +214,7 @@ mod tests { }; let script = engine::http::scripts::model::ScriptError::Stopped(stop); - let mut notifier = ui::services::errors::ErrorNotifier::default(); + let mut notifier = ui::ErrorNotifier::default(); notifier.report(i18n::keys::errors::NOTE_GONE, &duplicate); notifier.report(i18n::keys::errors::NOTE_GONE, &too_large.into()); notifier.report(i18n::keys::errors::NOTE_GONE, &script.into()); @@ -275,10 +254,7 @@ mod tests { assert!(title.contains(engine::app_info::METADATA.name), "{title}"); assert!(words.contains("C:/profil/logs"), "{words}"); assert_ne!(words, english); - assert!( - !words.contains("{{") && !english.contains("{{"), - "{words} {english}" - ); + assert!(!words.contains("{{") && !english.contains("{{"), "{words} {english}"); } /// Where the process that panics for the test below writes its log. @@ -295,10 +271,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let ended = std::process::Command::new(std::env::current_exe().unwrap()) - .args([ - "--exact", - "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log", - ]) + .args(["--exact", "logging::tests::a_panic_ends_the_process_once_its_place_is_in_the_log"]) .env(PANIC_IN, directory.path()) .output() .unwrap(); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 782050d68..60d2484d1 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -28,16 +28,13 @@ use engine::app_info::METADATA; use platform::instance::{self, Claim, Instance, Message}; use platform::paths::{self, Locations}; use platform::window::Geometry; -use ui::services::preferences::Preferences; +use ui::Preferences; fn main() -> ExitCode { // First, for the script host too: it logs nothing there, and exits the same. logging::install_panic_hook(); // A script host opens no window and writes no log. - if std::env::args_os() - .nth(1) - .is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) - { + if std::env::args_os().nth(1).is_some_and(|arg| arg == engine::SCRIPT_HOST_ARG) { std::process::exit(engine::serve_scripts()); } @@ -81,9 +78,8 @@ fn main() -> ExitCode { #[cfg(target_os = "linux")] fn missing_library() -> Option<&'static str> { let x11 = std::env::var_os("DISPLAY").is_some(); - (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()).then_some( - "libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)", - ) + (x11 && xkbcommon_dl::x11::xkbcommon_x11_option().is_none()) + .then_some("libxkbcommon-x11 (libxkbcommon-x11-0 on Debian and Ubuntu, libxkbcommon-x11 on Fedora)") } #[cfg(not(target_os = "linux"))] @@ -98,9 +94,9 @@ fn not_opened(error: &eframe::Error) -> String { use eframe::egui_wgpu::WgpuError; match error { - eframe::Error::Wgpu( - WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_), - ) if cfg!(target_os = "linux") => { + eframe::Error::Wgpu(WgpuError::CreateSurfaceError(_) | WgpuError::RequestAdapterError(_)) + if cfg!(target_os = "linux") => + { format!( "The window did not open: no graphics driver answered, neither Vulkan nor OpenGL \ ({error}). Install your graphics card's drivers, or Mesa's: mesa-vulkan-drivers \ @@ -127,23 +123,17 @@ fn hand_over(profile: &Path, action: Option) -> ExitCode { fn run(locations: Locations, instance: Instance) -> eframe::Result { let restored = platform::window::read(&locations.window); let preferences = Preferences::read(&locations.profile.join(engine::layout::PREFERENCES)); - let language = ui::services::settings::Settings::read(&preferences) - .locale - .language(); + let language = ui::Settings::read(&preferences).locale.language(); logging::tell_when_stopped(language, &locations.logs); - let (inbox, waker, inputs) = ui::inputs::channel(); + let (inbox, waker, inputs) = ui::channel(); let heard = inbox.clone(); - if let Err(error) = - instance.serve(move |message| heard.post(ui::inputs::Input::Instance(message))) - { + if let Err(error) = instance.serve(move |message| heard.post(ui::Input::Instance(message))) { log::warn!("Second launches will not be heard: {error}"); } // ⚠️ Called with the event loop running: macOS makes no tray icon before. let startup = move || ui::Startup { desktop: desktop::start(&preferences, &inbox), - paths: engine::Paths { - profile: locations.profile, - }, + paths: engine::Paths { profile: locations.profile }, window_file: locations.window, geometry: restored, reduced_motion: platform::motion::system_prefers_reduced(), @@ -264,22 +254,14 @@ mod tests { panic!("the profile was taken"); }; let (heard, hearing) = mpsc::channel(); - first - .serve(move |message| heard.send(message).unwrap()) - .unwrap(); + first.serve(move |message| heard.send(message).unwrap()).unwrap(); assert_eq!(hand_over(profile.path(), None), ExitCode::SUCCESS); - assert_eq!( - hand_over(profile.path(), Some("palette".to_string())), - ExitCode::SUCCESS - ); + assert_eq!(hand_over(profile.path(), Some("palette".to_string())), ExitCode::SUCCESS); let wait = Duration::from_secs(10); assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Reveal); - assert_eq!( - hearing.recv_timeout(wait).unwrap(), - Message::Action("palette".to_string()) - ); + assert_eq!(hearing.recv_timeout(wait).unwrap(), Message::Action("palette".to_string())); } #[test] @@ -297,21 +279,14 @@ mod tests { let said = not_opened(&no_adapter); - assert_eq!( - said.contains("neither Vulkan nor OpenGL"), - cfg!(target_os = "linux") - ); - assert_eq!( - said.contains("mesa-vulkan-drivers"), - cfg!(target_os = "linux") - ); + assert_eq!(said.contains("neither Vulkan nor OpenGL"), cfg!(target_os = "linux")); + assert_eq!(said.contains("mesa-vulkan-drivers"), cfg!(target_os = "linux")); assert!(!said.contains('\n'), "{said}"); } #[test] fn another_renderer_error_is_said_as_it_is() { - let no_format = - eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); + let no_format = eframe::Error::Wgpu(eframe::egui_wgpu::WgpuError::NoSurfaceFormatsAvailable); let said = not_opened(&no_format); @@ -324,14 +299,8 @@ mod tests { let options = options(None); assert_eq!(options.viewport.visible, Some(false)); - assert_eq!( - options.viewport.inner_size, - Some(egui::vec2(1_100.0, 720.0)) - ); - assert_eq!( - options.viewport.min_inner_size, - Some(egui::vec2(640.0, 480.0)) - ); + assert_eq!(options.viewport.inner_size, Some(egui::vec2(1_100.0, 720.0))); + assert_eq!(options.viewport.min_inner_size, Some(egui::vec2(640.0, 480.0))); assert!(options.viewport.icon.is_some()); assert!(options.centered); assert!(!options.persist_window); @@ -339,13 +308,8 @@ mod tests { #[test] fn a_later_launch_opens_where_the_window_was() { - let options = options(Some(Geometry { - x: 40.0, - y: 30.0, - width: 900.0, - height: 600.0, - maximized: true, - })); + let options = + options(Some(Geometry { x: 40.0, y: 30.0, width: 900.0, height: 600.0, maximized: true })); assert_eq!(options.viewport.visible, Some(false)); assert_eq!(options.viewport.inner_size, Some(egui::vec2(900.0, 600.0))); diff --git a/crates/app/src/renderer.rs b/crates/app/src/renderer.rs index c2aeb3dc5..ca27ac774 100644 --- a/crates/app/src/renderer.rs +++ b/crates/app/src/renderer.rs @@ -15,9 +15,8 @@ pub(crate) fn options() -> WgpuConfiguration { } let mut setup = WgpuSetupCreateNew::without_display_handle(); setup.native_adapter_selector = Some(std::sync::Arc::new(|adapters, surface| { - let draws_here = |adapter: &&wgpu::Adapter| { - surface.is_none_or(|surface| adapter.is_surface_supported(surface)) - }; + let draws_here = + |adapter: &&wgpu::Adapter| surface.is_none_or(|surface| adapter.is_surface_supported(surface)); adapters .iter() .filter(draws_here) @@ -26,10 +25,7 @@ pub(crate) fn options() -> WgpuConfiguration { .cloned() .ok_or_else(|| "no adapter draws on this window".to_string()) })); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } #[cfg(not(feature = "e2e"))] @@ -40,10 +36,7 @@ pub(crate) fn options() -> WgpuConfiguration { } let device = std::sync::Arc::clone(&setup.device_descriptor); setup.device_descriptor = std::sync::Arc::new(move |adapter| sparing(device(adapter))); - WgpuConfiguration { - wgpu_setup: WgpuSetup::CreateNew(setup), - ..Default::default() - } + WgpuConfiguration { wgpu_setup: WgpuSetup::CreateNew(setup), ..Default::default() } } /// The one API to open, or `None` for eframe's choice: `WGPU_BACKEND` when it is set, and every @@ -109,10 +102,7 @@ mod tests { fn the_device_is_asked_to_reserve_memory_by_small_blocks() { let device = sparing(wgpu::DeviceDescriptor::default()); - assert!(matches!( - device.memory_hints, - wgpu::MemoryHints::MemoryUsage - )); + assert!(matches!(device.memory_hints, wgpu::MemoryHints::MemoryUsage)); } #[test] diff --git a/crates/app/src/sight.rs b/crates/app/src/sight.rs index 2c5e9da36..030dca0ea 100644 --- a/crates/app/src/sight.rs +++ b/crates/app/src/sight.rs @@ -19,12 +19,7 @@ pub(crate) struct Watched { impl Watched { pub(crate) fn new(app: ui::DevNotesApp) -> Self { - Watched { - app, - hidden: false, - put_away: 0, - read: 0, - } + Watched { app, hidden: false, put_away: 0, read: 0 } } fn follow(&mut self, ctx: &Context) { @@ -55,11 +50,7 @@ impl eframe::App for Watched { fn ui(&mut self, ui: &mut Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); self.follow(ui.ctx()); - let said = if self.hidden { - "window-hidden" - } else { - "window-shown" - }; + let said = if self.hidden { "window-hidden" } else { "window-shown" }; mark(ui, said, said); mark(ui, "window-put-away", &self.put_away.to_string()); } diff --git a/crates/app/src/unpainted.rs b/crates/app/src/unpainted.rs index 9a1316284..7a1011669 100644 --- a/crates/app/src/unpainted.rs +++ b/crates/app/src/unpainted.rs @@ -32,12 +32,9 @@ impl egui::Plugin for Unpainted { } fn asks_for_capture(output: &FullOutput) -> bool { - output - .viewport_output - .get(&ViewportId::ROOT) - .is_some_and(|root| { - root.commands - .iter() - .any(|command| matches!(command, ViewportCommand::Screenshot(_))) - }) + output.viewport_output.get(&ViewportId::ROOT).is_some_and(|root| { + root.commands + .iter() + .any(|command| matches!(command, ViewportCommand::Screenshot(_))) + }) } diff --git a/crates/app/tests/windows_resources.rs b/crates/app/tests/windows_resources.rs index 5f9d37b22..a91f846f0 100644 --- a/crates/app/tests/windows_resources.rs +++ b/crates/app/tests/windows_resources.rs @@ -42,7 +42,5 @@ fn resource_types(file: &[u8]) -> Vec { let named = u16_at(root + 12); let numbered = u16_at(root + 14); - (named..named + numbered) - .map(|entry| u32_at(root + 16 + 8 * entry)) - .collect() + (named..named + numbered).map(|entry| u32_at(root + 16 + 8 * entry)).collect() } diff --git a/crates/drawing/src/edit.rs b/crates/drawing/src/edit.rs index c18d58d56..95864499b 100644 --- a/crates/drawing/src/edit.rs +++ b/crates/drawing/src/edit.rs @@ -103,10 +103,7 @@ impl Frame { /// A point of the frame's own plane, in the scene's. fn on_scene(&self, x: f64, y: f64) -> Point { let (sin, cos) = self.angle.to_radians().sin_cos(); - Point { - x: self.centre.x + x * cos - y * sin, - y: self.centre.y + x * sin + y * cos, - } + Point { x: self.centre.x + x * cos - y * sin, y: self.centre.y + x * sin + y * cos } } fn on_frame(&self, at: Point) -> (f64, f64) { @@ -117,11 +114,7 @@ impl Frame { pub fn grip(&self, grip: Grip) -> Point { let (x, y) = grip.place(); - let reach = if grip == Grip::Rotate { - self.reach - } else { - 0.0 - }; + let reach = if grip == Grip::Rotate { self.reach } else { 0.0 }; self.on_scene(x * self.width / 2.0, y * self.height / 2.0 - reach) } @@ -136,13 +129,7 @@ impl Frame { } pub fn corners(&self) -> [Point; 4] { - [ - Grip::TopLeft, - Grip::TopRight, - Grip::BottomRight, - Grip::BottomLeft, - ] - .map(|corner| self.grip(corner)) + [Grip::TopLeft, Grip::TopRight, Grip::BottomRight, Grip::BottomLeft].map(|corner| self.grip(corner)) } } @@ -328,10 +315,6 @@ impl Editor { self.drawing.objects.len() } - pub fn selected(&self) -> &[usize] { - &self.selected - } - pub fn can_undo(&self) -> bool { self.at > 0 } @@ -416,10 +399,7 @@ impl Editor { let mut step = 1.0; while step <= steps { let part = step / steps; - let at = Point { - x: from.x + (to.x - from.x) * part, - y: from.y + (to.y - from.y) * part, - }; + let at = Point { x: from.x + (to.x - from.x) * part, y: from.y + (to.y - from.y) * part }; let come_onto = |object: &Object| object.contains(at) && !object.contains(last); let gone: Vec = (0..self.drawing.objects.len()) .filter(|&index| come_onto(&self.drawing.objects[index])) @@ -498,17 +478,13 @@ impl Editor { let reach = GRIP_REACH / self.scale; let near = |end: Point| (end.x - at.x).abs() <= reach && (end.y - at.y).abs() <= reach; let ends = self.arrow_ends()?; - ends.into_iter() - .find(|(_, place)| near(*place)) - .map(|(end, _)| end) + ends.into_iter().find(|(_, place)| near(*place)).map(|(end, _)| end) } /// Asked while the arrow tool is in hand or an end is dragged. pub fn attaching(&self, at: Point) -> Option { let kept = match &self.gesture { - Some(Gesture::MovingEnd { index, end, .. }) => { - end.other_bound(&self.drawing.objects[*index]) - } + Some(Gesture::MovingEnd { index, end, .. }) => end.other_bound(&self.drawing.objects[*index]), Some(Gesture::Arrow { held, .. }) => held.as_ref().map(|hold| hold.id.as_str()), None if self.tool == Tool::Arrow => None, _ => return None, @@ -588,10 +564,7 @@ impl Editor { /// The topmost object under a point. fn object_at(&self, at: Point) -> Option { - self.drawing - .objects - .iter() - .rposition(|object| object.contains(at)) + self.drawing.objects.iter().rposition(|object| object.contains(at)) } /// A pointer pressed. `adding` is Shift: an object joins the selection or leaves it. @@ -634,11 +607,7 @@ impl Editor { && let Some(end) = self.end_at(at) && let [index] = self.selected[..] { - self.gesture = Some(Gesture::MovingEnd { - index, - end, - from: at, - }); + self.gesture = Some(Gesture::MovingEnd { index, end, from: at }); return; } if let Some(grip) = self.grip_at(at).filter(|_| !adding) @@ -646,17 +615,9 @@ impl Editor { { let before = self.selection(); self.gesture = Some(if grip == Grip::Rotate { - Gesture::Rotating { - frame, - from: bearing(frame.centre, at), - before, - } + Gesture::Rotating { frame, from: bearing(frame.centre, at), before } } else { - Gesture::Scaling { - grip, - frame, - before, - } + Gesture::Scaling { grip, frame, before } }); return; } @@ -679,11 +640,7 @@ impl Editor { self.selected = vec![index]; } let before = self.selection(); - self.gesture = Some(Gesture::Moving { - from: at, - before, - reselected, - }); + self.gesture = Some(Gesture::Moving { from: at, before, reselected }); } fn selection(&self) -> Selected { @@ -720,16 +677,8 @@ impl Editor { move_to(self, before, *from, to); } } - Gesture::Scaling { - grip, - frame, - before, - } => scale_to(self, before, *grip, *frame, to), - Gesture::Rotating { - frame, - from, - before, - } => { + Gesture::Scaling { grip, frame, before } => scale_to(self, before, *grip, *frame, to), + Gesture::Rotating { frame, from, before } => { rotate_to(self, before, *frame, bearing(frame.centre, to) - *from); } Gesture::Marquee { to: end, .. } => *end = to, @@ -747,16 +696,7 @@ impl Editor { let least = CLICKED / self.scale; let clicked = dragged.width < least && dragged.height < least; let (width, height) = CLICK_SIZE; - let bounds = if clicked { - Box { - left: from.x, - top: from.y, - width, - height, - } - } else { - dragged - }; + let bounds = if clicked { Box { left: from.x, top: from.y, width, height } } else { dragged }; self.reshape_last(tool, bounds); self.finish(); } @@ -766,9 +706,7 @@ impl Editor { return; }; let kept = held.map(|hold| hold.id); - let hold = self - .hold_at(at) - .filter(|hold| Some(&hold.id) != kept.as_ref()); + let hold = self.hold_at(at).filter(|hold| Some(&hold.id) != kept.as_ref()); End::To.hold(&mut arrow, hold.as_ref()); self.drawing.objects.push(arrow); let last = self.drawing.objects.len() - 1; @@ -780,16 +718,12 @@ impl Editor { Some(Gesture::MovingEnd { from, .. }) if from == at => {} Some(Gesture::MovingEnd { index, end, .. }) => { let kept = end.other_bound(&self.drawing.objects[index]); - let hold = self - .hold_at(at) - .filter(|hold| Some(hold.id.as_str()) != kept); + let hold = self.hold_at(at).filter(|hold| Some(hold.id.as_str()) != kept); self.move_end(index, end, hold.as_ref(), at); self.keep(); } Some(Gesture::Marquee { from, to }) => self.select_within(drag_box(from, to)), - Some(Gesture::Moving { - from, reselected, .. - }) => { + Some(Gesture::Moving { from, reselected, .. }) => { if from != at { self.settle(); } else if reselected { @@ -828,21 +762,15 @@ impl Editor { self.revision += 1; } - /// A text left empty was a click: it goes, and the history never knew it. + /// A text left empty goes. Just clicked, the history never knew it; typed before, it is a + /// deletion like another. pub fn leave_text(&mut self) { let Some(index) = self.editing.take() else { return; }; - if self.drawing.objects[index] - .text() - .unwrap_or_default() - .trim() - .is_empty() - { + if self.drawing.objects[index].text().unwrap_or_default().trim().is_empty() { self.drawing.objects.remove(index); self.selected.clear(); - self.revision += 1; - return; } self.keep(); } @@ -882,10 +810,7 @@ impl Editor { text.put("fontFamily", TEXT_FONT); text.put_number("strokeWidth", 0.0); text.set_size(TEXT_WIDTH, text_height(1, TEXT_SIZE, text.line_height())); - text.set_centre(Point { - x: at.x + TEXT_WIDTH / 2.0, - y: at.y, - }); + text.set_centre(Point { x: at.x + TEXT_WIDTH / 2.0, y: at.y }); self.drawing.objects.push(text); self.tool = Tool::Select; self.kept.clear(); @@ -919,18 +844,13 @@ impl Editor { } fn select_within(&mut self, marquee: Box) { - let touched = self - .drawing - .objects - .iter() - .enumerate() - .filter(|(_, object)| { - let bounds = object.bounds(); - bounds.left < marquee.left + marquee.width - && marquee.left < bounds.left + bounds.width - && bounds.top < marquee.top + marquee.height - && marquee.top < bounds.top + bounds.height - }); + let touched = self.drawing.objects.iter().enumerate().filter(|(_, object)| { + let bounds = object.bounds(); + bounds.left < marquee.left + marquee.width + && marquee.left < bounds.left + bounds.width + && bounds.top < marquee.top + marquee.height + && marquee.top < bounds.top + bounds.height + }); let touched: Vec = touched.map(|(index, _)| index).collect(); if marquee.width > 0.0 || marquee.height > 0.0 { for index in touched { @@ -946,12 +866,10 @@ impl Editor { /// it: a shape does, under the text or the arrow over it. fn holder_at(&self, at: Point) -> Option<(usize, Option)> { let objects = self.drawing.objects.iter().enumerate().rev(); - objects - .filter(|(_, object)| holds_arrows(object)) - .find_map(|(index, object)| { - let side = self.side_at(object, at); - (side.is_some() || object.contains(at)).then_some((index, side)) - }) + objects.filter(|(_, object)| holds_arrows(object)).find_map(|(index, object)| { + let side = self.side_at(object, at); + (side.is_some() || object.contains(at)).then_some((index, side)) + }) } fn side_at(&self, object: &Object, at: Point) -> Option { @@ -993,10 +911,7 @@ impl Editor { let arrow = &self.drawing.objects[index]; let from = self.held_by(arrow, End::From); let to = self.held_by(arrow, End::To); - set_arrow( - &mut self.drawing.objects[index], - bound_ends(drawn, from.as_ref(), to.as_ref()), - ); + set_arrow(&mut self.drawing.objects[index], bound_ends(drawn, from.as_ref(), to.as_ref())); } /// The arrows bound to anything take their place from it. @@ -1061,10 +976,7 @@ fn move_to(editor: &mut Editor, before: &Selected, from: Point, to: Point) { for (index, object) in before { let centre = object.centre(); let moved = &mut editor.drawing.objects[*index]; - moved.set_centre(Point { - x: centre.x + dx, - y: centre.y + dy, - }); + moved.set_centre(Point { x: centre.x + dx, y: centre.y + dy }); if let Some([x1, y1, x2, y2]) = object.ends() { moved.set_ends([x1 + dx, y1 + dy, x2 + dx, y2 + dy]); } @@ -1078,11 +990,7 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to // From the handle's opposite, which stays where it is. let anchor = (-place_x * frame.width / 2.0, -place_y * frame.height / 2.0); let along = |place: f64, size: f64, at: f64, from: f64| { - if place == 0.0 { - 1.0 - } else { - ((at - from) * place / size).max(LEAST_SCALE) - } + if place == 0.0 { 1.0 } else { ((at - from) * place / size).max(LEAST_SCALE) } }; let mut scale_x = along(place_x, frame.width, x, anchor.0); let mut scale_y = along(place_y, frame.height, y, anchor.1); @@ -1093,20 +1001,13 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } for (index, object) in before { let (cx, cy) = frame.on_frame(object.centre()); - let centre = frame.on_scene( - anchor.0 + (cx - anchor.0) * scale_x, - anchor.1 + (cy - anchor.1) * scale_y, - ); + let centre = + frame.on_scene(anchor.0 + (cx - anchor.0) * scale_x, anchor.1 + (cy - anchor.1) * scale_y); let scaled = &mut editor.drawing.objects[*index]; scaled.set_centre(centre); if object.kind() == Kind::Textbox && place_y == 0.0 { let width = (object.width() * scale_x).max(TEXT_MIN_WIDTH); - let lines = wrap( - object.text().unwrap_or_default(), - width, - object.font_size(), - &editor.fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), width, object.font_size(), &editor.fonts); let height = text_height(lines.len(), object.font_size(), object.line_height()); scaled.set_size(width, height); } else { @@ -1117,14 +1018,8 @@ fn scale_to(editor: &mut Editor, before: &Selected, grip: Grip, frame: Frame, to } fn rotate_to(editor: &mut Editor, before: &Selected, frame: Frame, degrees: f64) { - let turned = Frame { - angle: degrees, - ..frame - }; - let still = Frame { - angle: 0.0, - ..frame - }; + let turned = Frame { angle: degrees, ..frame }; + let still = Frame { angle: 0.0, ..frame }; for (index, object) in before { let (x, y) = still.on_frame(object.centre()); let rotated = &mut editor.drawing.objects[*index]; diff --git a/crates/drawing/src/edit/tests.rs b/crates/drawing/src/edit/tests.rs index 62155d0ba..18b3969e5 100644 --- a/crates/drawing/src/edit/tests.rs +++ b/crates/drawing/src/edit/tests.rs @@ -38,7 +38,7 @@ fn a_shape_covers_the_drag_is_selected_and_the_tool_goes_back() { assert_eq!((shape.width(), shape.height()), (100.0, 60.0)); assert_eq!(shape.corner_radius(), 6.0); assert_eq!(editor.tool(), Tool::Select); - assert_eq!(editor.selected(), [0]); + assert_eq!(editor.selected, [0]); assert!(shape.id().is_some()); } @@ -71,11 +71,7 @@ fn a_new_drawing_is_written_as_a_scene_read_back() { let read = Drawing::read(&editor.body()).unwrap(); assert_eq!(read.objects.len(), 1); - assert!( - editor - .body() - .starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#) - ); + assert!(editor.body().starts_with(r#"{"version":1,"scene":{"version":"7.4.0""#)); } #[test] @@ -91,11 +87,24 @@ fn an_arrow_started_and_ended_on_shapes_stays_on_their_edges() { assert_eq!(arrow.to(), object(&editor, 1).id()); assert_eq!(arrow.ends(), Some([201.0, 130.0, 399.0, 130.0])); assert_eq!(arrow.path().last(), Some(&PathCommand::Close)); +} - drag(&mut editor, at(150.0, 130.0), at(150.0, 130.0)); - drag(&mut editor, at(150.0, 130.0), at(150.0, 330.0)); - let moved = object(&editor, 2).ends().unwrap(); - assert!(moved[1] > 130.0, "the arrow followed: {moved:?}"); +#[test] +fn an_arrow_follows_a_shape_moved_at_either_of_its_ends() { + for (pressed, moved) in [(50.0, 1), (350.0, 3)] { + let mut editor = joined(); + drag(&mut editor, at(pressed, 10.0), at(pressed, 210.0)); + assert!(ends(&editor)[moved] > 150.0, "{:?}", ends(&editor)); + } +} + +#[test] +fn an_arrow_follows_while_its_shape_is_still_held() { + let mut editor = joined(); + editor.press(at(350.0, 10.0), false); + editor.drag(at(350.0, 110.0)); + + assert!(ends(&editor)[3] > 100.0, "{:?}", ends(&editor)); } #[test] @@ -112,92 +121,229 @@ fn an_arrow_on_nothing_ends_where_it_was_let_go() { } #[test] -fn an_arrow_cannot_end_on_the_shape_it_started_on_nor_on_a_text() { +fn an_arrow_cannot_end_on_the_shape_it_started_on() { let mut editor = with_a_rectangle(); editor.set_tool(Tool::Arrow); drag(&mut editor, at(120.0, 130.0), at(180.0, 130.0)); + assert_eq!(object(&editor, 1).from(), object(&editor, 0).id()); assert_eq!(object(&editor, 1).to(), None); +} - editor.set_tool(Tool::Text); - editor.press(at(300.0, 300.0), false); - editor.set_text("words"); - editor.leave_text(); - editor.set_tool(Tool::Arrow); - drag(&mut editor, at(0.0, 0.0), at(350.0, 300.0)); - assert_eq!(object(&editor, 3).to(), None); +#[test] +fn a_text_an_arrow_and_a_shape_without_a_name_hold_no_arrow() { + let body = r#"{"scene":{"objects":[ + {"type":"Textbox","id":"a","left":100,"top":100,"width":100,"height":40,"text":"words"}, + {"type":"Path","id":"b","ends":[0,0,20,0],"left":300,"top":100,"width":100,"height":40,"path":[["M",0,0],["L",20,0]]}, + {"type":"Rect","left":500,"top":100,"width":100,"height":40} + ]}}"#; + for x in [100.0, 300.0, 500.0] { + let mut editor = Editor::open(body, Arc::new(fonts())); + editor.set_tool(Tool::Arrow); + drag(&mut editor, at(0.0, 400.0), at(x, 100.0)); + assert_eq!(object(&editor, 3).to(), None, "{x}"); + } } #[test] fn a_shape_removed_lets_its_arrows_go() { - let mut editor = with_a_rectangle(); - editor.set_tool(Tool::Arrow); - drag(&mut editor, at(150.0, 130.0), at(400.0, 130.0)); - editor.press(at(150.0, 130.0), false); - editor.release(at(150.0, 130.0)); + for (pressed, kept) in [(50.0, 300.0), (350.0, 0.0)] { + let mut editor = joined(); + drag(&mut editor, at(pressed, 10.0), at(pressed, 10.0)); + let drawn = ends(&editor); + + assert!(editor.remove_selection()); + + let arrow = object(&editor, 1); + assert_eq!(editor.shapes(), 2); + assert_eq!([arrow.from(), arrow.to()].into_iter().flatten().count(), 1); + assert_eq!(object(&editor, 0).centre().x, kept + 50.0); + assert_eq!(arrow.ends(), Some(drawn), "it stays where it was"); + } +} + +#[test] +fn several_removed_at_once_are_one_step_of_the_history() { + let mut editor = joined(); + editor.press(at(50.0, 10.0), true); + editor.release(at(50.0, 10.0)); + assert_eq!(editor.selected, [2, 0]); assert!(editor.remove_selection()); + assert_eq!(object(&editor, 0).centre(), at(350.0, 30.0)); + assert_eq!((editor.shapes(), editor.selected.len()), (1, 0)); + editor.undo(); + assert_eq!(editor.shapes(), 3); +} - assert_eq!(editor.shapes(), 1); - assert_eq!(object(&editor, 0).from(), None); +#[test] +fn with_nothing_selected_or_a_text_typed_into_nothing_is_removed() { + let mut editor = with_a_rectangle(); + editor.deselect(); + assert!(!editor.remove_selection()); + + editor.set_tool(Tool::Text); + editor.press(at(300.0, 300.0), false); assert!(!editor.remove_selection()); + assert_eq!(editor.shapes(), 2); } -#[test] -fn the_pen_leaves_a_smoothed_line_unfilled_and_a_click_leaves_none() { +fn with_the_pen(points: &[Point]) -> Editor { let mut editor = editor(); editor.set_tool(Tool::Pen); - editor.press(at(0.0, 0.0), false); - assert!(editor.pen_line().is_some()); - for step in 1..10 { - editor.drag(at(f64::from(step) * 5.0, f64::from(step % 2) * 4.0)); + editor.press(points[0], false); + for point in &points[1..] { + editor.drag(*point); } - editor.release(at(50.0, 0.0)); + editor.release(points[points.len() - 1]); + editor +} + +#[test] +fn the_pen_leaves_a_smoothed_line_round_and_unfilled() { + let points: Vec = (0..10) + .map(|step| at(f64::from(step) * 5.0, f64::from(step % 2) * 4.0)) + .collect(); + let editor = with_the_pen(&points); let line = object(&editor, 0); assert_eq!(line.kind(), Kind::Path); - assert_eq!(line.line_cap(), "round"); + assert_eq!((line.line_cap(), line.line_join()), ("round", "round")); assert_eq!(line.stroke_width(), 2.5); assert!(matches!(line.path()[1], PathCommand::Quad(..))); + assert!(editor.body().contains(r#""fill":null"#)); +} + +#[test] +fn the_pen_stays_in_hand_and_each_line_is_a_step_of_the_history() { + let mut editor = with_the_pen(&[at(0.0, 0.0), at(30.0, 0.0), at(60.0, 20.0)]); + assert_eq!(editor.tool(), Tool::Pen); + assert!(editor.can_undo() && editor.take_unsaved()); +} - drag(&mut editor, at(9.0, 9.0), at(9.0, 9.0)); - assert_eq!(editor.shapes(), 1); +#[test] +fn a_click_of_the_pen_leaves_nothing() { + let mut editor = with_the_pen(&[at(9.0, 9.0), at(9.0, 9.0)]); + + assert_eq!(editor.shapes(), 0); + assert!(!editor.take_unsaved()); +} + +#[test] +fn the_pen_s_line_is_shown_while_it_is_drawn() { + let mut editor = editor(); + assert_eq!(editor.pen_line(), None); + editor.set_tool(Tool::Pen); + editor.press(at(0.0, 0.0), false); + editor.drag(at(5.0, 0.0)); + + assert_eq!(editor.pen_line(), Some(&[at(0.0, 0.0), at(5.0, 0.0)][..])); + editor.release(at(5.0, 0.0)); + assert_eq!(editor.pen_line(), None); } #[test] -fn a_text_is_typed_where_clicked_and_left_empty_it_goes() { +fn a_text_is_typed_where_clicked_its_left_edge_there() { let mut editor = editor(); editor.set_tool(Tool::Text); editor.press(at(10.0, 20.0), false); + let text = object(&editor, 0); assert_eq!(editor.tool(), Tool::Select); - assert!(editor.editing().is_some()); - assert_eq!(editor.frame(), None); - assert_eq!(object(&editor, 0).centre(), at(100.0, 20.0)); + assert_eq!(text.centre(), at(100.0, 20.0)); + assert_eq!((text.text(), text.font_size(), text.stroke_width()), (Some(""), 18.0, 0.0)); + assert_eq!(text.font_family(), "Inter Variable, sans-serif"); + assert!(editor.editing().is_some_and(|(index, _)| index == 0)); + assert_eq!(editor.frame(), None, "typed into, it has no handles"); +} + +#[test] +fn a_text_left_empty_goes_and_the_history_never_knew_it() { + for typed in ["", " \n"] { + let mut editor = editor(); + editor.set_tool(Tool::Text); + editor.press(at(10.0, 20.0), false); + editor.set_text(typed); + + editor.leave_text(); + assert_eq!((editor.shapes(), editor.selected.len()), (0, 0)); + assert!(!editor.can_undo() && !editor.take_unsaved()); + } +} + +#[test] +fn a_text_emptied_is_saved_and_undone_like_a_deletion() { + let mut editor = editor(); + editor.set_tool(Tool::Text); + editor.press(at(10.0, 20.0), false); + editor.set_text("words"); + editor.leave_text(); + editor.take_unsaved(); + let inside = object(&editor, 0).centre(); + drag(&mut editor, inside, inside); + editor.set_text(" "); editor.leave_text(); assert_eq!(editor.shapes(), 0); - assert!(!editor.can_undo()); + assert!(editor.take_unsaved()); + + editor.undo(); + assert_eq!(object(&editor, 0).text(), Some("words")); } -#[test] -fn a_text_grows_with_its_lines_and_a_second_click_types_in_it_again() { +fn with_a_text(text: &str) -> Editor { let mut editor = editor(); editor.set_tool(Tool::Text); editor.press(at(10.0, 20.0), false); - editor.set_text("one\ntwo"); + editor.set_text(text); editor.leave_text(); + editor +} + +#[test] +fn a_text_grows_with_its_lines() { + assert_eq!(object(&with_a_text("one"), 0).height(), 20.34); + assert_eq!(object(&with_a_text("one\ntwo"), 0).height(), 43.93); +} - assert_eq!(object(&editor, 0).height(), 43.93); - assert!(editor.can_undo()); +#[test] +fn a_text_left_is_a_step_of_the_history() { + let mut editor = with_a_text("one"); + assert!(editor.editing().is_none()); + assert!(editor.can_undo() && editor.take_unsaved()); +} + +#[test] +fn a_click_on_a_text_already_selected_types_in_it() { + let mut editor = with_a_text("one"); let inside = object(&editor, 0).centre(); - editor.press(inside, false); - editor.release(inside); + + editor.deselect(); + drag(&mut editor, inside, inside); + assert!(editor.editing().is_none(), "the first click selects it"); + drag(&mut editor, inside, inside); assert!(editor.editing().is_some()); } +#[test] +fn a_click_on_a_shape_selected_types_nothing() { + let mut editor = with_a_rectangle(); + drag(&mut editor, at(150.0, 130.0), at(150.0, 130.0)); + + assert!(editor.editing().is_none()); +} + +#[test] +fn nothing_is_typed_out_of_a_text() { + let mut editor = with_a_text("one"); + editor.set_text("two"); + editor.leave_text(); + + assert_eq!(object(&editor, 0).text(), Some("one")); +} + #[test] fn a_click_selects_the_topmost_and_on_the_paper_drops_the_selection() { let mut editor = with_a_rectangle(); @@ -205,48 +351,127 @@ fn a_click_selects_the_topmost_and_on_the_paper_drops_the_selection() { drag(&mut editor, at(120.0, 120.0), at(220.0, 180.0)); drag(&mut editor, at(150.0, 140.0), at(150.0, 140.0)); - assert_eq!(editor.selected(), [1]); + assert_eq!(editor.selected, [1]); drag(&mut editor, at(105.0, 105.0), at(105.0, 105.0)); - assert_eq!(editor.selected(), [0]); + assert_eq!(editor.selected, [0]); drag(&mut editor, at(600.0, 600.0), at(600.0, 600.0)); - assert!(editor.selected().is_empty()); + assert!(editor.selected.is_empty()); } -#[test] -fn shift_adds_and_takes_away_and_a_marquee_selects_what_it_touches() { +fn with_two_rectangles() -> Editor { let mut editor = with_a_rectangle(); editor.set_tool(Tool::Rectangle); drag(&mut editor, at(300.0, 100.0), at(400.0, 160.0)); editor.deselect(); + editor +} - editor.press(at(150.0, 130.0), true); - editor.release(at(150.0, 130.0)); - editor.press(at(350.0, 130.0), true); - editor.release(at(350.0, 130.0)); - assert_eq!(editor.selected(), [0, 1]); +fn shift_click(editor: &mut Editor, on: Point) { + editor.press(on, true); + editor.release(on); +} - editor.press(at(150.0, 130.0), true); - editor.release(at(150.0, 130.0)); - assert_eq!(editor.selected(), [1]); +#[test] +fn a_click_with_shift_adds_to_the_selection_and_takes_away() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); + assert_eq!(editor.selected, [0, 1]); + + shift_click(&mut editor, at(150.0, 130.0)); + assert_eq!(editor.selected, [1]); + shift_click(&mut editor, at(600.0, 600.0)); + assert_eq!(editor.selected, [1], "the paper takes nothing away"); +} - editor.deselect(); - editor.press(at(50.0, 50.0), false); - editor.drag(at(120.0, 120.0)); - assert!(editor.marquee().is_some()); - editor.release(at(120.0, 120.0)); - assert_eq!(editor.selected(), [0]); +/// With Shift, a handle is what is under it. +#[test] +fn a_click_with_shift_on_a_handle_is_on_the_object() { + let mut editor = with_a_rectangle(); + shift_click(&mut editor, at(199.0, 130.0)); + + assert!(editor.selected.is_empty()); +} + +#[test] +fn a_marquee_selects_what_it_touches() { + for (from, to, selected) in [ + (at(50.0, 50.0), at(120.0, 120.0), vec![0]), + (at(120.0, 120.0), at(50.0, 50.0), vec![0]), + (at(50.0, 50.0), at(320.0, 120.0), vec![0, 1]), + (at(210.0, 100.0), at(290.0, 160.0), vec![]), + (at(250.0, 130.0), at(310.0, 130.0), vec![1]), + (at(350.0, 50.0), at(350.0, 110.0), vec![1]), + (at(50.0, 50.0), at(99.0, 99.0), vec![]), + (at(202.0, 162.0), at(298.0, 300.0), vec![]), + ] { + let mut editor = with_two_rectangles(); + editor.press(from, false); + editor.drag(to); + editor.release(to); + assert_eq!(editor.selected, selected, "{from:?} {to:?}"); + } +} + +#[test] +fn a_marquee_is_shown_while_it_is_dragged() { + let mut editor = with_two_rectangles(); + assert_eq!(editor.marquee(), None); + editor.press(at(120.0, 250.0), false); + editor.drag(at(50.0, 300.0)); + + let shown = editor.marquee().unwrap(); + assert_eq!((shown.left, shown.top, shown.width, shown.height), (50.0, 250.0, 70.0, 50.0)); + editor.release(at(50.0, 300.0)); + assert_eq!(editor.marquee(), None); +} + +#[test] +fn a_marquee_with_shift_adds_to_the_selection_once_each() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(350.0, 130.0)); + editor.press(at(50.0, 50.0), true); + editor.drag(at(320.0, 120.0)); + editor.release(at(320.0, 120.0)); + + assert_eq!(editor.selected, [1, 0]); } #[test] fn what_is_selected_moves_together() { - let mut editor = with_a_rectangle(); + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); drag(&mut editor, at(150.0, 130.0), at(170.0, 140.0)); assert_eq!(object(&editor, 0).centre(), at(170.0, 140.0)); - assert!(editor.can_undo()); + assert_eq!(object(&editor, 1).centre(), at(370.0, 140.0)); + editor.undo(); + assert_eq!(object(&editor, 1).centre(), at(350.0, 130.0), "in one step"); +} + +#[test] +fn a_press_on_what_is_not_selected_moves_it_alone() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + + drag(&mut editor, at(350.0, 130.0), at(350.0, 140.0)); + + assert_eq!(editor.selected, [1]); + assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); +} + +#[test] +fn an_arrow_moved_takes_its_ends_along() { + let mut editor = editor(); + editor.set_tool(Tool::Arrow); + drag(&mut editor, at(0.0, 0.0), at(100.0, 40.0)); + drag(&mut editor, at(50.0, 20.0), at(60.0, 25.0)); + + assert_eq!(object(&editor, 0).ends(), Some([10.0, 5.0, 110.0, 45.0])); } #[test] @@ -256,11 +481,7 @@ fn a_corner_keeps_the_proportions_from_the_opposite_corner() { let corner = frame.grip(Grip::BottomRight); let anchor = frame.grip(Grip::TopLeft); - drag( - &mut editor, - corner, - at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0), - ); + drag(&mut editor, corner, at(anchor.x + frame.width * 2.0, anchor.y + frame.height * 2.0)); let shape = object(&editor, 0); assert_eq!((shape.scale_x(), shape.scale_y()), (2.0, 2.0)); @@ -269,29 +490,93 @@ fn a_corner_keeps_the_proportions_from_the_opposite_corner() { } #[test] -fn a_side_scales_one_way_and_a_text_gets_wider_instead() { +fn a_side_scales_one_way() { + for (grip, (dx, dy), scale) in [ + (Grip::Right, (102.0, 0.0), (2.0, 1.0)), + (Grip::Left, (-102.0, 0.0), (2.0, 1.0)), + (Grip::Bottom, (0.0, 62.0), (1.0, 2.0)), + (Grip::Top, (0.0, -62.0), (1.0, 2.0)), + (Grip::TopLeft, (-102.0, -10.0), (2.0, 2.0)), + (Grip::BottomRight, (10.0, 62.0), (2.0, 2.0)), + ] { + let mut editor = with_a_rectangle(); + let from = editor.frame().unwrap().grip(grip); + drag(&mut editor, from, at(from.x + dx, from.y + dy)); + let shape = object(&editor, 0); + assert_eq!((shape.scale_x(), shape.scale_y()), scale, "{grip:?}"); + } +} + +#[test] +fn the_side_opposite_the_handle_stays_where_it_is() { + let mut editor = with_a_rectangle(); + let before = editor.frame().unwrap(); + + drag(&mut editor, before.grip(Grip::Right), at(301.0, 130.0)); + + let after = editor.frame().unwrap(); + assert!((after.grip(Grip::Left).x - before.grip(Grip::Left).x).abs() < 1.5); +} + +/// Scaled to nothing, it could not be taken again. +#[test] +fn a_handle_dragged_past_the_opposite_side_leaves_a_sliver() { let mut editor = with_a_rectangle(); + let side = editor.frame().unwrap().grip(Grip::Right); + + drag(&mut editor, side, at(-500.0, 130.0)); + + assert_eq!(object(&editor, 0).scale_x(), 0.01); +} + +#[test] +fn several_objects_scale_from_the_side_opposite_the_handle() { + let mut editor = with_two_rectangles(); + shift_click(&mut editor, at(150.0, 130.0)); + shift_click(&mut editor, at(350.0, 130.0)); let frame = editor.frame().unwrap(); let side = frame.grip(Grip::Right); drag(&mut editor, side, at(side.x + frame.width, side.y)); - assert_eq!(object(&editor, 0).scale_x(), 2.0); - assert_eq!(object(&editor, 0).scale_y(), 1.0); - let mut editor = self::editor(); - editor.set_tool(Tool::Text); - editor.press(at(0.0, 100.0), false); - editor.set_text("words enough to wrap across two lines at least"); - editor.leave_text(); + assert_eq!(object(&editor, 1).scale_x(), 2.0); + assert!((object(&editor, 0).centre().x - 201.0).abs() < 0.01); + assert!((object(&editor, 1).centre().x - 601.0).abs() < 0.01); +} + +#[test] +fn a_text_gets_wider_or_narrower_by_its_sides_and_wraps_anew() { + let mut editor = with_a_text("words enough to wrap across two lines at least"); let height = object(&editor, 0).height(); - let frame = editor.frame().unwrap(); + let side = editor.frame().unwrap().grip(Grip::Right); - let side = frame.grip(Grip::Right); drag(&mut editor, side, at(side.x - 90.0, side.y)); - assert_eq!(object(&editor, 0).scale_x(), 1.0); - assert!(object(&editor, 0).width() < 100.0); - assert!(object(&editor, 0).height() > height); + let text = object(&editor, 0); + assert_eq!((text.scale_x(), text.scale_y()), (1.0, 1.0)); + assert!(text.width() < 100.0 && text.height() > height); +} + +#[test] +fn a_text_is_never_narrower_than_a_few_letters() { + let mut editor = with_a_text("words"); + let side = editor.frame().unwrap().grip(Grip::Right); + + drag(&mut editor, side, at(side.x - 400.0, side.y)); + + assert_eq!(object(&editor, 0).width(), 20.0); +} + +#[test] +fn a_text_is_scaled_by_its_corners() { + let mut editor = with_a_text("words"); + let frame = editor.frame().unwrap(); + let corner = frame.grip(Grip::BottomRight); + + drag(&mut editor, corner, at(corner.x + frame.width, corner.y + frame.height)); + + assert_eq!(object(&editor, 0).scale_x(), 2.0); + assert_eq!(object(&editor, 0).width(), 180.0); } #[test] @@ -299,11 +584,7 @@ fn the_rotation_handle_turns_around_the_centre() { let mut editor = with_a_rectangle(); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x + 100.0, frame.centre.y), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x + 100.0, frame.centre.y)); assert_eq!(object(&editor, 0).angle(), 90.0); assert_eq!(object(&editor, 0).centre(), frame.centre); @@ -318,52 +599,108 @@ fn several_objects_turn_around_their_frame() { editor.release(at(150.0, 130.0)); let frame = editor.frame().unwrap(); - drag( - &mut editor, - frame.grip(Grip::Rotate), - at(frame.centre.x, frame.centre.y + 100.0), - ); + drag(&mut editor, frame.grip(Grip::Rotate), at(frame.centre.x, frame.centre.y + 100.0)); assert_eq!(object(&editor, 0).angle(), 180.0); assert!(object(&editor, 0).centre().x > object(&editor, 1).centre().x); } #[test] -fn a_hue_is_for_what_is_drawn_next_and_what_is_selected() { - let mut editor = with_a_rectangle(); +fn a_hue_is_for_what_is_drawn_next() { + let mut editor = editor(); + editor.set_hue(Hue::Blue); + editor.set_tool(Tool::Rectangle); + drag(&mut editor, at(300.0, 300.0), at(340.0, 340.0)); + assert_eq!(editor.hue(), Hue::Blue); + assert_eq!(object(&editor, 0).hue(), Hue::Blue); +} + +#[test] +fn a_hue_is_for_what_is_selected_now_a_step_of_the_history() { + let mut editor = with_a_rectangle(); editor.set_hue(Hue::Red); assert_eq!(object(&editor, 0).hue(), Hue::Red); + editor.undo(); + assert_eq!(object(&editor, 0).hue(), Hue::Ink); +} + +#[test] +fn with_nothing_selected_a_hue_changes_nothing_drawn() { + let mut editor = with_a_rectangle(); editor.deselect(); - editor.set_hue(Hue::Blue); - assert_eq!(object(&editor, 0).hue(), Hue::Red); - editor.set_tool(Tool::Rectangle); - drag(&mut editor, at(300.0, 300.0), at(340.0, 340.0)); - assert_eq!(object(&editor, 1).hue(), Hue::Blue); - assert_eq!(editor.hue(), Hue::Blue); + editor.take_unsaved(); + editor.set_hue(Hue::Red); + + assert_eq!(object(&editor, 0).hue(), Hue::Ink); + assert!(!editor.take_unsaved()); } #[test] -fn undo_and_redo_walk_the_history_and_a_change_drops_what_was_undone() { +fn undo_and_redo_walk_the_history() { let mut editor = with_a_rectangle(); drag(&mut editor, at(150.0, 130.0), at(250.0, 130.0)); editor.undo(); assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); - assert!(editor.can_redo()); - editor.redo(); assert_eq!(object(&editor, 0).centre(), at(250.0, 130.0)); - + assert!(!editor.can_redo()); editor.undo(); editor.undo(); assert_eq!(editor.shapes(), 0); assert!(!editor.can_undo()); +} + +#[test] +fn past_either_end_of_the_history_nothing_changes() { + let mut editor = with_a_rectangle(); + editor.take_unsaved(); editor.redo(); + assert_eq!(editor.shapes(), 1); + assert!(!editor.take_unsaved()); + + let mut empty = self::editor(); + empty.undo(); + assert!(!empty.take_unsaved()); +} + +#[test] +fn what_is_undone_is_to_save_and_drops_the_selection() { + let mut editor = with_a_rectangle(); + editor.take_unsaved(); + let shown = editor.revision(); + + editor.undo(); + assert!(editor.selected.is_empty()); + assert!(editor.take_unsaved()); + assert!(editor.revision() > shown); +} + +#[test] +fn what_is_undone_while_a_text_is_typed_into_leaves_it() { + let mut editor = with_a_text("one"); + let inside = object(&editor, 0).centre(); + drag(&mut editor, inside, inside); + assert!(editor.editing().is_some()); + + editor.undo(); + assert!(editor.editing().is_none()); +} + +#[test] +fn a_change_drops_what_was_undone() { + let mut editor = with_a_rectangle(); + drag(&mut editor, at(150.0, 130.0), at(250.0, 130.0)); + editor.undo(); + assert!(editor.can_redo()); + editor.set_tool(Tool::Ellipse); drag(&mut editor, at(0.0, 0.0), at(40.0, 40.0)); assert!(!editor.can_redo()); + editor.undo(); + assert_eq!(object(&editor, 0).centre(), at(150.0, 130.0)); } #[test] @@ -371,11 +708,7 @@ fn the_history_keeps_sixty_states() { let mut editor = with_a_rectangle(); for step in 0..70 { let from = object(&editor, 0).centre(); - drag( - &mut editor, - from, - at(from.x + 1.0, from.y + f64::from(step % 2)), - ); + drag(&mut editor, from, at(from.x + 1.0, from.y + f64::from(step % 2))); } let mut back = 0; @@ -409,10 +742,7 @@ fn a_click_leaves_an_arrow_where_it_stands_until_its_shape_moves() { let mut editor = Editor::open(body, Arc::new(fonts())); drag(&mut editor, at(100.0, 100.0), at(100.0, 100.0)); - assert_eq!( - object(&editor, 1).ends(), - Some([300.0, 100.0, 400.0, 100.0]) - ); + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); assert_ne!(object(&editor, 1).ends().unwrap()[0], 300.0); @@ -421,13 +751,46 @@ fn a_click_leaves_an_arrow_where_it_stands_until_its_shape_moves() { #[test] fn escape_gives_back_the_selection_a_tool_took_over() { let mut editor = with_a_rectangle(); - editor.set_tool(Tool::Arrow); - assert!(editor.selected().is_empty()); + assert!(editor.selected.is_empty()); + editor.set_tool(Tool::Pen); editor.back_to_selection(); assert_eq!(editor.tool(), Tool::Select); - assert_eq!(editor.selected(), [0]); + assert_eq!(editor.selected, [0]); +} + +#[test] +fn the_selection_kept_goes_with_what_is_drawn_erased_or_undone_since() { + let draws = |editor: &mut Editor| { + editor.set_tool(Tool::Ellipse); + drag(editor, at(400.0, 0.0), at(440.0, 40.0)); + editor.deselect(); + }; + let erases = |editor: &mut Editor| { + editor.set_tool(Tool::Eraser); + drag(editor, at(150.0, 130.0), at(150.0, 130.0)); + }; + let undoes = |editor: &mut Editor| { + editor.set_tool(Tool::Pen); + editor.undo(); + }; + let types = |editor: &mut Editor| { + editor.set_tool(Tool::Text); + editor.press(at(400.0, 0.0), false); + editor.leave_text(); + }; + for since in [draws as fn(&mut Editor), erases, undoes, types] { + let mut editor = with_a_rectangle(); + since(&mut editor); + editor.back_to_selection(); + assert!(editor.selected.is_empty()); + } +} + +#[test] +fn a_selection_dropped_is_told_once() { + let mut editor = with_a_rectangle(); assert!(editor.deselect()); assert!(!editor.deselect()); @@ -543,7 +906,7 @@ fn ends(editor: &Editor) -> Ends { #[test] fn an_arrow_selected_alone_shows_its_two_ends_and_no_frame() { let editor = joined(); - assert_eq!(editor.selected(), [2]); + assert_eq!(editor.selected, [2]); assert!(editor.frame().is_none()); let [(_, from), (_, to)] = editor.arrow_ends().unwrap(); assert_eq!((from, to), (at(101.0, 30.0), at(299.0, 30.0))); @@ -598,10 +961,7 @@ fn the_shape_an_end_would_hold_is_told_while_an_arrow_is_drawn_or_an_end_moved() editor.set_tool(Tool::Arrow); assert!(editor.attaching(on_the_second).is_some()); editor.press(at(50.0, 30.0), false); - assert!( - editor.attaching(at(60.0, 30.0)).is_none(), - "not the one it starts on" - ); + assert!(editor.attaching(at(60.0, 30.0)).is_none(), "not the one it starts on"); editor.release(at(200.0, 200.0)); let end = editor.arrow_ends().unwrap()[1].1; @@ -633,27 +993,15 @@ fn an_arrow_follows_a_shape_resized_and_rotated() { drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); // Its left side pulled 50 to the left. drag(&mut editor, at(299.0, 30.0), at(249.0, 30.0)); - assert!( - (ends(&editor)[2] - 249.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 249.0).abs() < 1.0, "{:?}", ends(&editor)); let mut editor = joined(); drag(&mut editor, at(350.0, 30.0), at(350.0, 30.0)); let frame = editor.frame().unwrap(); let handle = frame.grip(Grip::Rotate); - drag( - &mut editor, - handle, - at(frame.centre.x + 200.0, frame.centre.y), - ); + drag(&mut editor, handle, at(frame.centre.x + 200.0, frame.centre.y)); // Turned a quarter, it is 62 wide: its left side came closer to its centre. - assert!( - (ends(&editor)[2] - 319.0).abs() < 1.5, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 319.0).abs() < 1.5, "{:?}", ends(&editor)); } #[test] @@ -661,11 +1009,7 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { let mut editor = joined(); drag(&mut editor, at(299.0, 30.0), at(352.0, 64.0)); assert_eq!(object(&editor, 2).to(), object(&editor, 1).id()); - assert_eq!( - ends(&editor)[2..], - [350.0, 61.0], - "the middle of its bottom" - ); + assert_eq!(ends(&editor)[2..], [350.0, 61.0], "the middle of its bottom"); let stored = editor.body(); assert!(stored.contains(r#""toAnchor":"bottom""#), "{stored}"); assert!(!stored.contains("fromAnchor")); @@ -674,19 +1018,11 @@ fn an_end_let_go_on_the_middle_of_a_side_stays_on_it() { drag(&mut editor, at(380.0, 10.0), at(380.0, 110.0)); assert_eq!(ends(&editor)[2..], [350.0, 161.0]); drag(&mut editor, at(401.0, 130.0), at(501.0, 130.0)); - assert!( - (ends(&editor)[2] - 400.0).abs() < 1.0, - "{:?}", - ends(&editor) - ); + assert!((ends(&editor)[2] - 400.0).abs() < 1.0, "{:?}", ends(&editor)); let mut reopened = Editor::open(&editor.body(), Arc::new(fonts())); drag(&mut reopened, at(480.0, 150.0), at(480.0, 50.0)); - assert_eq!( - ends(&reopened)[3], - 61.0, - "read back, it is on the same point" - ); + assert_eq!(ends(&reopened)[3], 61.0, "read back, it is on the same point"); } #[test] @@ -736,3 +1072,186 @@ fn an_anchor_no_code_here_wrote_is_the_edge_and_stays_stored() { drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); assert!(editor.body().contains(r#""fromAnchor":"corner""#)); } + +#[test] +fn a_shape_drawn_has_the_stroke_and_the_corners_of_its_kind() { + for (tool, kind, corners) in [ + (Tool::Rectangle, Kind::Rect, r#""rx":6,"ry":6"#), + (Tool::Ellipse, Kind::Ellipse, r#""rx":50,"ry":30"#), + (Tool::Diamond, Kind::Polygon, r#""points":["#), + ] { + let mut editor = editor(); + editor.set_tool(tool); + drag(&mut editor, at(0.0, 0.0), at(100.0, 60.0)); + let body = editor.body(); + + assert_eq!(object(&editor, 0).kind(), kind); + assert_eq!(object(&editor, 0).stroke_width(), 2.0); + assert!(object(&editor, 0).stroke_uniform()); + assert!(body.contains(corners), "{body}"); + assert!(body.contains(r#""originX":"center","originY":"center""#)); + assert!(body.contains(r#""type":"#) && body.contains(r#""version":"7.4.0","originX""#)); + } +} + +#[test] +fn a_shape_is_shown_while_it_is_dragged() { + let mut editor = editor(); + editor.set_tool(Tool::Rectangle); + editor.press(at(0.0, 0.0), false); + let shown = editor.revision(); + editor.drag(at(40.0, 20.0)); + + assert_eq!((object(&editor, 0).width(), object(&editor, 0).height()), (40.0, 20.0)); + assert!(editor.revision() > shown); + assert!(!editor.can_undo(), "a step of the history once let go"); +} + +/// On the screen: closer, the same click covers less of the scene. +#[test] +fn a_click_is_told_from_a_drag_on_the_screen() { + for (scale, dragged, size) in [ + (1.0, (5.0, 5.0), (140.0, 80.0)), + (1.0, (6.0, 1.0), (6.0, 1.0)), + (1.0, (1.0, 6.0), (1.0, 6.0)), + (4.0, (2.0, 2.0), (2.0, 2.0)), + (0.5, (11.0, 11.0), (140.0, 80.0)), + ] { + let mut editor = editor(); + editor.set_scale(scale); + editor.set_tool(Tool::Rectangle); + drag(&mut editor, at(0.0, 0.0), at(dragged.0, dragged.1)); + let shape = object(&editor, 0); + assert_eq!((shape.width(), shape.height()), size, "{scale} {dragged:?}"); + } +} + +#[test] +fn a_handle_is_taken_from_as_far_on_the_screen_whatever_the_scale() { + for (scale, away, taken) in [(1.0, 8.0, true), (1.0, 8.5, false), (2.0, 4.0, true), (2.0, 4.5, false)] { + let mut editor = with_a_rectangle(); + editor.set_scale(scale); + let corner = editor.frame().unwrap().grip(Grip::BottomRight); + let near = at(corner.x + away, corner.y + away); + drag(&mut editor, near, at(near.x + 100.0, near.y + 100.0)); + assert_eq!(object(&editor, 0).scale_x() > 1.0, taken, "{scale} {away}"); + } +} + +#[test] +fn an_end_of_an_arrow_is_taken_from_as_far_on_the_screen() { + for (dx, dy, taken) in [(8.0, 0.0, true), (0.0, 8.0, true), (8.5, 0.0, false), (0.0, 8.5, false)] { + let mut editor = joined(); + let end = at(299.0 + dx, 30.0 + dy); + editor.press(end, false); + editor.drag(at(250.0, 300.0)); + let moved = ends(&editor)[2..] == [250.0, 300.0]; + assert_eq!(moved, taken, "{dx} {dy}"); + } +} + +#[test] +fn the_rotation_handle_stands_as_high_on_the_screen_whatever_the_scale() { + let mut editor = with_a_rectangle(); + assert_eq!(editor.frame().unwrap().grip(Grip::Rotate), at(150.0, 59.0)); + + editor.set_scale(2.0); + assert_eq!(editor.frame().unwrap().grip(Grip::Rotate), at(150.0, 79.0)); +} + +#[test] +fn the_frame_of_a_turned_shape_turns_with_it() { + let mut editor = with_a_rectangle(); + let handle = editor.frame().unwrap().grip(Grip::Rotate); + drag(&mut editor, handle, at(250.0, 130.0)); + + let corners = editor.frame().unwrap().corners(); + for (corner, (x, y)) in + corners + .into_iter() + .zip([(181.0, 79.0), (181.0, 181.0), (119.0, 181.0), (119.0, 79.0)]) + { + assert!((corner.x - x).abs() < 1e-6 && (corner.y - y).abs() < 1e-6, "{corner:?}"); + } +} + +#[test] +fn a_turned_shape_is_scaled_along_its_own_sides() { + let mut editor = with_a_rectangle(); + let handle = editor.frame().unwrap().grip(Grip::Rotate); + drag(&mut editor, handle, at(250.0, 130.0)); + // Its right side is now at the bottom. + drag(&mut editor, at(150.0, 181.0), at(150.0, 283.0)); + + let shape = object(&editor, 0); + assert_eq!((shape.scale_x(), shape.scale_y()), (2.0, 1.0)); +} + +#[test] +fn where_an_arrow_is_held_is_told_from_as_far_as_its_side_is_reached() { + let mut editor = joined(); + editor.set_tool(Tool::Arrow); + for (dx, dy, told) in [(8.0, 0.0, true), (8.5, 0.0, false), (0.0, 8.0, true), (0.0, 8.5, false)] { + let chosen = editor.attaching(at(401.0 + dx, 30.0 + dy)).and_then(|found| found.chosen); + assert_eq!(chosen, told.then_some(at(401.0, 30.0)), "{dx} {dy}"); + } +} + +#[test] +fn a_pen_line_holds_an_arrow_by_its_edge_alone() { + let mut editor = with_the_pen(&[at(0.0, 0.0), at(50.0, 50.0), at(100.0, 0.0)]); + editor.set_tool(Tool::Arrow); + + let found = editor.attaching(at(50.0, 20.0)).unwrap(); + assert!(found.points.is_empty() && found.chosen.is_none()); +} + +#[test] +fn an_arrow_bound_to_a_shape_that_is_gone_stays_where_it_is() { + let body = r#"{"scene":{"objects":[ + {"type":"Rect","id":"a","left":100,"top":100,"width":100,"height":100}, + {"type":"Path","id":"b","from":"gone","ends":[300,100,400,100],"path":[["M",300,100],["L",400,100]]} + ]}}"#; + let mut editor = Editor::open(body, Arc::new(fonts())); + drag(&mut editor, at(100.0, 100.0), at(100.0, 110.0)); + + assert_eq!(object(&editor, 1).ends(), Some([300.0, 100.0, 400.0, 100.0])); +} + +#[test] +fn every_gesture_shows_what_it_changes() { + let mut editor = with_a_rectangle(); + for (tool, from, to) in [ + (Tool::Select, at(150.0, 130.0), at(160.0, 130.0)), + (Tool::Select, at(600.0, 600.0), at(650.0, 650.0)), + (Tool::Pen, at(0.0, 0.0), at(50.0, 0.0)), + (Tool::Arrow, at(0.0, 300.0), at(50.0, 300.0)), + (Tool::Eraser, at(600.0, 0.0), at(650.0, 0.0)), + ] { + editor.set_tool(tool); + editor.press(from, false); + let pressed = editor.revision(); + editor.drag(to); + assert!(editor.revision() > pressed, "{tool:?}"); + editor.release(to); + } +} + +#[test] +fn nothing_pressed_a_drag_and_a_release_do_nothing() { + let mut editor = with_a_rectangle(); + let shown = editor.revision(); + editor.drag(at(0.0, 0.0)); + editor.release(at(0.0, 0.0)); + + assert_eq!(editor.revision(), shown); +} + +#[test] +fn the_eraser_tells_what_it_would_take_by_its_frame() { + let editor = with_a_rectangle(); + let frame = editor.erasable(at(150.0, 130.0)).unwrap(); + + assert_eq!((frame.centre, frame.width, frame.height), (at(150.0, 130.0), 102.0, 62.0)); + assert!(editor.erasable(at(0.0, 0.0)).is_none()); +} diff --git a/crates/drawing/src/geometry.rs b/crates/drawing/src/geometry.rs index 360f0237a..6428831d9 100644 --- a/crates/drawing/src/geometry.rs +++ b/crates/drawing/src/geometry.rs @@ -41,10 +41,7 @@ pub fn arrow_path([x1, y1, x2, y2]: Ends) -> [PathCommand; 6] { let reach = HEAD.min(length); let (foot_x, foot_y) = (x2 - ux * reach, y2 - uy * reach); let half = reach / 2.0; - let at = |x: f64, y: f64| Point { - x: (x * 10.0).round() / 10.0, - y: (y * 10.0).round() / 10.0, - }; + let at = |x: f64, y: f64| Point { x: (x * 10.0).round() / 10.0, y: (y * 10.0).round() / 10.0 }; [ PathCommand::Move(at(x1, y1)), PathCommand::Line(at(foot_x, foot_y)), @@ -65,10 +62,7 @@ pub(crate) fn number(value: f64) -> String { impl Box { pub fn centre(&self) -> Point { - Point { - x: self.left + self.width / 2.0, - y: self.top + self.height / 2.0, - } + Point { x: self.left + self.width / 2.0, y: self.top + self.height / 2.0 } } } @@ -80,17 +74,10 @@ pub fn edge_point(bounds: &Box, toward: Point) -> Point { return centre; } let along = |half: f64, delta: f64| { - if delta == 0.0 { - f64::INFINITY - } else { - half / delta.abs() - } + if delta == 0.0 { f64::INFINITY } else { half / delta.abs() } }; let scale = along(bounds.width / 2.0, dx).min(along(bounds.height / 2.0, dy)); - Point { - x: centre.x + dx * scale, - y: centre.y + dy * scale, - } + Point { x: centre.x + dx * scale, y: centre.y + dy * scale } } /// What an end of an arrow holds on to. @@ -143,22 +130,10 @@ pub fn drag_box(from: Point, to: Point) -> Box { pub fn diamond_points(width: f64, height: f64) -> [Point; 4] { [ - Point { - x: width / 2.0, - y: 0.0, - }, - Point { - x: width, - y: height / 2.0, - }, - Point { - x: width / 2.0, - y: height, - }, - Point { - x: 0.0, - y: height / 2.0, - }, + Point { x: width / 2.0, y: 0.0 }, + Point { x: width, y: height / 2.0 }, + Point { x: width / 2.0, y: height }, + Point { x: 0.0, y: height / 2.0 }, ] } @@ -175,12 +150,7 @@ pub fn scene_box(boxes: &[Box], margin: f64) -> Option { let top = boxes.iter().map(|b| b.top).reduce(f64::min)? - margin; let right = boxes.iter().map(|b| b.left + b.width).reduce(f64::max)? + margin; let bottom = boxes.iter().map(|b| b.top + b.height).reduce(f64::max)? + margin; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } /// What the commands of a path cover, curves to their furthest; `None` for no point at all. @@ -219,10 +189,7 @@ pub fn smooth_path(points: &[Point]) -> Option> { for pair in points.windows(2) { let (control, next) = (pair[0], pair[1]); if control != next { - let middle = Point { - x: f64::midpoint(control.x, next.x), - y: f64::midpoint(control.y, next.y), - }; + let middle = Point { x: f64::midpoint(control.x, next.x), y: f64::midpoint(control.y, next.y) }; path.push(PathCommand::Quad(control, middle)); } } @@ -249,10 +216,8 @@ fn decimated(points: &[Point]) -> Vec { /// Where a curve turns, on each axis it turns on, as a point of the box around it. fn furthest(from: Point, control: Point, to: Point) -> [Option; 2] { - let at = |t: f64| Point { - x: quadratic(from.x, control.x, to.x, t), - y: quadratic(from.y, control.y, to.y, t), - }; + let at = + |t: f64| Point { x: quadratic(from.x, control.x, to.x, t), y: quadratic(from.y, control.y, to.y, t) }; let turn = |from: f64, control: f64, to: f64| { let t = (from - control) / (from - 2.0 * control + to); (t > 0.0 && t < 1.0).then(|| at(t)) @@ -271,12 +236,7 @@ pub fn points_box(points: &[Point]) -> Option { let top = points.iter().map(|point| point.y).reduce(f64::min)?; let right = points.iter().map(|point| point.x).reduce(f64::max)?; let bottom = points.iter().map(|point| point.y).reduce(f64::max)?; - Some(Box { - left, - top, - width: right - left, - height: bottom - top, - }) + Some(Box { left, top, width: right - left, height: bottom - top }) } #[cfg(test)] @@ -284,12 +244,7 @@ pub fn points_box(points: &[Point]) -> Option { mod tests { use super::*; - const BOX: Box = Box { - left: 0.0, - top: 0.0, - width: 100.0, - height: 50.0, - }; + const BOX: Box = Box { left: 0.0, top: 0.0, width: 100.0, height: 50.0 }; fn at(x: f64, y: f64) -> Point { Point { x, y } @@ -327,22 +282,10 @@ mod tests { fn each_bound_end_is_on_its_shape_facing_the_other() { let left = Held::Edge(BOX); let right = Held::Edge(Box { left: 200.0, ..BOX }); - assert_eq!( - bound_ends([0.0; 4], Some(&left), Some(&right)), - [100.0, 25.0, 200.0, 25.0] - ); - assert_eq!( - bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), - [50.0, 50.0, 50.0, 300.0] - ); - assert_eq!( - bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), - [400.0, 25.0, 300.0, 25.0] - ); - assert_eq!( - bound_ends([1.0, 2.0, 3.0, 4.0], None, None), - [1.0, 2.0, 3.0, 4.0] - ); + assert_eq!(bound_ends([0.0; 4], Some(&left), Some(&right)), [100.0, 25.0, 200.0, 25.0]); + assert_eq!(bound_ends([0.0, 0.0, 50.0, 300.0], Some(&left), None), [50.0, 50.0, 50.0, 300.0]); + assert_eq!(bound_ends([400.0, 25.0, 0.0, 0.0], None, Some(&right)), [400.0, 25.0, 300.0, 25.0]); + assert_eq!(bound_ends([1.0, 2.0, 3.0, 4.0], None, None), [1.0, 2.0, 3.0, 4.0]); } #[test] @@ -355,16 +298,19 @@ mod tests { } #[test] - fn a_drag_reads_whichever_way_it_went_and_a_diamond_has_its_corners_mid_side() { - assert_eq!( - drag_box(at(50.0, 40.0), at(10.0, 60.0)), - Box { - left: 10.0, - top: 40.0, - width: 40.0, - height: 20.0 - } - ); + fn a_drag_reads_whichever_way_it_went() { + let covered = Box { left: 10.0, top: 40.0, width: 40.0, height: 20.0 }; + for (from, to) in [ + (at(50.0, 40.0), at(10.0, 60.0)), + (at(10.0, 40.0), at(50.0, 60.0)), + (at(50.0, 60.0), at(10.0, 40.0)), + ] { + assert_eq!(drag_box(from, to), covered); + } + } + + #[test] + fn a_diamond_has_its_corners_mid_side() { assert_eq!( diamond_points(40.0, 20.0), [at(20.0, 0.0), at(40.0, 10.0), at(20.0, 20.0), at(0.0, 10.0)] @@ -372,29 +318,103 @@ mod tests { } #[test] - fn a_picture_is_scaled_and_framed() { - let wide = Box { - width: 800.0, - height: 200.0, - ..BOX - }; - assert!((picture_scale(&wide, 400.0, 2.0) - 0.5).abs() < f64::EPSILON); - assert!((picture_scale(&BOX, 1600.0, 2.0) - 2.0).abs() < f64::EPSILON); - let small = Box { - left: 150.0, - top: -20.0, - width: 10.0, - height: 10.0, - }; + fn a_picture_s_longest_side_is_brought_to_its_size_never_enlarged_too_much() { + for (width, height, scale) in + [(800.0, 200.0, 0.5), (200.0, 800.0, 0.5), (100.0, 50.0, 2.0), (0.0, 0.0, 2.0)] + { + let bounds = Box { width, height, ..BOX }; + assert_eq!(picture_scale(&bounds, 400.0, 2.0), scale, "{width} {height}"); + } + assert_eq!(picture_scale(&Box { width: 0.5, height: 0.0, ..BOX }, 400.0, 900.0), 400.0); + } + + #[test] + fn a_scene_is_framed_by_all_that_is_on_it_with_room_around() { + let small = Box { left: 150.0, top: -20.0, width: 10.0, height: 10.0 }; assert_eq!( scene_box(&[BOX, small], 10.0), - Some(Box { - left: -10.0, - top: -30.0, - width: 180.0, - height: 90.0 - }) + Some(Box { left: -10.0, top: -30.0, width: 180.0, height: 90.0 }) ); assert_eq!(scene_box(&[], MARGIN), None); } + + #[test] + fn a_path_is_covered_to_where_its_curves_turn() { + use PathCommand::{Close, Line, Move, Quad}; + + let covered = |path: &[PathCommand]| path_box(path).map(|b| [b.left, b.top, b.width, b.height]); + + assert_eq!(covered(&[Move(at(1.0, 2.0)), Line(at(5.0, 9.0)), Close]), Some([1.0, 2.0, 4.0, 7.0])); + // A curve up to its control and back: it goes half the way. + assert_eq!( + covered(&[Move(at(0.0, 0.0)), Quad(at(10.0, 20.0), at(20.0, 0.0))]), + Some([0.0, 0.0, 20.0, 10.0]) + ); + // The second curve starts where the first ended. + assert_eq!( + covered(&[ + Move(at(0.0, 0.0)), + Quad(at(5.0, 0.0), at(10.0, 0.0)), + Quad(at(20.0, 0.0), at(10.0, 10.0)) + ]), + Some([0.0, 0.0, 15.0, 10.0]) + ); + // A control between its ends turns nowhere. + assert_eq!( + covered(&[Move(at(0.0, 0.0)), Quad(at(1.0, 5.0), at(10.0, 10.0))]), + Some([0.0, 0.0, 10.0, 10.0]) + ); + assert_eq!(covered(&[Quad(at(9.0, 9.0), at(1.0, 1.0))]), Some([1.0, 1.0, 0.0, 0.0])); + assert_eq!(covered(&[Close]), None); + assert_eq!(covered(&[]), None); + } + + #[test] + fn a_line_by_hand_is_a_curve_through_the_middles_of_its_points() { + use PathCommand::{Line, Move, Quad}; + + assert_eq!( + smooth_path(&[at(0.0, 0.0), at(10.0, 0.0), at(20.0, 10.0)]), + Some(vec![ + Move(at(0.0, 0.0)), + Quad(at(0.0, 0.0), at(5.0, 0.0)), + Quad(at(10.0, 0.0), at(15.0, 5.0)), + Line(at(20.0, 10.0)), + ]) + ); + } + + /// The first and the last are kept, whatever is between. + #[test] + fn points_too_close_to_the_last_one_kept_are_dropped() { + let near = PEN_DECIMATE / 2.0; + let kept = decimated(&[ + at(0.0, 0.0), + at(near, 0.0), + at(PEN_DECIMATE, 0.0), + at(PEN_DECIMATE + near, 0.0), + at(PEN_DECIMATE * 3.0, 0.0), + at(PEN_DECIMATE * 3.0 + near, 0.0), + ]); + + assert_eq!( + kept, + [ + at(0.0, 0.0), + at(PEN_DECIMATE, 0.0), + at(PEN_DECIMATE * 3.0, 0.0), + at(PEN_DECIMATE * 3.0 + near, 0.0) + ] + ); + assert!(decimated(&[]).is_empty()); + } + + #[test] + fn a_line_that_went_nowhere_is_none() { + let here = at(3.0, 4.0); + for points in [vec![], vec![here], vec![here; 2], vec![here; 5]] { + assert_eq!(smooth_path(&points), None, "{points:?}"); + } + assert!(smooth_path(&[here, at(3.0, 5.0)]).is_some()); + } } diff --git a/crates/drawing/src/marks.rs b/crates/drawing/src/marks.rs index 7db6ec6a5..0bc1b3aad 100644 --- a/crates/drawing/src/marks.rs +++ b/crates/drawing/src/marks.rs @@ -63,14 +63,7 @@ struct Plane { } impl Plane { - const IDENTITY: Self = Self { - a: 1.0, - b: 0.0, - c: 0.0, - d: 1.0, - e: 0.0, - f: 0.0, - }; + const IDENTITY: Self = Self { a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0 }; /// Fabric's order: translate, rotate, scale, skew. fn of(object: &Object) -> Self { @@ -78,10 +71,7 @@ impl Plane { let (sin, cos) = object.angle().to_radians().sin_cos(); let (flip_x, flip_y) = object.flipped(); let mirror = |flipped: bool| if flipped { -1.0 } else { 1.0 }; - let (scale_x, scale_y) = ( - object.scale_x() * mirror(flip_x), - object.scale_y() * mirror(flip_y), - ); + let (scale_x, scale_y) = (object.scale_x() * mirror(flip_x), object.scale_y() * mirror(flip_y)); let (skew_x, skew_y) = object.skew(); let turned = Self { a: cos * scale_x, @@ -92,14 +82,8 @@ impl Plane { f: centre.y, }; turned - .then(Self { - c: skew_x.to_radians().tan(), - ..Self::IDENTITY - }) - .then(Self { - b: skew_y.to_radians().tan(), - ..Self::IDENTITY - }) + .then(Self { c: skew_x.to_radians().tan(), ..Self::IDENTITY }) + .then(Self { b: skew_y.to_radians().tan(), ..Self::IDENTITY }) } /// This plane, with `inner` inside it. @@ -115,10 +99,7 @@ impl Plane { } fn apply(self, at: Point) -> Point { - Point { - x: self.a * at.x + self.c * at.y + self.e, - y: self.b * at.x + self.d * at.y + self.f, - } + Point { x: self.a * at.x + self.c * at.y + self.e, y: self.b * at.x + self.d * at.y + self.f } } fn scale(self) -> f64 { @@ -159,11 +140,7 @@ fn add(marks: &mut Vec, object: &Object, outer: Plane, fonts: &Fonts) { } fn stroke_width(object: &Object, plane: Plane) -> f64 { - if object.stroke_uniform() { - object.stroke_width() - } else { - object.stroke_width() * plane.scale() - } + if object.stroke_uniform() { object.stroke_width() } else { object.stroke_width() * plane.scale() } } /// Round its centre, each corner an arc when it has a radius. @@ -180,10 +157,7 @@ fn rectangle(object: &Object) -> Vec { for (x, y, from) in corners { for step in 0..=CORNER_STEPS { let turned = from + FRAC_PI_2 * f64::from(step) / f64::from(CORNER_STEPS); - outline.push(Point { - x: x + radius * turned.cos(), - y: y + radius * turned.sin(), - }); + outline.push(Point { x: x + radius * turned.cos(), y: y + radius * turned.sin() }); } } outline @@ -194,10 +168,7 @@ fn ellipse(object: &Object) -> Vec { (0..ELLIPSE_STEPS) .map(|step| { let turned = TAU * f64::from(step) / f64::from(ELLIPSE_STEPS); - Point { - x: rx * turned.cos(), - y: ry * turned.sin(), - } + Point { x: rx * turned.cos(), y: ry * turned.sin() } }) .collect() } @@ -207,10 +178,7 @@ fn polygon(object: &Object) -> Vec { let middle = points_box(&points).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); points .iter() - .map(|point| Point { - x: point.x - middle.x, - y: point.y - middle.y, - }) + .map(|point| Point { x: point.x - middle.x, y: point.y - middle.y }) .collect() } @@ -218,23 +186,14 @@ fn polygon(object: &Object) -> Vec { fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { let commands = object.path(); let middle = path_box(&commands).map_or(Point { x: 0.0, y: 0.0 }, |bounds| bounds.centre()); - let on_plane = |at: Point| { - plane.apply(Point { - x: at.x - middle.x, - y: at.y - middle.y, - }) - }; + let on_plane = |at: Point| plane.apply(Point { x: at.x - middle.x, y: at.y - middle.y }); let arrow = object.ends().is_some(); let mut flush = |points: &mut Vec, closed: bool| { if points.len() > 1 { marks.push(Mark::Line { points: std::mem::take(points), closed, - fill: if closed && arrow { - Fill::Stroke - } else { - Fill::None - }, + fill: if closed && arrow { Fill::Stroke } else { Fill::None }, hue: object.hue(), width: stroke_width(object, plane), }); @@ -269,13 +228,8 @@ fn add_path(marks: &mut Vec, object: &Object, plane: Plane) { fn along_curve(from: Point, control: Point, to: Point, t: f64) -> Point { let rest = 1.0 - t; - let at = |from: f64, control: f64, to: f64| { - rest * rest * from + 2.0 * rest * t * control + t * t * to - }; - Point { - x: at(from.x, control.x, to.x), - y: at(from.y, control.y, to.y), - } + let at = |from: f64, control: f64, to: f64| rest * rest * from + 2.0 * rest * t * control + t * t * to; + Point { x: at(from.x, control.x, to.x), y: at(from.y, control.y, to.y) } } fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) { @@ -287,10 +241,7 @@ fn add_text(marks: &mut Vec, object: &Object, plane: Plane, fonts: &Fonts) for line in wrap(text, object.width(), font_size, fonts) { marks.push(Mark::Words { text: line, - at: plane.apply(Point { - x: left, - y: baseline, - }), + at: plane.apply(Point { x: left, y: baseline }), angle: plane.angle(), size: font_size * plane.scale(), hue: object.hue(), @@ -315,12 +266,7 @@ mod tests { fn line(mark: &Mark) -> (&[Point], bool, Fill) { match mark { - Mark::Line { - points, - closed, - fill, - .. - } => (points, *closed, *fill), + Mark::Line { points, closed, fill, .. } => (points, *closed, *fill), Mark::Words { .. } => panic!("words"), } } @@ -342,11 +288,7 @@ mod tests { let marks = marks_of(r#"{"type":"Rect","width":20,"height":20,"rx":5}"#); let (points, ..) = line(&marks[0]); - assert!( - points - .iter() - .all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0) - ); + assert!(points.iter().all(|at| at.x.hypot(at.y) < 10.0 * 2f64.sqrt() - 1.0)); } #[test] @@ -389,13 +331,9 @@ mod tests { Mark::Words { .. } => panic!("words"), }; + assert!((width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9); assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"scaleY":3}"#) - 6.0).abs() < 1e-9 - ); - assert!( - (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0) - .abs() - < 1e-9 + (width(r#"{"type":"Rect","strokeWidth":2,"scaleX":3,"strokeUniform":true}"#) - 2.0).abs() < 1e-9 ); } @@ -428,13 +366,45 @@ mod tests { #[test] fn a_flip_and_a_skew_reach_the_plane() { - let flipped = marks_of( - r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#, - ); + let flipped = + marks_of(r#"{"type":"Path","flipX":true,"left":0,"top":0,"path":[["M",0,0],["L",10,0]]}"#); assert!(near(line(&flipped[0]).0[0], 5.0, 0.0)); - let skewed = - marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); + let skewed = marks_of(r#"{"type":"Polygon","skewX":45,"points":[{"x":0,"y":0},{"x":0,"y":10}]}"#); assert!(near(line(&skewed[0]).0[1], 5.0, 5.0)); } + + #[test] + fn a_path_of_a_lone_point_is_not_drawn_and_each_piece_is_its_own() { + let pieces = |path: &str| { + let marks = marks_of(&format!(r#"{{"type":"Path","path":[{path}]}}"#)); + marks.iter().map(|mark| line(mark).0.len()).collect::>() + }; + + assert!(pieces(r#"["M",0,0]"#).is_empty()); + assert!(pieces(r#"["M",0,0],["Z"]"#).is_empty()); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["M",5,5],["M",6,6],["L",7,7],["L",8,8]"#), [2, 3]); + assert_eq!(pieces(r#"["M",0,0],["L",1,0],["Z"],["L",9,9],["L",8,8]"#), [2, 2]); + } + + /// Each curve starts where the one before ended, whatever it was. + #[test] + fn a_curve_starts_where_the_pen_was() { + for before in [r#"["M",10,0]"#, r#"["M",0,0],["L",10,0]"#, r#"["M",0,0],["Q",5,0,10,0]"#] { + let marks = marks_of(&format!(r#"{{"type":"Path","path":[{before},["Q",10,100,10,200]]}}"#)); + let (points, ..) = line(&marks[0]); + let x = points[points.len() - 1].x; + let curve = &points[points.len() - usize::try_from(CURVE_STEPS).unwrap()..]; + assert!(curve.iter().all(|at| (at.x - x).abs() < 1e-9), "{before}: {curve:?}"); + } + } + + /// The head of an arrow closes; a pen's line that closes is no head. + #[test] + fn a_closed_piece_is_filled_on_an_arrow_alone() { + let closed = marks_of(r#"{"type":"Path","path":[["M",0,0],["L",10,0],["L",5,5],["Z"]]}"#); + + assert!(line(&closed[0]).1); + assert_eq!(line(&closed[0]).2, Fill::None); + } } diff --git a/crates/drawing/src/picture.rs b/crates/drawing/src/picture.rs index 258bdb8ff..e65c5f835 100644 --- a/crates/drawing/src/picture.rs +++ b/crates/drawing/src/picture.rs @@ -64,24 +64,14 @@ pub fn pictures(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option

Option> { +pub fn export(drawing: &Drawing, palette: &Palette, fonts: &Fonts, format: Format) -> Option> { match format { Format::Png => png(drawing, palette, fonts, PICTURE), Format::Svg => svg(drawing, palette, fonts).map(String::into_bytes), } } -fn png( - drawing: &Drawing, - palette: &Palette, - fonts: &Fonts, - (side, most): (f64, f64), -) -> Option> { +fn png(drawing: &Drawing, palette: &Palette, fonts: &Fonts, (side, most): (f64, f64)) -> Option> { let frame = frame(drawing)?; let options = usvg::Options { font_family: fonts.family.clone(), @@ -95,15 +85,11 @@ fn png( clippy::cast_sign_loss, reason = "positive, and a picture's side at most" )] - let (width, height) = ( - (frame.width * scale).ceil() as u32, - (frame.height * scale).ceil() as u32, - ); + let (width, height) = ((frame.width * scale).ceil() as u32, (frame.height * scale).ceil() as u32); let mut pixmap = Pixmap::new(width, height)?; let drawn = tree.size(); #[expect(clippy::cast_precision_loss, reason = "a picture's side")] - let transform = - Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); + let transform = Transform::from_scale(width as f32 / drawn.width(), height as f32 / drawn.height()); resvg::render(&tree, transform, &mut pixmap.as_mut()); pixmap.encode_png().ok() } @@ -144,11 +130,8 @@ pub fn svg(drawing: &Drawing, palette: &Palette, fonts: &Fonts) -> Option return, Kind::Group => { @@ -163,12 +146,8 @@ fn write_object(out: &mut String, object: &Object, palette: &Palette, fonts: &Fo Kind::Rect | Kind::Ellipse | Kind::Polygon | Kind::Path => {} } let shape = shape(object, drawn_at); - let _ = write!( - out, - r#"<{shape} transform="{}" {}/>"#, - transform(object, drawn_at), - paint(object, palette) - ); + let _ = + write!(out, r#"<{shape} transform="{}" {}/>"#, transform(object, drawn_at), paint(object, palette)); } /// The tag and geometry of a shape, around the plane's origin: what `left` and `top` place. @@ -187,11 +166,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { number(radius * scale_y), ) } - Kind::Ellipse => format!( - r#"ellipse rx="{}" ry="{}""#, - number(width / 2.0), - number(height / 2.0) - ), + Kind::Ellipse => format!(r#"ellipse rx="{}" ry="{}""#, number(width / 2.0), number(height / 2.0)), Kind::Polygon => { let points = object.points(); let middle = points_box(&points).map(|bounds| bounds.centre()); @@ -206,10 +181,7 @@ fn shape(object: &Object, (scale_x, scale_y): (f64, f64)) -> String { .collect(); format!(r#"polygon points="{}""#, points.join(" ")) } - _ => format!( - r#"path d="{}""#, - path_data(&object.path(), (scale_x, scale_y)) - ), + _ => format!(r#"path d="{}""#, path_data(&object.path(), (scale_x, scale_y))), } } @@ -274,12 +246,7 @@ fn paint(object: &Object, palette: &Palette) -> String { fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Fonts) { let font_size = object.font_size(); - let lines = wrap( - object.text().unwrap_or_default(), - object.width(), - font_size, - fonts, - ); + let lines = wrap(object.text().unwrap_or_default(), object.width(), font_size, fonts); let step = line_step(font_size, object.line_height()); let left = -object.width() / 2.0; let top = -object.height() / 2.0 + first_baseline(font_size); @@ -293,13 +260,8 @@ fn write_text(out: &mut String, object: &Object, palette: &Palette, fonts: &Font ); let mut baseline = top; for line in lines { - let _ = write!( - out, - r#"{}"#, - number(left), - number(baseline), - escaped(&line) - ); + let _ = + write!(out, r#"{}"#, number(left), number(baseline), escaped(&line)); baseline += step; } out.push_str(""); diff --git a/crates/drawing/src/picture/tests.rs b/crates/drawing/src/picture/tests.rs index a56ae5e19..7ec7f1533 100644 --- a/crates/drawing/src/picture/tests.rs +++ b/crates/drawing/src/picture/tests.rs @@ -3,20 +3,12 @@ use crate::text::tests::fonts; fn palette() -> Palette { let each = |prefix: &str| Hue::ALL.map(|hue| format!("{prefix}-{}", hue.name())); - Palette { - stroke: each("stroke"), - fill: each("fill"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("stroke"), fill: each("fill"), paper: "#101010".to_owned() } } fn colours() -> Palette { let each = |colour: &str| [colour; 6].map(str::to_owned); - Palette { - stroke: each("#e5e7eb"), - fill: each("rgba(96, 165, 250, 0.14)"), - paper: "#101010".to_owned(), - } + Palette { stroke: each("#e5e7eb"), fill: each("rgba(96, 165, 250, 0.14)"), paper: "#101010".to_owned() } } fn scene(objects: &str) -> Drawing { @@ -59,13 +51,9 @@ fn nothing_drawn_has_no_picture() { #[test] fn the_frame_is_what_is_drawn_with_room_on_its_paper() { - let svg = - svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); + let svg = svg_of(r#"{"type":"Rect","left":100,"top":50,"width":100,"height":50,"strokeWidth":0}"#); - assert!( - svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), - "{svg}" - ); + assert!(svg.contains(r#"viewBox="26 1 148 98" width="148" height="98""#), "{svg}"); assert!(svg.contains(r##""##)); } @@ -77,14 +65,16 @@ fn each_shape_is_drawn_round_its_centre_in_its_hues_colours() { {"type":"Polygon","left":0,"top":0,"width":40,"height":20,"points":[{"x":20,"y":0},{"x":40,"y":10},{"x":20,"y":20},{"x":0,"y":10}]}"#, ); - assert!(svg.contains(r#" Option { let boxes: Vec<_> = self.objects.iter().map(Object::bounds).collect(); crate::geometry::scene_box(&boxes, 0.0) } + /// `None` for a body that holds no scene, or one whose objects are not objects: what + /// opens as a new drawing. pub fn read(content: &str) -> Option { let Value::Object(mut body) = serde_json::from_str(content).ok()? else { return None; @@ -120,11 +116,7 @@ impl Drawing { return None; }; let objects = take_objects(&mut scene)?; - Some(Self { - body, - scene, - objects, - }) + Some(Self { body, scene, objects }) } /// The body to store. @@ -152,10 +144,7 @@ fn put_objects(fields: &mut Map, objects: &[Object]) { if objects.is_empty() && !fields.contains_key(OBJECTS) { return; } - let objects = objects - .iter() - .map(|object| Value::Object(object.fields())) - .collect(); + let objects = objects.iter().map(|object| Value::Object(object.fields())).collect(); fields.insert(OBJECTS.to_owned(), Value::Array(objects)); } @@ -170,10 +159,7 @@ impl Object { /// A new object of Fabric's `kind`, in `hue`, on nothing yet. pub(crate) fn make(kind: &str, id: String, hue: Hue) -> Self { - let mut object = Self { - fields: Map::new(), - children: Vec::new(), - }; + let mut object = Self { fields: Map::new(), children: Vec::new() }; object.put("type", kind); object.put("version", FABRIC); object.put("originX", "center"); @@ -299,10 +285,7 @@ impl Object { /// ⚠️ Fabric 7 places an object by its centre: `left` and `top` are the box's middle. pub fn centre(&self) -> Point { - Point { - x: self.number("left", 0.0), - y: self.number("top", 0.0), - } + Point { x: self.number("left", 0.0), y: self.number("top", 0.0) } } pub fn width(&self) -> f64 { @@ -391,15 +374,9 @@ impl Object { let stroke = self.stroke_width(); let (scale_x, scale_y) = (self.scale_x().abs(), self.scale_y().abs()); if self.stroke_uniform() { - ( - self.width() * scale_x + stroke, - self.height() * scale_y + stroke, - ) + (self.width() * scale_x + stroke, self.height() * scale_y + stroke) } else { - ( - (self.width() + stroke) * scale_x, - (self.height() + stroke) * scale_y, - ) + ((self.width() + stroke) * scale_x, (self.height() + stroke) * scale_y) } } @@ -410,17 +387,9 @@ impl Object { let (sin, cos) = self.angle().to_radians().sin_cos(); let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(x, y)| { let (x, y) = (x * width / 2.0, y * height / 2.0); - Point { - x: centre.x + x * cos - y * sin, - y: centre.y + x * sin + y * cos, - } + Point { x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos } }); - points_box(&corners).unwrap_or(Box { - left: centre.x, - top: centre.y, - width: 0.0, - height: 0.0, - }) + points_box(&corners).unwrap_or(Box { left: centre.x, top: centre.y, width: 0.0, height: 0.0 }) } /// Whether a point falls on it: its whole box, as Fabric finds a target, not its ink. @@ -437,10 +406,7 @@ impl Object { } fn number(&self, name: &str, otherwise: f64) -> f64 { - self.fields - .get(name) - .and_then(Value::as_f64) - .unwrap_or(otherwise) + self.fields.get(name).and_then(Value::as_f64).unwrap_or(otherwise) } fn list(&self, name: &str, read: impl Fn(&Value) -> Option) -> Vec { @@ -459,21 +425,11 @@ fn stored(value: f64) -> Value { } fn point_of(value: &Value) -> Option { - Some(Point { - x: value.get("x")?.as_f64()?, - y: value.get("y")?.as_f64()?, - }) + Some(Point { x: value.get("x")?.as_f64()?, y: value.get("y")?.as_f64()? }) } impl Hue { - pub const ALL: [Self; 6] = [ - Self::Ink, - Self::Blue, - Self::Green, - Self::Amber, - Self::Red, - Self::Purple, - ]; + pub const ALL: [Self; 6] = [Self::Ink, Self::Blue, Self::Green, Self::Amber, Self::Red, Self::Purple]; pub fn name(self) -> &'static str { match self { @@ -488,10 +444,7 @@ impl Hue { /// A name no theme paints is ink, as an object with none. fn named(name: &str) -> Self { - Self::ALL - .into_iter() - .find(|hue| hue.name() == name) - .unwrap_or_default() + Self::ALL.into_iter().find(|hue| hue.name() == name).unwrap_or_default() } } @@ -514,12 +467,8 @@ impl PathCommand { fn read(value: &Value) -> Option { let parts = value.as_array()?; - let at = |index: usize| { - Some(Point { - x: parts.get(index)?.as_f64()?, - y: parts.get(index + 1)?.as_f64()?, - }) - }; + let at = + |index: usize| Some(Point { x: parts.get(index)?.as_f64()?, y: parts.get(index + 1)?.as_f64()? }); match parts.first()?.as_str()? { "M" => Some(Self::Move(at(1)?)), "L" => Some(Self::Line(at(1)?)), diff --git a/crates/drawing/src/scene/tests.rs b/crates/drawing/src/scene/tests.rs index f82d8d0a6..4134c9a04 100644 --- a/crates/drawing/src/scene/tests.rs +++ b/crates/drawing/src/scene/tests.rs @@ -59,11 +59,7 @@ fn a_body_with_no_scene_opens_as_a_new_drawing() { #[test] fn each_object_reads_as_its_kind_and_hue() { let drawing = drawn(); - let read: Vec<_> = drawing - .objects - .iter() - .map(|object| (object.kind(), object.hue())) - .collect(); + let read: Vec<_> = drawing.objects.iter().map(|object| (object.kind(), object.hue())).collect(); assert_eq!( read, @@ -111,19 +107,12 @@ fn an_object_is_placed_by_its_centre_with_fabrics_transform() { #[test] fn a_field_left_out_reads_as_fabrics_default() { let drawing = - Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#) - .unwrap(); + Drawing::read(r#"{"scene":{"objects":[{"type":"Textbox","hue":"teal","ends":[1,2]}]}}"#).unwrap(); let object = &drawing.objects[0]; assert_eq!(object.centre(), at(0.0, 0.0)); assert_eq!( - [ - object.scale_x(), - object.scale_y(), - object.angle(), - object.stroke_width(), - object.font_size(), - ], + [object.scale_x(), object.scale_y(), object.angle(), object.stroke_width(), object.font_size(),], [1.0, 1.0, 0.0, 1.0, 40.0] ); assert_eq!(object.hue(), Hue::Ink); @@ -139,14 +128,8 @@ fn an_arrow_holds_its_ends_its_shapes_and_its_path() { assert_eq!(arrow.from(), Some("rect-1")); assert_eq!(arrow.to(), Some("ellipse-1")); - assert_eq!( - arrow.ends().map(|ends| ends[0]), - Some(240.000_000_000_000_03) - ); - assert_eq!( - arrow.path().first(), - Some(&PathCommand::Move(at(240.0, 90.1))) - ); + assert_eq!(arrow.ends().map(|ends| ends[0]), Some(240.000_000_000_000_03)); + assert_eq!(arrow.path().first(), Some(&PathCommand::Move(at(240.0, 90.1)))); assert_eq!(arrow.path().last(), Some(&PathCommand::Close)); } @@ -167,8 +150,7 @@ fn a_freehand_line_is_read_with_its_curves() { #[test] fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { - let body = - r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; + let body = r#"{"scene":{"objects":[{"type":"Path","path":[["M",1,2],["C",1,2,3,4,5,6],["L",3]]}]}}"#; let drawing = Drawing::read(body).unwrap(); assert_eq!(drawing.objects[0].path(), [PathCommand::Move(at(1.0, 2.0))]); @@ -179,25 +161,10 @@ fn a_path_command_the_app_never_wrote_is_not_drawn_and_stays_stored() { fn a_diamond_keeps_its_corners_a_text_its_words_a_group_its_children() { let drawing = drawn(); - assert_eq!( - drawing.objects[2].points(), - [ - at(60.0, 0.0), - at(120.0, 40.0), - at(60.0, 80.0), - at(0.0, 40.0) - ] - ); - assert_eq!( - drawing.objects[5].text(), - Some("API gateway\nsits in front of « everything »") - ); + assert_eq!(drawing.objects[2].points(), [at(60.0, 0.0), at(120.0, 40.0), at(60.0, 80.0), at(0.0, 40.0)]); + assert_eq!(drawing.objects[5].text(), Some("API gateway\nsits in front of « everything »")); assert_eq!(drawing.objects[5].font_size(), 18.0); - let inside: Vec<_> = drawing.objects[6] - .children - .iter() - .map(Object::kind) - .collect(); + let inside: Vec<_> = drawing.objects[6].children.iter().map(Object::kind).collect(); assert_eq!(inside, [Kind::Rect, Kind::Textbox]); } @@ -215,18 +182,105 @@ fn an_object_taken_away_leaves_the_rest_as_stored() { drawing.objects.remove(0); - assert_eq!( - drawing.write(), - r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"# - ); + assert_eq!(drawing.write(), r#"{"version":1,"scene":{"objects":[{"id":"b"}],"background":"x"}}"#); } #[test] fn the_first_object_put_on_an_empty_scene_is_stored() { let mut drawing = Drawing::read(r#"{"scene":{}}"#).unwrap(); - drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#) - .unwrap() - .objects; + drawing.objects = Drawing::read(r#"{"scene":{"objects":[{"id":"a"}]}}"#).unwrap().objects; assert_eq!(drawing.write(), r#"{"scene":{"objects":[{"id":"a"}]}}"#); } + +/// As Fabric stores one: two decimals, and no `.0`. +#[test] +fn a_number_is_stored_with_two_decimals_at_most() { + for (value, expected) in [ + (1.0, "1"), + (-0.5, "-0.5"), + (1.005_1, "1.01"), + (0.001, "0"), + (1e14, "100000000000000"), + (1e15, "1000000000000000.0"), + ] { + assert_eq!(stored(value).to_string(), expected); + } +} + +#[test] +fn an_angle_is_stored_within_one_turn() { + let mut object = Object::make("Rect", "a".to_owned(), Hue::Ink); + for (degrees, angle) in [(90.0, 90.0), (360.0, 0.0), (-90.0, 270.0), (725.0, 5.0)] { + object.set_angle(degrees); + assert_eq!(object.angle().to_string(), angle.to_string()); + } +} + +/// Its whole box, its stroke counted, turned with it. +#[test] +fn a_point_is_on_an_object_by_its_box() { + let object = |angle: f64| { + let body = format!( + r#"{{"scene":{{"objects":[{{"type":"Ellipse","left":10,"top":20,"width":98,"height":18,"strokeWidth":2,"angle":{angle}}}]}}}}"# + ); + Drawing::read(&body).unwrap().objects.remove(0) + }; + + let level = object(0.0); + for (x, y, on) in [ + (60.0, 20.0, true), + (60.1, 20.0, false), + (10.0, 30.0, true), + (10.0, 30.1, false), + (-40.0, 10.0, true), + ] { + assert_eq!(level.contains(at(x, y)), on, "{x} {y}"); + } + let turned = object(90.0); + assert!(turned.contains(at(10.0, 69.0)) && !turned.contains(at(59.0, 20.0))); +} + +#[test] +fn a_drawing_covers_all_that_is_drawn() { + let body = r#"{"scene":{"objects":[ + {"type":"Rect","left":0,"top":0,"width":10,"height":10,"strokeWidth":0}, + {"type":"Rect","left":50,"top":20,"width":20,"height":10,"strokeWidth":0}]}}"#; + let covered = Drawing::read(body).unwrap().bounds().unwrap(); + + assert_eq!( + [covered.left, covered.top, covered.width, covered.height].map(|side| side.to_string()), + ["-5", "-5", "65", "30"] + ); + assert_eq!(Drawing::empty().bounds(), None); +} + +#[test] +fn a_new_drawing_is_empty_and_read_back() { + let empty = Drawing::empty(); + + assert_eq!(empty.write(), r#"{"version":1,"scene":{"version":"7.4.0"}}"#); + let read = Drawing::read(&empty.write()).unwrap(); + assert_eq!(read.write(), empty.write()); +} + +#[test] +fn a_shape_let_go_is_null_and_its_point_goes_with_it() { + let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); + arrow.set_bound("from", Some("b")); + arrow.set_anchor("from", Some(Side::Left)); + assert_eq!((arrow.from(), arrow.anchor("from")), (Some("b"), Some(Side::Left))); + + arrow.set_bound("from", None); + assert_eq!((arrow.from(), arrow.anchor("from")), (None, None)); + assert_eq!(arrow.fields().get("from"), Some(&Value::Null)); +} + +#[test] +fn each_side_is_read_back_by_its_word() { + let mut arrow = Object::make("Path", "a".to_owned(), Hue::Ink); + for side in Side::ALL { + arrow.set_anchor("to", Some(side)); + assert_eq!(arrow.anchor("to"), Some(side)); + } +} diff --git a/crates/drawing/src/text.rs b/crates/drawing/src/text.rs index ab1505d93..448cdffe2 100644 --- a/crates/drawing/src/text.rs +++ b/crates/drawing/src/text.rs @@ -36,10 +36,7 @@ impl Fonts { .map_or_else(String::new, |(name, _)| name.clone()); database.set_sans_serif_family(family.clone()); Self { - faces: files - .iter() - .filter_map(|file| FontRef::new(file).ok()) - .collect(), + faces: files.iter().filter_map(|file| FontRef::new(file).ok()).collect(), database: Arc::new(database), family, } @@ -54,9 +51,7 @@ impl Fonts { } fn width(&self, word: &str, font_size: f64) -> f64 { - word.chars() - .map(|character| self.advance(character) * font_size) - .sum() + word.chars().map(|character| self.advance(character) * font_size).sum() } } diff --git a/crates/drawing/src/text/tests.rs b/crates/drawing/src/text/tests.rs index 9d944ebb5..6439e4de2 100644 --- a/crates/drawing/src/text/tests.rs +++ b/crates/drawing/src/text/tests.rs @@ -14,8 +14,7 @@ fn wrapped(text: &str, width: f64) -> Vec { } /// Where Fabric's lines, in a browser, kerned, break elsewhere than these. -const KERNED_ELSEWHERE: [&str; 1] = - ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; +const KERNED_ELSEWHERE: [&str; 1] = ["The quick brown fox jumps over the lazy dog, twice over, then rests"]; #[test] fn the_lines_are_those_fabric_broke_in_a_browser() { @@ -42,10 +41,7 @@ fn the_lines_are_those_fabric_broke_in_a_browser() { #[test] fn a_word_is_never_broken_and_widens_the_box() { - assert_eq!( - wrapped("supercalifragilistic ok", 10.0), - ["supercalifragilistic", "ok"] - ); + assert_eq!(wrapped("supercalifragilistic ok", 10.0), ["supercalifragilistic", "ok"]); } #[test] @@ -64,3 +60,16 @@ fn the_baselines_are_fabrics() { assert!((line_step(18.0, 1.16) - 23.5944).abs() < 1e-9); assert!((first_baseline(18.0) - 15.82452).abs() < 1e-9); } + +/// Spaces that do not fit end a line; a blank line is a line. +#[test] +fn lines_break_at_spaces_and_at_line_ends() { + for (text, width, lines) in [ + ("", 180.0, vec![""]), + ("a\n\nb", 180.0, vec!["a", "", "b"]), + ("a b", 1.0, vec!["a", "b"]), + ("ab cd", 1000.0, vec!["ab cd"]), + ] { + assert_eq!(wrapped(text, width), lines, "{text:?}"); + } +} diff --git a/crates/engine/benches/commands.rs b/crates/engine/benches/commands.rs index 264fd2427..034290ad4 100644 --- a/crates/engine/benches/commands.rs +++ b/crates/engine/benches/commands.rs @@ -77,10 +77,7 @@ fn whole_corpus_read(c: &mut Criterion) { // Narrowed in SQL to the 160 pinned notes: what a filtered query pays for its side tables. group.bench_function("query_notes, pinned only", |b| { - let pinned = NotesQuery { - filter: NoteFilter::Pinned, - ..query("") - }; + let pinned = NotesQuery { filter: NoteFilter::Pinned, ..query("") }; b.iter(|| black_box(run_query(&mut corpus, &pinned))); }); @@ -97,10 +94,7 @@ fn single_write(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - title: Some(format!("Retitled {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitled {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -122,10 +116,7 @@ fn body_writes(c: &mut Criterion) { // A full history, so every save below also rotates the oldest body out. for kept in 0..=engine::notes::revision::KEEP { - let patch = NotePatch { - content: Some(format!("{body}\n-- {kept}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- {kept}")), ..NotePatch::default() }; store::update(&mut corpus.connection, &id, &patch, now()).expect("a write"); } @@ -133,10 +124,7 @@ fn body_writes(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let patch = NotePatch { - content: Some(format!("{body}\n-- saved {at}")), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(format!("{body}\n-- saved {at}")), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -145,10 +133,7 @@ fn body_writes(c: &mut Criterion) { let mut pinned = false; b.iter(|| { pinned = !pinned; - let patch = NotePatch { - pinned: Some(pinned), - ..NotePatch::default() - }; + let patch = NotePatch { pinned: Some(pinned), ..NotePatch::default() }; black_box(store::update(&mut corpus.connection, &id, &patch, now()).expect("a write")); }); }); @@ -164,10 +149,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("tag_notes", |b| { b.iter(|| { - black_box( - store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]) - .expect("a batch"), - ); + black_box(store::tag_many(&mut corpus.connection, &ids, &["bulk".to_string()]).expect("a batch")); }); }); @@ -183,9 +165,7 @@ fn bulk(c: &mut Criterion) { group.bench_function("delete_notes then restore_notes", |b| { b.iter(|| { store::trash::trash_many(&mut corpus.connection, &ids, now()).expect("a trashing"); - black_box( - store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration"), - ); + black_box(store::trash::restore_many(&mut corpus.connection, &ids).expect("a restoration")); }); }); @@ -209,9 +189,7 @@ fn aggregation(c: &mut Criterion) { group.bench_function("list_global_placeholders", |b| { b.iter(|| { - black_box( - store::global_placeholder_values(&mut corpus.connection).expect("the globals"), - ); + black_box(store::global_placeholder_values(&mut corpus.connection).expect("the globals")); }); }); @@ -227,14 +205,9 @@ fn corpus_rewrite(c: &mut Criterion) { let mut at = 0u32; b.iter(|| { at += 1; - let (from, into) = if at.is_multiple_of(2) { - ("ops", "operations") - } else { - ("operations", "ops") - }; - black_box( - store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag"), - ); + let (from, into) = + if at.is_multiple_of(2) { ("ops", "operations") } else { ("operations", "ops") }; + black_box(store::retag(&mut corpus.connection, &[from.to_string()], into).expect("a retag")); }); }); @@ -259,14 +232,8 @@ fn disk(c: &mut Criterion) { let notes = store::all(&mut corpus.connection, None).expect("the corpus"); let packed = bundle::collect(&mut corpus.connection, notes).expect("a bundle"); black_box( - file::write( - &target, - &packed, - &attachments, - corpus.connection.vault(), - None, - ) - .expect("a written file"), + file::write(&target, &packed, &attachments, corpus.connection.vault(), None) + .expect("a written file"), ); }); }); @@ -275,8 +242,7 @@ fn disk(c: &mut Criterion) { b.iter(|| { let (incoming, mut payload) = file::read(&target, None).expect("a readable file"); black_box( - bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments) - .expect("a merge"), + bundle::merge(&mut corpus.connection, incoming, &mut payload, &attachments).expect("a merge"), ); }); }); @@ -304,25 +270,19 @@ fn attachment(c: &mut Criterion) { created_at: now(), }; let (db, vault) = corpus.connection.split(); - sealed::write_sealed( - vault, - &directory.join(screenshot.stored_name()), - &vec![7u8; 256 * 1024], - ) - .expect("a sealed file"); + sealed::write_sealed(vault, &directory.join(screenshot.stored_name()), &vec![7u8; 256 * 1024]) + .expect("a sealed file"); attachments::store::create(db, vault, &screenshot).expect("a record"); group.bench_function("read_attachment, 256 kB", |b| { b.iter(|| { black_box( - attachments::files::read_plain(&mut corpus.connection, "a-screenshot") - .expect("the bytes"), + attachments::files::read_plain(&mut corpus.connection, "a-screenshot").expect("the bytes"), ) }); }); - let profile = - std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); + let profile = std::env::temp_dir().join(format!("devnotes-bench-profile-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&profile).expect("a writable temporary directory"); libraries::registry::open_directory_in(&profile).expect("a registry"); @@ -348,12 +308,8 @@ fn unlock(c: &mut Criterion) { group.bench_function("Vault::derive at the shipped cost", |b| { b.iter(|| { black_box( - Vault::derive( - black_box("a passphrase"), - b"0123456789abcdef", - Cost::default(), - ) - .expect("a key"), + Vault::derive(black_box("a passphrase"), b"0123456789abcdef", Cost::default()) + .expect("a key"), ) }); }); @@ -367,11 +323,9 @@ fn cookie_jar(c: &mut Criterion) { use engine::http::cookies::{self, Change, JarCookie}; let scratch = tempfile::tempdir().expect("a temporary directory"); - let mut library = engine::db::open( - &scratch.path().join("jar.sqlite3"), - engine::db::test_vault().expect("a key"), - ) - .expect("a library"); + let mut library = + engine::db::open(&scratch.path().join("jar.sqlite3"), engine::db::test_vault().expect("a key")) + .expect("a library"); let changes: Vec = (0..500) .map(|at| { Change::Set(JarCookie { diff --git a/crates/engine/benches/corpus.rs b/crates/engine/benches/corpus.rs index 9d71d0a5a..1e760976b 100644 --- a/crates/engine/benches/corpus.rs +++ b/crates/engine/benches/corpus.rs @@ -29,9 +29,7 @@ pub(crate) const NOTES: usize = 8000; /// Roughly 13 kB of body. const LINES_PER_NOTE: usize = 200; const SPACES: usize = 4; -const TAGS: &[&str] = &[ - "angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh", -]; +const TAGS: &[&str] = &["angular", "api", "ci", "db", "docker", "git", "ops", "rust", "sql", "ssh"]; /// A database file of its own per group, erased with the guard. pub(crate) struct Corpus { @@ -82,23 +80,14 @@ fn draft(seed: usize, space_id: &str) -> NoteDraft { language: Language::Rs, content: if checklist { String::new() } else { body(seed) }, source: "Runbook".to_string(), - tags: vec![ - TAGS[seed % TAGS.len()].to_string(), - TAGS[(seed + 3) % TAGS.len()].to_string(), - ], + tags: vec![TAGS[seed % TAGS.len()].to_string(), TAGS[(seed + 3) % TAGS.len()].to_string()], pinned: seed.is_multiple_of(50), lifecycle: if seed.is_multiple_of(25) { - NoteLifecycle::Expires { - at: now() + TimeDelta::days(3), - } + NoteLifecycle::Expires { at: now() + TimeDelta::days(3) } } else { NoteLifecycle::Permanent }, - kind: if checklist { - NoteKind::Checklist - } else { - NoteKind::Snippet - }, + kind: if checklist { NoteKind::Checklist } else { NoteKind::Snippet }, priority: Priority::None, items: if checklist { (0..5u32) @@ -125,11 +114,7 @@ pub(crate) fn run_query(corpus: &mut Corpus, request: &NotesQuery) -> Vec Corpus { // The corpus is sealed like a real library, so the benchmarks measure what the // commands really pay, encryption included. - let mut connection = db::open( - &directory.join("bench.sqlite3"), - db::test_vault().expect("a key"), - ) - .expect("a fresh database"); + let mut connection = db::open(&directory.join("bench.sqlite3"), db::test_vault().expect("a key")) + .expect("a fresh database"); let space_ids: Vec = (0..SPACES) - .map(|at| { - spaces::create(&mut connection, &format!("Space {at}")) - .expect("a space") - .id - }) + .map(|at| spaces::create(&mut connection, &format!("Space {at}")).expect("a space").id) .collect(); let at = now(); let note_ids: Vec = (0..notes) .map(|seed| { let space_id = &space_ids[seed % SPACES]; - store::create(&mut connection, draft(seed, space_id), at) - .expect("a note") - .id + store::create(&mut connection, draft(seed, space_id), at).expect("a note").id }) .collect(); - Corpus { - connection, - space_ids, - note_ids, - _directory: TempDir(directory), - } + Corpus { connection, space_ids, note_ids, _directory: TempDir(directory) } } diff --git a/crates/engine/benches/corpus_size.rs b/crates/engine/benches/corpus_size.rs index a70f41796..ede273c5a 100644 --- a/crates/engine/benches/corpus_size.rs +++ b/crates/engine/benches/corpus_size.rs @@ -66,13 +66,9 @@ fn query_by_corpus_size(c: &mut Criterion) { // The same query stopped before the view is built: the gap between the two is // what the view costs, and what a LIMIT could not take away. - group.bench_with_input( - BenchmarkId::new(format!("{name}, read only"), size), - &size, - |b, _| { - b.iter(|| black_box(read_only(&mut corpus, &request))); - }, - ); + group.bench_with_input(BenchmarkId::new(format!("{name}, read only"), size), &size, |b, _| { + b.iter(|| black_box(read_only(&mut corpus, &request))); + }); } } diff --git a/crates/engine/benches/index.rs b/crates/engine/benches/index.rs index 8229dabaa..2142503bf 100644 --- a/crates/engine/benches/index.rs +++ b/crates/engine/benches/index.rs @@ -31,27 +31,16 @@ struct Bench { fn bench(size: Size) -> Bench { let mut corpus = build(size); let runtime = tokio::runtime::Runtime::new().unwrap(); - let paths = Paths { - profile: std::env::temp_dir(), - }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let paths = Paths { profile: std::env::temp_dir() }; + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); *engine.db().lock().unwrap() = corpus.library.take(); reference::attach(&engine, &corpus.note_ids); - Bench { - engine, - runtime, - corpus, - } + Bench { engine, runtime, corpus } } impl Bench { fn fill(&self) { - self.runtime - .block_on(engine::index::fill(Arc::clone(&self.engine))); + self.runtime.block_on(engine::index::fill(Arc::clone(&self.engine))); } } @@ -103,17 +92,11 @@ fn index_query(c: &mut Criterion) { let engine = &bench.engine; let mut group = c.benchmark_group(format!("index_query/{}", label(size))); group.sample_size(20); - for (name, search) in [ - ("unfiltered", ""), - ("search matching nothing", "zzzzzz"), - ("search folding accents", "etape"), - ] { + for (name, search) in + [("unfiltered", ""), ("search matching nothing", "zzzzzz"), ("search folding accents", "etape")] + { group.bench_function(name, |b| { - b.iter(|| { - black_box(run_here(engine, |e| { - query_notes(e, &query(search)).unwrap() - })) - }); + b.iter(|| black_box(run_here(engine, |e| query_notes(e, &query(search)).unwrap()))); }); } let space = bench.corpus.space_ids[0].clone(); @@ -145,10 +128,7 @@ fn index_refresh(c: &mut Criterion) { let mut n = 0_u32; b.iter(|| { n += 1; - let patch = NotePatch { - title: Some(format!("Retitrée {n}")), - ..NotePatch::default() - }; + let patch = NotePatch { title: Some(format!("Retitrée {n}")), ..NotePatch::default() }; black_box(run_here(engine, |e| update_note(e, &id, &patch).unwrap())) }); }); diff --git a/crates/engine/benches/reference.rs b/crates/engine/benches/reference.rs index d8162d08e..a7a631829 100644 --- a/crates/engine/benches/reference.rs +++ b/crates/engine/benches/reference.rs @@ -88,20 +88,13 @@ fn line(seed: usize) -> &'static str { } fn lines(seed: usize, count: usize) -> String { - (0..count) - .map(|n| line(seed + n)) - .collect::>() - .join("\n") + (0..count).map(|n| line(seed + n)).collect::>().join("\n") } fn markdown(seed: usize) -> String { let mut text = format!("# Procédure {seed}\n\n"); for section in 0..4 { - let _ = write!( - text, - "## Étape {section}\n\n{}\n\n", - lines(seed + section, 4) - ); + let _ = write!(text, "## Étape {section}\n\n{}\n\n", lines(seed + section, 4)); text.push_str("- vérifier\n- **déployer**\n- surveiller\n\n"); text.push_str("| hôte | rôle |\n| --- | --- |\n| db-1 | primaire |\n\n"); let _ = write!(text, "```sql\n{}\n```\n\n", lines(seed, 3)); @@ -169,17 +162,10 @@ fn note(n: usize, size: Size, space_id: &str, folder_id: Option<&str>) -> Note { space_id: space_id.to_string(), folder_id: folder_id.map(str::to_string), title: format!("Note {n} — étape de déploiement"), - language: if kind == NoteKind::Snippet { - LANGUAGES[n % LANGUAGES.len()] - } else { - Language::Txt - }, + language: if kind == NoteKind::Snippet { LANGUAGES[n % LANGUAGES.len()] } else { Language::Txt }, content, source: format!("API Gateway / Auth / {}", n % 50), - tags: vec![ - format!("tag-{}", n % TAGS), - format!("tag-{}", (n * 7) % TAGS), - ], + tags: vec![format!("tag-{}", n % TAGS), format!("tag-{}", (n * 7) % TAGS)], pinned: n.is_multiple_of(97), created_at: at, updated_at: at, @@ -196,30 +182,20 @@ fn uuid(n: usize) -> String { } pub(crate) fn build(size: Size) -> Reference { - let directory = - std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); + let directory = std::env::temp_dir().join(format!("devnotes-reference-{}", uuid::Uuid::new_v4())); std::fs::create_dir_all(&directory).unwrap(); let vault = engine::vault::file::create(&directory, "a passphrase", Cost::FOR_TESTS).unwrap(); let mut library = db::open(&directory.join("devnotes.sqlite3"), vault).unwrap(); let (space_ids, note_ids) = seed(&mut library, size); std::fs::create_dir_all(directory.join("attachments")).unwrap(); - Reference { - library: Some(library), - note_ids, - space_ids, - _directory: Directory(directory), - } + Reference { library: Some(library), note_ids, space_ids, _directory: Directory(directory) } } /// Everything but the attachments, into a library already open: the spaces, then the notes. pub(crate) fn seed(library: &mut Library, size: Size) -> (Vec, Vec) { let space_ids: Vec = (0..SPACES) - .map(|n| { - engine::spaces::store::create(library, &format!("Espace {n}")) - .unwrap() - .id - }) + .map(|n| engine::spaces::store::create(library, &format!("Espace {n}")).unwrap().id) .collect(); let folder_ids = folders(library, &space_ids); let note_ids = notes(library, size, &space_ids, &folder_ids); @@ -330,15 +306,10 @@ fn http(library: &mut Library) { }, }; let name = draft.name.clone(); - request_ids.push( - engine::http::store::create_request(library, &draft, &name, now()) - .unwrap() - .id, - ); + request_ids.push(engine::http::store::create_request(library, &draft, &name, now()).unwrap().id); } for n in 0..ENVIRONMENTS { - engine::http::environments::store::create(library, &format!("Environnement {n}"), now()) - .unwrap(); + engine::http::environments::store::create(library, &format!("Environnement {n}"), now()).unwrap(); } for n in 0..HISTORY { let summary = serde_json::from_value(serde_json::json!({ diff --git a/crates/engine/benches/reference_profile.rs b/crates/engine/benches/reference_profile.rs index 1b31eb68b..3bf7f5cef 100644 --- a/crates/engine/benches/reference_profile.rs +++ b/crates/engine/benches/reference_profile.rs @@ -31,11 +31,7 @@ fn main() { std::fs::create_dir_all(&profile).unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); let paths = Paths { profile }; - let engine = Arc::new(Engine::new( - paths, - Arc::new(RecordingSink::default()), - runtime.handle().clone(), - )); + let engine = Arc::new(Engine::new(paths, Arc::new(RecordingSink::default()), runtime.handle().clone())); run_here(&engine, |e| create_vault(e, secret(PASSPHRASE.to_owned()))).unwrap(); let (_, note_ids) = run_here(&engine, |e| { let mut library = e.db().lock().unwrap(); diff --git a/crates/engine/build.rs b/crates/engine/build.rs index 9c350d6c4..639443b0e 100644 --- a/crates/engine/build.rs +++ b/crates/engine/build.rs @@ -13,8 +13,8 @@ fn export_metadata() { println!("cargo:rerun-if-changed=Cargo.toml"); let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set by cargo"); - let text = fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")) - .expect("Cargo.toml is readable"); + let text = + fs::read_to_string(Path::new(&manifest_dir).join("Cargo.toml")).expect("Cargo.toml is readable"); let manifest: toml::Table = toml::from_str(&text).expect("Cargo.toml is valid TOML"); let metadata = manifest @@ -38,10 +38,7 @@ fn export_metadata() { let author = authors.split(';').next().unwrap_or_default(); println!("cargo:rustc-env=DEVNOTES_AUTHOR={author}"); - println!( - "cargo:rustc-env=DEVNOTES_RUST_VERSION={}", - pinned_toolchain(&manifest_dir) - ); + println!("cargo:rustc-env=DEVNOTES_RUST_VERSION={}", pinned_toolchain(&manifest_dir)); } /// Every page of `docs/content`, by language and name, for `docs.rs` to embed: a page added there @@ -59,11 +56,7 @@ fn list_the_documentation() { let path = file.expect("docs/content is readable").path(); if path.extension().is_some_and(|extension| extension == "md") { let id = path.file_stem().and_then(|stem| stem.to_str()); - pages.push(( - language, - id.expect("a page's name is text").to_owned(), - path, - )); + pages.push((language, id.expect("a page's name is text").to_owned(), path)); } } } @@ -72,8 +65,7 @@ fn list_the_documentation() { let mut out = String::from("const SOURCES: &[(&str, &str, &str)] = &[\n"); for (language, id, path) in pages { let path = path.to_str().expect("the repository is at a path of text"); - writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),") - .expect("a string grows"); + writeln!(out, " ({language:?}, {id:?}, include_str!({path:?})),").expect("a string grows"); } out.push_str("];\n"); let target = Path::new(&env::var("OUT_DIR").expect("cargo sets OUT_DIR")).join("docs.rs"); diff --git a/crates/engine/src/attachments.rs b/crates/engine/src/attachments.rs index 774f11918..b33e99d29 100644 --- a/crates/engine/src/attachments.rs +++ b/crates/engine/src/attachments.rs @@ -34,10 +34,7 @@ pub async fn attach_file( crate::db::run(engine, move |engine| { engine.write(|db| { let answer = store_new(note_id, file_name, &bytes, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) }) @@ -97,10 +94,7 @@ pub fn attach_image( let png = model::encode_png(width, height, rgba)?; model::validate_size(png.len() as u64, &model::png_name(file_name))?; let answer = store_new(note_id, model::png_name(file_name), &png, db)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -108,10 +102,7 @@ pub fn attach_image( pub fn delete_attachment(engine: &Engine, id: &str) -> Result<(), AppError> { engine.write(|db| { delete(db, id)?; - let changed = Changed { - attachments: true, - ..Changed::default() - }; + let changed = Changed { attachments: true, ..Changed::default() }; Ok(((), changed)) }) } @@ -130,29 +121,3 @@ fn delete(db: &Db, id: &str) -> Result<(), StorageError> { Ok(()) } - -#[cfg(test)] -mod tests { - use super::*; - use files::tests::{a_library_with_a_note, attachments_of}; - - #[test] - fn deleting_an_attachment_takes_its_file_with_it() { - let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let stored = store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap(); - - delete(&db, &stored.id).unwrap(); - - assert!(!directory.join(stored.stored_name()).exists()); - assert!( - store::list(&mut lock(&db).unwrap(), ¬e_id) - .unwrap() - .is_empty() - ); - assert!(matches!( - delete(&db, &stored.id), - Err(StorageError::AttachmentNotFound(_)) - )); - } -} diff --git a/crates/engine/src/attachments/files.rs b/crates/engine/src/attachments/files.rs index b0da4be63..7d4b1f12a 100644 --- a/crates/engine/src/attachments/files.rs +++ b/crates/engine/src/attachments/files.rs @@ -66,8 +66,8 @@ pub(crate) fn store_new( let destination = directory.join(attachment.stored_name()); let (db, vault) = connection.split(); - let stored = sealed::write_sealed(vault, &destination, bytes) - .and_then(|_| store::create(db, vault, &attachment)); + let stored = + sealed::write_sealed(vault, &destination, bytes).and_then(|_| store::create(db, vault, &attachment)); if stored.is_err() { remove_files(&directory, &[attachment.stored_name()]); } @@ -114,12 +114,9 @@ pub(crate) fn write_plain(path: &str, bytes: &[u8]) -> Result<(), StorageError> std::fs::write(path, bytes).context(path) } -fn locate( - library: &mut Library, - id: &str, -) -> Result<(Attachment, PathBuf, Arc), StorageError> { - let attachment = store::find(library, id)? - .ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; +fn locate(library: &mut Library, id: &str) -> Result<(Attachment, PathBuf, Arc), StorageError> { + let attachment = + store::find(library, id)?.ok_or_else(|| StorageError::AttachmentNotFound(id.to_string()))?; let path = directory(library).join(attachment.stored_name()); Ok((attachment, path, library.shared_vault())) @@ -129,10 +126,7 @@ fn locate( pub fn sweep_orphan_files(db: &Db) -> Result { let (directory, known) = { let mut connection = lock(db)?; - ( - directory(&connection), - store::all_stored_names(&mut connection)?, - ) + (directory(&connection), store::all_stored_names(&mut connection)?) }; let entries = std::fs::read_dir(&directory).context("attachments sweep")?; @@ -152,174 +146,154 @@ pub fn sweep_orphan_files(db: &Db) -> Result { pub(crate) mod tests { use super::*; + /// A library on disk, its attachments directory made, holding one note: answered with the + /// scratch directory that must outlive it, and the note's id. pub(crate) fn a_library_with_a_note() -> (tempfile::TempDir, Db, String) { - use crate::notes::model::NoteDraft; - let scratch = tempfile::tempdir().unwrap(); let mut library = crate::db::open_in_memory() .unwrap() .with_directory(scratch.path().to_path_buf()); - let space = crate::spaces::store::create(&mut library, "Personal").unwrap(); - let note = crate::notes::store::create( - &mut library, - NoteDraft { - space_id: space.id, - folder_id: None, - title: "T".to_string(), - language: crate::notes::language::Language::Txt, - content: String::new(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: crate::notes::model::NoteLifecycle::Permanent, - kind: crate::notes::kind::NoteKind::Snippet, - priority: crate::notes::priority::Priority::None, - items: Vec::new(), - }, - Utc::now(), - ) - .unwrap(); + let space = crate::spaces::store::create(&mut library, "Work").unwrap(); + let draft = crate::notes::model::NoteDraft { + folder_id: None, + title: "T".to_string(), + language: crate::notes::language::Language::Txt, + content: String::new(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + space_id: space.id, + }; + let note = crate::notes::store::create(&mut library, draft, Utc::now()).unwrap(); + std::fs::create_dir_all(directory(&library)).unwrap(); (scratch, std::sync::Mutex::new(Some(library)), note.id) } pub(crate) fn attachments_of(db: &Db) -> PathBuf { - let directory = directory(&lock(db).unwrap()); - std::fs::create_dir_all(&directory).unwrap(); + directory(&lock(db).unwrap()) + } - directory + fn listed(db: &Db, note_id: &str) -> Vec { + store::list(&mut lock(db).unwrap(), note_id).unwrap() } #[test] - fn a_new_attachment_is_sealed_beside_the_library_then_recorded() { - let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let attachment = - store_new(note_id.clone(), "capture.png".to_string(), b"png", &db).unwrap(); + fn attachments_live_in_the_library_s_own_directory() { + let (scratch, db, _) = a_library_with_a_note(); - let written = std::fs::read(directory.join(attachment.stored_name())).unwrap(); - assert_ne!(written, b"png"); - let listed = store::list(&mut lock(&db).unwrap(), ¬e_id).unwrap(); - assert_eq!(listed[0].mime_type, "image/png"); + assert_eq!(attachments_of(&db), scratch.path().join(crate::layout::ATTACHMENTS)); } - /// A file without a record would sit there until the next launch's sweep. + /// Sealed like the rows beside it: the plain bytes are nowhere on disk. #[test] - fn an_attachment_that_cannot_be_recorded_leaves_no_file_behind() { - let (_scratch, db, _) = a_library_with_a_note(); - let directory = attachments_of(&db); - let refused = store_new("ghost".to_string(), "capture.png".to_string(), b"png", &db); + fn a_new_attachment_is_sealed_on_disk_and_recorded_with_its_plain_size_and_type() { + let (_scratch, db, note_id) = a_library_with_a_note(); + let bytes = b"a credentials page"; + + let stored = store_new(note_id.clone(), "capture.png".to_string(), bytes, &db).unwrap(); - assert!(matches!(refused, Err(StorageError::NoteNotFound(_)))); - assert_eq!(std::fs::read_dir(&directory).unwrap().count(), 0); + let on_disk = std::fs::read(attachments_of(&db).join(stored.stored_name())).unwrap(); + assert!(!on_disk.windows(bytes.len()).any(|window| window == bytes)); + assert_eq!((stored.byte_size, stored.mime_type.as_str()), (18, "image/png")); + assert_eq!(listed(&db, ¬e_id)[0].id, stored.id); } + /// A file without a record would only be swept later; none is left behind. #[test] - fn an_attachment_reads_back_as_the_bytes_it_was_given() { - let (_scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); + fn an_attachment_of_a_note_not_there_leaves_no_file() { + let (_scratch, db, _) = a_library_with_a_note(); - let (attachment, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); + let refused = store_new("missing".to_string(), "capture.png".to_string(), b"png", &db); - assert_eq!(attachment.id, stored.id); - assert_eq!(bytes, b"png"); + assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == "missing")); + assert_eq!(std::fs::read_dir(attachments_of(&db)).unwrap().count(), 0); } - /// The read commands' path: the same bytes, and the lock free again once they are in hand. #[test] - fn an_attachment_read_outside_the_lock_leaves_it_free() { + fn an_attachment_is_read_back_opened_with_its_record() { let (_scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let stored = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); - - let (attachment, bytes) = read_outside_lock(&db, &stored.id).unwrap(); - - assert_eq!( - (attachment.id, bytes.as_slice()), - (stored.id, b"png".as_slice()) - ); - assert!(db.try_lock().is_ok()); - assert!(matches!( - read_outside_lock(&db, "unknown"), - Err(StorageError::AttachmentNotFound(_)) - )); + let stored = store_new(note_id, "notes.txt".to_string(), b"plain", &db).unwrap(); + + let (record, bytes) = read_plain(&mut lock(&db).unwrap(), &stored.id).unwrap(); + let (_, outside) = read_outside_lock(&db, &stored.id).unwrap(); + + assert_eq!((record.file_name.as_str(), bytes.as_slice()), ("notes.txt", &b"plain"[..])); + assert_eq!(outside, b"plain"); + assert!(db.try_lock().is_ok(), "the lock is free once the bytes are in hand"); } + /// Opening a file nothing refers to would read outside what the library knows. #[test] - fn two_decrypted_copies_of_the_same_name_do_not_overwrite_each_other() { - let (scratch, db, note_id) = a_library_with_a_note(); - attachments_of(&db); - let first = store_new(note_id.clone(), "capture.png".to_string(), b"1", &db).unwrap(); - let second = store_new(note_id, "capture.png".to_string(), b"2", &db).unwrap(); - let open = scratch.path().join("open"); - - let one = write_plaintext_copy(&open, &first, b"1").unwrap(); - let two = write_plaintext_copy(&open, &second, b"2").unwrap(); + fn a_file_no_record_names_is_never_read() { + let (_scratch, db, _) = a_library_with_a_note(); + std::fs::write(attachments_of(&db).join("stray"), b"stray").unwrap(); - assert_ne!(one, two); - assert_eq!(one.file_name().unwrap(), "capture.png"); - assert_eq!(std::fs::read(one).unwrap(), b"1"); - assert_eq!(std::fs::read(two).unwrap(), b"2"); + for id in ["stray", "missing"] { + assert!(matches!(read_outside_lock(&db, id), Err(StorageError::AttachmentNotFound(_)))); + } } + /// One byte past the limit is enough to refuse: a growing file cannot outrun the read. #[test] - fn an_attachment_nobody_recorded_is_not_read() { - let (_scratch, db, _) = a_library_with_a_note(); + fn a_source_is_read_one_byte_past_the_limit_at_most() { + let scratch = tempfile::tempdir().unwrap(); + let source = scratch.path().join("big.bin"); + let too_long = usize::try_from(model::MAX_BYTES).unwrap() + 10; + std::fs::write(&source, vec![0u8; too_long]).unwrap(); - let refused = read_plain(&mut lock(&db).unwrap(), "../vault"); + let read = read_within_limit(&source.to_string_lossy()).unwrap(); - assert!(matches!(refused, Err(StorageError::AttachmentNotFound(_)))); + assert_eq!(read.len() as u64, model::MAX_BYTES + 1); + let missing = scratch.path().join("missing.bin"); + assert!(matches!(read_within_limit(&missing.to_string_lossy()), Err(StorageError::File(_)))); } + /// Two copies of one name do not overwrite each other. #[test] - fn the_sweep_removes_the_files_no_record_claims_and_only_those() { + fn an_opened_copy_is_written_in_the_clear_in_a_folder_of_its_own() { let (_scratch, db, note_id) = a_library_with_a_note(); - let directory = attachments_of(&db); - let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); - std::fs::write(directory.join("orphan.png"), b"left behind").unwrap(); + let copies = tempfile::tempdir().unwrap(); + let first = store_new(note_id.clone(), "capture.png".to_string(), b"one", &db).unwrap(); + let second = store_new(note_id, "capture.png".to_string(), b"two", &db).unwrap(); - assert_eq!(sweep_orphan_files(&db).unwrap(), 1); + let one = write_plaintext_copy(copies.path(), &first, b"one").unwrap(); + let two = write_plaintext_copy(copies.path(), &second, b"two").unwrap(); - assert!(directory.join(kept.stored_name()).exists()); - assert!(!directory.join("orphan.png").exists()); + assert_eq!(one, copies.path().join(first.opened_copy())); + assert_ne!(one, two); + assert_eq!(std::fs::read(&one).unwrap(), b"one"); + assert_eq!(std::fs::read(&two).unwrap(), b"two"); } + /// That is what "save as" means. #[test] - fn a_file_within_the_limit_is_read_whole() { + fn a_saved_attachment_is_written_in_the_clear_where_asked() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source = directory.join("capture.png"); - std::fs::write(&source, vec![7u8; 2048]).unwrap(); + let path = scratch.path().join("saved.txt"); - let bytes = read_within_limit(&source.to_string_lossy()).unwrap(); + write_plain(&path.to_string_lossy(), b"plain").unwrap(); - assert_eq!(bytes, vec![7u8; 2048]); + assert_eq!(std::fs::read(&path).unwrap(), b"plain"); } - /// A file that grew past the limit is still refused, and no more than one byte past it is - /// ever held. + /// An interrupted copy or a purge cut short leaves one; a file already gone is no error. #[test] - fn a_file_over_the_limit_is_read_one_byte_past_it_and_refused() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let source = directory.join("huge.bin"); - let limit = usize::try_from(model::MAX_BYTES).unwrap(); - std::fs::write(&source, vec![0u8; limit + 10]).unwrap(); - - let bytes = read_within_limit(&source.to_string_lossy()).unwrap(); - - assert_eq!(bytes.len(), limit + 1); - assert!(matches!( - model::validate_size(bytes.len() as u64, "huge.bin"), - Err(StorageError::TooLarge { .. }) - )); - } + fn the_sweep_removes_the_files_no_record_claims_and_keeps_the_others() { + let (_scratch, db, note_id) = a_library_with_a_note(); + let directory = attachments_of(&db); + let kept = store_new(note_id, "capture.png".to_string(), b"png", &db).unwrap(); + std::fs::write(directory.join("orphan.png"), b"orphan").unwrap(); - #[test] - fn a_missing_source_is_reported_rather_than_panicking() { - let error = read_within_limit("no-such-file.png").unwrap_err(); + let swept = sweep_orphan_files(&db).unwrap(); - assert!(matches!(error, StorageError::File(_)), "{error}"); + assert_eq!(swept, 1); + assert!(!directory.join("orphan.png").exists()); + assert!(directory.join(kept.stored_name()).exists()); + remove_files(&directory, &["orphan.png".to_string()]); } } diff --git a/crates/engine/src/attachments/model.rs b/crates/engine/src/attachments/model.rs index 62ea23f90..635af260c 100644 --- a/crates/engine/src/attachments/model.rs +++ b/crates/engine/src/attachments/model.rs @@ -54,21 +54,13 @@ fn copy_name(id: &str, file_name: &str) -> String { } }) .collect(); - let mut name = replaced - .trim_end_matches(['.', ' ']) - .trim_start() - .to_string(); + let mut name = replaced.trim_end_matches(['.', ' ']).trim_start().to_string(); if name.chars().count() > COPY_NAME_CHARS { let extension = extension_of(&name).map(|extension| format!(".{extension}")); let kept = COPY_NAME_CHARS - extension.as_ref().map_or(0, String::len); name = name.chars().take(kept).collect::() + extension.as_deref().unwrap_or(""); } - let stem = name - .split('.') - .next() - .unwrap_or_default() - .trim_end() - .to_ascii_uppercase(); + let stem = name.split('.').next().unwrap_or_default().trim_end().to_ascii_uppercase(); let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") || ((stem.starts_with("COM") || stem.starts_with("LPT")) && stem.len() == 4 @@ -100,10 +92,7 @@ fn contained(id: &str) -> String { /// Lowercase and alphanumeric: separators, `..` or colons would escape the directory. fn extension_of(file_name: &str) -> Option { let candidate = file_name.rsplit_once('.')?.1; - if candidate.is_empty() - || candidate.len() > 8 - || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) - { + if candidate.is_empty() || candidate.len() > 8 || !candidate.chars().all(|c| c.is_ascii_alphanumeric()) { return None; } @@ -141,12 +130,7 @@ pub fn mime_of(file_name: &str) -> String { /// Stripped of any path: an import must not show `../../secrets/key.pem` as a note's own. pub fn display_name(path: &str) -> Result { - let trimmed = path - .rsplit(['/', '\\']) - .next() - .unwrap_or_default() - .trim() - .to_string(); + let trimmed = path.rsplit(['/', '\\']).next().unwrap_or_default().trim().to_string(); if trimmed.is_empty() || trimmed == "." || trimmed == ".." { return Err(ValidationError::new("fileName", "unreadable file name")); @@ -159,24 +143,14 @@ pub fn display_name(path: &str) -> Result { /// `mime_of` answers `application/octet-stream` and skips the preview. pub fn png_name(base: &str) -> String { let trimmed = base.trim(); - let stem = if trimmed.is_empty() { - "capture" - } else { - trimmed - }; + let stem = if trimmed.is_empty() { "capture" } else { trimmed }; - if stem.to_ascii_lowercase().ends_with(".png") { - stem.to_string() - } else { - format!("{stem}.png") - } + if stem.to_ascii_lowercase().ends_with(".png") { stem.to_string() } else { format!("{stem}.png") } } /// Encodes raw RGBA — what the system clipboard hands over — into PNG. pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, StorageError> { - let expected = (width as usize) - .saturating_mul(height as usize) - .saturating_mul(4); + let expected = (width as usize).saturating_mul(height as usize).saturating_mul(4); if width == 0 || height == 0 || rgba.len() < expected { return Err(StorageError::File(format!( "clipboard image of {width}×{height} carries {} bytes, {expected} expected", @@ -190,9 +164,7 @@ pub fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Result, Stora encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder.write_header().context("png header")?; - writer - .write_image_data(&rgba[..expected]) - .context("png data")?; + writer.write_image_data(&rgba[..expected]).context("png data")?; } Ok(png) @@ -205,10 +177,7 @@ const _: () = assert!(MAX_BYTES == MAX_MEGABYTES as u64 * 1024 * 1024); pub fn validate_size(byte_size: u64, name: &str) -> Result { if byte_size > MAX_BYTES { - return Err(StorageError::TooLarge { - name: name.to_string(), - limit_mb: MAX_MEGABYTES, - }); + return Err(StorageError::TooLarge { name: name.to_string(), limit_mb: MAX_MEGABYTES }); } Ok(saturating_u32(byte_size)) @@ -216,63 +185,39 @@ pub fn validate_size(byte_size: u64, name: &str) -> Result { #[cfg(test)] mod tests { - use std::path::Path; - use super::*; - #[test] - fn the_stored_name_comes_from_the_identifier_not_from_the_user() { - assert_eq!(stored_name("a-1", "capture.png"), "a-1.png"); - assert_eq!(stored_name("a-2", "capture.png"), "a-2.png"); - } - - fn opened(id: &str, file_name: &str) -> PathBuf { + fn attachment(id: &str, file_name: &str) -> Attachment { Attachment { id: id.to_string(), - note_id: "n".to_string(), + note_id: "n-1".to_string(), file_name: file_name.to_string(), mime_type: mime_of(file_name), - byte_size: 1, - created_at: Utc::now(), + byte_size: 3, + created_at: DateTime::::UNIX_EPOCH, } - .opened_copy() } #[test] - fn an_opened_copy_keeps_its_own_name_in_a_folder_of_its_own() { - assert_eq!( - opened("7d44d90f", "image-test.png"), - Path::new("7d44d90f").join("image-test.png") - ); - assert_eq!(opened("../x", "a:b?.png"), Path::new("x").join("a_b_.png")); - assert_eq!(opened("a", "notes. "), Path::new("a").join("notes")); - } - - #[test] - fn a_name_windows_will_not_write_falls_back_on_the_stored_one() { - assert_eq!(opened("a", "CON.txt"), Path::new("a").join("a.txt")); - assert_eq!(opened("a", "lpt1"), Path::new("a").join("a")); - assert_eq!(opened("a", "..."), Path::new("a").join("a")); - let long = format!("{}.png", "x".repeat(300)); - let cut = opened("a", &long); - let name = cut.file_name().unwrap().to_string_lossy(); - assert_eq!(name.chars().count(), 100); - assert!(name.ends_with(".png")); - } - - #[test] - fn a_hostile_extension_is_dropped_rather_than_written() { - for name in ["x.../../evil", "x.p g", "x.", "x.verylongextension"] { - assert_eq!(stored_name("a-1", name), "a-1"); + fn a_stored_name_is_the_id_and_the_extension_lowercased() { + let cases = [ + ("a-1", "Capture.PNG", "a-1.png"), + ("a-1", "archive.tar.gz", "a-1.gz"), + ("a-1", "notes", "a-1"), + ("3f2504e0-4f89-41d3-9a0c-0305e82c3301", "x.png", "3f2504e0-4f89-41d3-9a0c-0305e82c3301.png"), + ]; + + for (id, file_name, stored) in cases { + assert_eq!(stored_name(id, file_name), stored, "{file_name}"); } } /// An import decides the id: a record claiming `../vault` must not reach the key file. #[test] - fn a_hostile_identifier_cannot_leave_the_directory() { + fn a_stored_name_is_one_plain_component_whatever_id_it_is_given() { use std::path::{Component, Path}; - for id in [ + let hostile = [ "../vault", "..\\vault", "../../../../Users/me/Startup/run", @@ -282,81 +227,160 @@ mod tests { ".", "", "a/b", - ] { + ]; + + for id in hostile { for file_name in ["capture.png", "no-extension"] { let name = stored_name(id, file_name); - let components: Vec> = Path::new(&name).components().collect(); - - assert_eq!( - components.len(), - 1, - "{id:?} + {file_name:?} gave {name:?}, which is not one component" - ); + let parts: Vec> = Path::new(&name).components().collect(); assert!( - matches!(components[0], Component::Normal(_)), + matches!(parts.as_slice(), [Component::Normal(_)]), "{id:?} + {file_name:?} gave {name:?}" ); } } + assert_eq!(stored_name("../../etc", "x.png"), "etc.png"); + assert_eq!(stored_name("", "x.png"), "attachment.png"); + } + + #[test] + fn a_stored_name_drops_an_extension_that_is_not_plain_letters_and_digits() { + let cases = [ + ("a-1", "x.p/ng", "a-1"), + ("a-1", "x.ph:p", "a-1"), + ("a-1", "x.abcdefghi", "a-1"), + ("a-1", "x.", "a-1"), + ]; + + for (id, file_name, stored) in cases { + assert_eq!(stored_name(id, file_name), stored, "{id:?} {file_name:?}"); + } } + /// An unknown type stays attachable; it is only not previewed. #[test] - fn the_identifiers_the_application_generates_pass_through_untouched() { - let id = "3f2504e0-4f89-41d3-9a0c-0305e82c3301"; + fn a_type_is_read_from_the_extension() { + let cases = [ + ("a.PNG", "image/png"), + ("a.jpeg", "image/jpeg"), + ("a.jpg", "image/jpeg"), + ("a.svg", "image/svg+xml"), + ("a.pdf", "application/pdf"), + ("a.log", "text/plain"), + ("a.csv", "text/csv"), + ("a.exe", "application/octet-stream"), + ("a", "application/octet-stream"), + ]; + + for (file_name, mime) in cases { + assert_eq!(mime_of(file_name), mime, "{file_name}"); + } + } - assert_eq!(stored_name(id, "capture.png"), format!("{id}.png")); + #[test] + fn a_displayed_name_is_the_file_s_own_without_any_path() { + let cases = [ + ("../../secrets/key.pem", "key.pem"), + ("C:\\Users\\me\\report.pdf", "report.pdf"), + (" spaced.txt ", "spaced.txt"), + ]; + + for (path, shown) in cases { + assert_eq!(display_name(path), Ok(shown.to_string()), "{path}"); + } + for unreadable in ["", "folder/", ".", "..", " "] { + assert_eq!(display_name(unreadable).unwrap_err().field, "fileName", "{unreadable:?}"); + } } + /// Without its extension a pasted image would not be previewed. #[test] - fn the_extension_decides_the_type_case_insensitively() { - assert_eq!(mime_of("Capture.PNG"), "image/png"); - assert_eq!(mime_of("dump.unknown"), "application/octet-stream"); + fn a_pasted_image_is_named_as_a_png() { + let cases = [ + ("", "capture.png"), + (" shot ", "shot.png"), + ("Screen.PNG", "Screen.PNG"), + ("photo.jpg", "photo.jpg.png"), + ]; + + for (base, named) in cases { + assert_eq!(png_name(base), named, "{base:?}"); + } } + /// What the clipboard hands over is raw RGBA; bytes past the image are not read. #[test] - fn only_the_last_segment_of_a_path_is_displayed() { - assert_eq!( - display_name(r"C:\Users\me\capture.png").unwrap(), - "capture.png" - ); - assert_eq!(display_name("/home/me/capture.png").unwrap(), "capture.png"); + fn raw_pixels_are_encoded_as_a_png() { + let red = [255, 0, 0, 255]; + + let png = encode_png(1, 1, &red).unwrap(); + + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(encode_png(1, 1, &[red, red].concat()).unwrap(), png); } #[test] - fn a_path_with_no_file_name_is_refused_with_its_field() { - assert_eq!(display_name(" ").unwrap_err().field, "fileName"); - assert_eq!(display_name("/tmp/..").unwrap_err().field, "fileName"); + fn an_image_without_pixels_or_short_of_them_is_refused() { + for (width, height, bytes) in [(0, 1, 4), (1, 0, 4), (2, 2, 15)] { + let rgba = vec![0; bytes]; + + assert!( + matches!(encode_png(width, height, &rgba), Err(StorageError::File(_))), + "{width}×{height} with {bytes} bytes" + ); + } } #[test] - fn a_file_over_the_limit_is_refused_before_being_copied() { - assert!(validate_size(MAX_BYTES, "capture.png").is_ok()); + fn a_file_is_attached_up_to_ten_megabytes_and_refused_past_them() { + assert_eq!(validate_size(MAX_BYTES, "big.bin").unwrap(), 10 * 1024 * 1024); assert!(matches!( - validate_size(MAX_BYTES + 1, "capture.mov"), - Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "capture.mov" + validate_size(MAX_BYTES + 1, "big.bin"), + Err(StorageError::TooLarge { name, limit_mb: 10 }) if name == "big.bin" )); } + /// Two copies of one name must not meet: each sits in a folder of its own. #[test] - fn a_pasted_image_always_ends_up_with_its_extension() { - assert_eq!(png_name("capture-2026"), "capture-2026.png"); - assert_eq!(png_name("capture.PNG"), "capture.PNG"); - assert_eq!(png_name(" "), "capture.png"); + fn an_opened_copy_sits_in_a_folder_of_its_own_under_its_own_name() { + assert_eq!(attachment("a-1", "Rapport.pdf").opened_copy(), PathBuf::from("a-1").join("Rapport.pdf")); + assert_eq!(attachment("../a-1", "x.pdf").opened_copy(), PathBuf::from("a-1").join("x.pdf")); } + /// What Windows forbids is replaced; a device name or nothing left falls back on the + /// stored name. #[test] - fn raw_clipboard_pixels_become_a_readable_png() { - let rgba = vec![255u8; 2 * 2 * 4]; - - let png = encode_png(2, 2, &rgba).unwrap(); - - assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n"); - assert_eq!(mime_of(&png_name("capture")), "image/png"); + fn an_opened_copy_is_named_as_windows_accepts_a_file() { + let cases = [ + ("a:c?.txt", "a_b__c_.txt"), + ("tab\tname.txt", "tab_name.txt"), + ("name. . ", "name"), + (" lead.txt", "lead.txt"), + ("CON.txt", "a-1.txt"), + ("nul", "a-1"), + ("com1.log", "a-1.log"), + ("LPT9", "a-1"), + ("COM10.txt", "COM10.txt"), + ("console.txt", "console.txt"), + ("...", "a-1"), + ]; + + for (file_name, copy) in cases { + let opened = attachment("a-1", file_name).opened_copy(); + assert_eq!(opened, PathBuf::from("a-1").join(copy), "{file_name:?}"); + } } + /// The profile's path comes first: a long name is cut, its extension kept. #[test] - fn a_truncated_clipboard_image_is_refused_rather_than_written() { - assert!(encode_png(2, 2, &[0u8; 4]).is_err()); - assert!(encode_png(0, 0, &[]).is_err()); + fn a_long_opened_copy_name_is_cut_before_its_extension() { + let long = "a".repeat(150); + + let with_extension = attachment("a-1", &format!("{long}.pdf")).opened_copy(); + let without = attachment("a-1", &long).opened_copy(); + + let name = |path: &std::path::Path| path.file_name().unwrap().to_string_lossy().to_string(); + assert_eq!(name(&with_extension), format!("{}.pdf", "a".repeat(96))); + assert_eq!(name(&without), "a".repeat(100)); } } diff --git a/crates/engine/src/attachments/sealed.rs b/crates/engine/src/attachments/sealed.rs index 645334a67..bb7619857 100644 --- a/crates/engine/src/attachments/sealed.rs +++ b/crates/engine/src/attachments/sealed.rs @@ -38,10 +38,7 @@ pub fn sweep_plaintext(paths: &Paths) { if let Err(error) = std::fs::remove_dir_all(&directory) && error.kind() != std::io::ErrorKind::NotFound { - log::warn!( - "Decrypted copies not swept from {}: {error}", - directory.display() - ); + log::warn!("Decrypted copies not swept from {}: {error}", directory.display()); } } @@ -58,14 +55,9 @@ mod tests { #[test] fn the_decrypted_copies_live_under_the_profile_and_go_in_one_sweep() { let profile = tempfile::tempdir().unwrap(); - let paths = Paths { - profile: profile.path().to_path_buf(), - }; + let paths = Paths { profile: profile.path().to_path_buf() }; let directory = plaintext_directory(&paths); - assert_eq!( - directory, - profile.path().join(crate::layout::PLAINTEXT_COPIES) - ); + assert_eq!(directory, profile.path().join(crate::layout::PLAINTEXT_COPIES)); sweep_plaintext(&paths); std::fs::create_dir_all(&directory).unwrap(); @@ -75,17 +67,6 @@ mod tests { assert!(!directory.exists()); } - /// The property the name has to have, asserted without waiting for a coincidence. - #[test] - fn two_scratch_directories_are_never_the_same_one() { - let scratch = tempfile::tempdir().unwrap(); - let first = scratch.path().to_path_buf(); - let scratch = tempfile::tempdir().unwrap(); - let second = scratch.path().to_path_buf(); - - assert_ne!(first, second); - } - #[test] fn a_sealed_file_reads_back_byte_for_byte() { let scratch = tempfile::tempdir().unwrap(); @@ -132,8 +113,7 @@ mod tests { let target = directory.join("capture.png"); write_sealed(&vault(), &target, b"bytes").unwrap(); - let other = - Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); + let other = Vault::derive("another passphrase", b"0123456789abcdef", Cost::FOR_TESTS).unwrap(); assert!(read_sealed(&other, &target).is_err()); } diff --git a/crates/engine/src/attachments/store.rs b/crates/engine/src/attachments/store.rs index 87c1fa8a6..4d5210cbf 100644 --- a/crates/engine/src/attachments/store.rs +++ b/crates/engine/src/attachments/store.rs @@ -26,10 +26,8 @@ struct AttachmentRow { /// `{id}.{extension}`, so the type is already public. Sealing it would be theatre. impl AttachmentRow { fn open(row: Self, vault: &Vault) -> Result { - let created_at = iso8601::parse(&row.created_at).map_err(|_| StorageError::CorruptRow { - id: row.id.clone(), - field: "createdAt", - })?; + let created_at = iso8601::parse(&row.created_at) + .map_err(|_| StorageError::CorruptRow { id: row.id.clone(), field: "createdAt" })?; Ok(Attachment { byte_size: saturating_u32(row.byte_size), @@ -116,10 +114,7 @@ pub fn delete(connection: &mut SqliteConnection, id: &str) -> Result<(), Storage /// The records an export carries. The bytes are not here: the caller reads them from the /// attachments directory by [`model::stored_name`]. -pub fn for_notes( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn for_notes(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -137,10 +132,7 @@ pub fn for_notes( } /// ⚠️ Collected before a purge: the cascade takes the records, never the files. -pub fn stored_names_of( - connection: &mut Library, - note_ids: &[String], -) -> Result, StorageError> { +pub fn stored_names_of(connection: &mut Library, note_ids: &[String]) -> Result, StorageError> { if note_ids.is_empty() { return Ok(Vec::new()); } @@ -182,89 +174,189 @@ pub fn counts(connection: &mut SqliteConnection) -> Result, #[cfg(test)] mod tests { - use chrono::Utc; + use chrono::{DateTime, Utc}; use super::*; use crate::db::open_in_memory; - use crate::notes::kind::NoteKind; - use crate::notes::language::Language; - use crate::notes::model::{NoteDraft, NoteLifecycle}; - use crate::notes::priority::Priority; - - fn note(connection: &mut Library) -> String { - let space = crate::spaces::store::create(connection, "Personal").unwrap(); - crate::notes::store::create( - connection, - NoteDraft { - space_id: space.id, - folder_id: None, - title: "T".to_string(), - language: Language::Txt, - content: String::new(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: NoteLifecycle::Permanent, - kind: NoteKind::Snippet, - priority: Priority::None, - items: Vec::new(), - }, - Utc::now(), - ) - .unwrap() - .id + use crate::notes::fixtures::at; + + fn note_in(library: &mut Library) -> String { + let space = crate::spaces::store::create(library, &uuid::Uuid::new_v4().to_string()) + .unwrap() + .id; + let draft = crate::notes::model::NoteDraft { + space_id: space, + folder_id: None, + title: "T".to_string(), + language: crate::notes::language::Language::Txt, + content: String::new(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + }; + crate::notes::store::create(library, draft, at("2026-07-25T09:00:00.000Z")) + .unwrap() + .id } - /// The tests hold a library; `create` takes the pair, as an import does. - fn create_here(connection: &mut Library, attachment: &Attachment) -> Result<(), StorageError> { - let (db, vault) = connection.split(); - create(db, vault, attachment) - } - - fn sample(id: &str, note_id: &str) -> Attachment { + fn attachment(id: &str, note_id: &str, file_name: &str, created_at: DateTime) -> Attachment { Attachment { id: id.to_string(), note_id: note_id.to_string(), - file_name: "capture.png".to_string(), - mime_type: "image/png".to_string(), - byte_size: 12, - created_at: Utc::now(), + file_name: file_name.to_string(), + mime_type: model::mime_of(file_name), + byte_size: 3, + created_at, + } + } + + fn record(library: &mut Library, attachment: &Attachment) { + let (db, vault) = library.split(); + create(db, vault, attachment).unwrap(); + } + + fn ids(attachments: &[Attachment]) -> Vec<&str> { + attachments.iter().map(|attachment| attachment.id.as_str()).collect() + } + + /// The foreign key would refuse it too, in words the screen cannot translate. + #[test] + fn an_attachment_is_recorded_only_for_a_live_note() { + let mut library = open_in_memory().unwrap(); + let trashed = note_in(&mut library); + crate::notes::fixtures::trash(&mut library, &trashed, Utc::now()); + let (db, vault) = library.split(); + + for note_id in ["missing", trashed.as_str()] { + let refused = create(db, vault, &attachment("a-1", note_id, "x.png", Utc::now())); + + assert!(matches!(refused, Err(StorageError::NoteNotFound(id)) if id == note_id), "{note_id}"); } } #[test] - fn an_attachment_is_read_back_whole() { - let mut connection = open_in_memory().unwrap(); - let note_id = note(&mut connection); + fn a_note_s_attachments_are_listed_in_the_order_they_came() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let other = note_in(&mut library); + record(&mut library, &attachment("late", ¬e, "b.png", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("early", ¬e, "a.png", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("else", &other, "c.png", at("2026-07-25T10:00:00.000Z"))); + + assert_eq!(ids(&list(&mut library, ¬e).unwrap()), ["early", "late"]); + } + + /// The type stays in the clear: the file on disk already says it by its extension. + #[test] + fn a_record_s_name_is_sealed_and_read_back_whole() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let made = attachment("a-1", ¬e, "secret plan.png", at("2026-07-25T10:00:00.000Z")); + record(&mut library, &made); + + let (name, mime): (String, String) = attachments::table + .select((attachments::file_name, attachments::mime_type)) + .first(library.db()) + .unwrap(); + let found = find(&mut library, "a-1").unwrap().unwrap(); + + assert!(!name.contains("secret")); + assert_eq!(mime, "image/png"); + assert_eq!( + (found.file_name, found.byte_size, found.created_at), + (made.file_name, 3, made.created_at) + ); + assert!(find(&mut library, "missing").unwrap().is_none()); + } + + #[test] + fn an_unreadable_instant_is_answered_as_a_corrupt_row() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + diesel::update(attachments::table.find("a-1")) + .set(attachments::created_at.eq("yesterday")) + .execute(library.db()) + .unwrap(); + + assert!(matches!( + find(&mut library, "a-1"), + Err(StorageError::CorruptRow { id, field: "createdAt" }) if id == "a-1" + )); + } - create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap(); - let listed = list(&mut connection, ¬e_id).unwrap(); + #[test] + fn a_record_is_deleted_once_and_a_second_time_is_not_found() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + + delete(library.db(), "a-1").unwrap(); + + assert!(list(&mut library, ¬e).unwrap().is_empty()); + assert!(matches!( + delete(library.db(), "a-1"), + Err(StorageError::AttachmentNotFound(id)) if id == "a-1" + )); + } - assert_eq!(listed.len(), 1); - assert_eq!(listed[0].file_name, "capture.png"); - assert_eq!(listed[0].byte_size, 12); + /// What an export carries, and the names its files are read under. + #[test] + fn the_records_of_some_notes_come_with_the_names_their_files_are_stored_under() { + let mut library = open_in_memory().unwrap(); + let first = note_in(&mut library); + let second = note_in(&mut library); + let left = note_in(&mut library); + record(&mut library, &attachment("a-1", &first, "Shot.PNG", at("2026-07-25T10:00:00.000Z"))); + record(&mut library, &attachment("a-2", &second, "notes", at("2026-07-25T11:00:00.000Z"))); + record(&mut library, &attachment("a-3", &left, "x.pdf", at("2026-07-25T12:00:00.000Z"))); + let chosen = [first, second]; + + let records = for_notes(&mut library, &chosen).unwrap(); + let mut names = stored_names_of(&mut library, &chosen).unwrap(); + names.sort(); + let mut every = all_stored_names(&mut library).unwrap(); + every.sort(); + + assert_eq!(ids(&records), ["a-1", "a-2"]); + assert_eq!(names, ["a-1.png", "a-2"]); + assert_eq!(every, ["a-1.png", "a-2", "a-3.pdf"]); + assert!(for_notes(&mut library, &[]).unwrap().is_empty()); + assert!(stored_names_of(&mut library, &[]).unwrap().is_empty()); } + /// The cascade takes the records, never the files: their names are read before a purge. #[test] - fn attaching_to_an_unknown_note_is_refused() { - let mut connection = open_in_memory().unwrap(); + fn a_purged_note_s_records_go_with_it() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + record(&mut library, &attachment("a-1", ¬e, "x.png", Utc::now())); + let names = stored_names_of(&mut library, std::slice::from_ref(¬e)).unwrap(); - let error = create_here(&mut connection, &sample("a-1", "ghost")).unwrap_err(); + crate::notes::fixtures::trash(&mut library, ¬e, Utc::now()); + crate::notes::store::trash::purge(&mut library, std::slice::from_ref(¬e)).unwrap(); - assert!(matches!(error, StorageError::NoteNotFound(_))); + assert_eq!(names, ["a-1.png"]); + assert!(list(&mut library, ¬e).unwrap().is_empty()); } #[test] - fn purging_a_note_takes_its_attachment_rows_with_it() { - let mut connection = open_in_memory().unwrap(); - let note_id = note(&mut connection); - create_here(&mut connection, &sample("a-1", ¬e_id)).unwrap(); + fn each_note_is_counted_its_attachments_in_one_read() { + let mut library = open_in_memory().unwrap(); + let note = note_in(&mut library); + let other = note_in(&mut library); + let bare = note_in(&mut library); + for (id, owner) in [("a-1", ¬e), ("a-2", ¬e), ("a-3", &other)] { + record(&mut library, &attachment(id, owner, "x.png", Utc::now())); + } - let files = stored_names_of(&mut connection, std::slice::from_ref(¬e_id)).unwrap(); - crate::notes::store::trash::trash(&mut connection, ¬e_id, Utc::now()).unwrap(); - crate::notes::store::trash::purge(&mut connection, std::slice::from_ref(¬e_id)).unwrap(); + let counted = counts(library.db()).unwrap(); - assert_eq!(files, ["a-1.png"]); - assert!(list(&mut connection, ¬e_id).unwrap().is_empty()); + assert_eq!(counted, HashMap::from([(note, 2), (other, 1)])); + assert!(!counted.contains_key(&bare)); } } diff --git a/crates/engine/src/backup.rs b/crates/engine/src/backup.rs index b5211a1f4..9bf299018 100644 --- a/crates/engine/src/backup.rs +++ b/crates/engine/src/backup.rs @@ -7,7 +7,6 @@ pub mod copies; use std::path::PathBuf; -use std::sync::Mutex; use chrono::{DateTime, Utc}; @@ -16,23 +15,6 @@ use crate::db::{Db, lock}; use crate::error::{AppError, StorageError}; use copies::{Backup, list, replace, rotate}; -/// Where the library the last restore replaced went, kept for the page the restore reloads: -/// nothing in the page survives the reload on every platform. -#[derive(Default)] -pub struct Restored(Mutex>); - -impl Restored { - fn keep(&self, aside: String) { - if let Ok(mut kept) = self.0.lock() { - *kept = Some(aside); - } - } - - fn take(&self) -> Option { - self.0.lock().ok().and_then(|mut kept| kept.take()) - } -} - /// The launch copy, when the person wants them. Never fatal: a library that cannot be copied /// still has to open. pub(crate) fn take(wanted: bool, db: &Db) { @@ -72,79 +54,15 @@ pub fn list_backups(engine: &Engine) -> Result, AppError> { pub fn restore_backup(engine: &Engine, id: &str) -> Result { let db = &engine.db; engine.let_go_of_the_network(); - let aside = restore(db, id, Utc::now())?.to_string_lossy().to_string(); - engine.restored.keep(aside.clone()); - - Ok(aside) -} -/// Where the library the last restore replaced went, once: the page it reloaded says it. -pub fn take_restored_aside(engine: &Engine) -> Option { - engine.restored.take() + Ok(restore(db, id, Utc::now())?.to_string_lossy().to_string()) } fn restore(db: &Db, id: &str, now: DateTime) -> Result { let mut open = db.lock().map_err(|_| StorageError::Unavailable)?; - let directory = open - .as_ref() - .ok_or(StorageError::Locked)? - .directory() - .to_path_buf(); + let directory = open.as_ref().ok_or(StorageError::Locked)?.directory().to_path_buf(); // Dropped before a single file moves, and the lock held for the whole swap. *open = None; replace(&directory, id, now) } - -#[cfg(test)] -mod tests { - use super::*; - use copies::tests::{at, library}; - - #[test] - fn where_a_restore_set_the_library_aside_is_told_once() { - let restored = Restored::default(); - assert_eq!(restored.take(), None); - - restored.keep("replaced/2026-07-25_09-00-00".to_string()); - - assert_eq!( - restored.take().as_deref(), - Some("replaced/2026-07-25_09-00-00") - ); - assert_eq!(restored.take(), None); - } - - #[test] - fn the_launch_copy_lands_beside_the_open_library() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (connection, _) = library(&directory); - let db: Db = std::sync::Mutex::new(Some(connection)); - - copy(&db); - - assert_eq!(list(&directory).len(), 1); - drop(db); - } - - /// Closed before a single file moves: every command answers `Locked` afterwards. - #[test] - fn restoring_closes_the_library_and_says_where_the_replaced_one_went() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_string_lossy().to_string(); - let db: Db = std::sync::Mutex::new(Some(connection)); - - let aside = restore(&db, &id, at(1)).unwrap(); - - assert!(db.lock().unwrap().is_none()); - assert!(aside.join(crate::layout::DATABASE).exists()); - assert!(matches!( - restore(&db, &id, at(2)), - Err(StorageError::Locked) - )); - } -} diff --git a/crates/engine/src/backup/copies.rs b/crates/engine/src/backup/copies.rs index 26ee111c1..4283e0729 100644 --- a/crates/engine/src/backup/copies.rs +++ b/crates/engine/src/backup/copies.rs @@ -154,11 +154,7 @@ pub(crate) fn list(library: &Path) -> Vec { /// Moved aside into `replaced/`, never deleted, and `vault.json` with it: the copy brings its /// own, and a database and a key from two wrappings open nothing. `attachments/` goes too, and /// the copy's is linked back: an attachment added since is kept aside, not lost. -pub(crate) fn replace( - library: &Path, - id: &str, - now: DateTime, -) -> Result { +pub(crate) fn replace(library: &Path, id: &str, now: DateTime) -> Result { // ⚠️ Matched against the listing, never joined: the id comes from the front end, and // `../2026-01-01_00-00-00` joins to a path outside `backups/` that still parses as a stamp. let copy = existing(&library.join(BACKUPS)) @@ -213,11 +209,7 @@ fn copy_back(copy: &Path, library: &Path) -> Result<(), String> { fn put_back(moved: &[(PathBuf, PathBuf)], aside: &Path) { for (from, to) in moved { - let _ = if from.is_dir() { - std::fs::remove_dir_all(from) - } else { - std::fs::remove_file(from) - }; + let _ = if from.is_dir() { std::fs::remove_dir_all(from) } else { std::fs::remove_file(from) }; let _ = std::fs::rename(to, from); } let _ = std::fs::remove_dir_all(aside); @@ -250,10 +242,7 @@ pub(crate) fn rewrap(library: &Path, vault: &Vault, passphrase: &str, cost: Cost match crate::vault::file::write_wrapped(&path, vault, passphrase, cost) { Ok(()) => tally.done += 1, Err(error) => { - log::warn!( - "{}: still opens with the old passphrase: {error}", - path.display() - ); + log::warn!("{}: still opens with the old passphrase: {error}", path.display()); tally.left += 1; } } @@ -263,492 +252,344 @@ pub(crate) fn rewrap(library: &Path, vault: &Vault, passphrase: &str, cost: Cost } #[cfg(test)] -pub(crate) mod tests { +mod tests { use super::*; use crate::db; use crate::notes::store as notes; use crate::spaces::store as spaces; + use crate::vault::file; - pub(crate) fn at(offset_hours: i64) -> DateTime { + const PHRASE: &str = "a passphrase"; + + fn at(offset_hours: i64) -> DateTime { db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + TimeDelta::hours(offset_hours) } - /// A library with one note in it, and the key file beside it, as a real one is. - pub(crate) fn library(directory: &Path) -> (Library, String) { - let vault = crate::vault::file::create( - directory, - "a passphrase", - crate::vault::key::Cost::FOR_TESTS, - ) - .unwrap(); + fn draft(space_id: &str, title: &str) -> crate::notes::model::NoteDraft { + crate::notes::model::NoteDraft { + space_id: space_id.to_string(), + folder_id: None, + title: title.to_string(), + language: crate::notes::language::Language::Txt, + content: "psql -h prod".to_string(), + source: String::new(), + tags: Vec::new(), + pinned: false, + lifecycle: crate::notes::model::NoteLifecycle::Permanent, + kind: crate::notes::kind::NoteKind::Snippet, + priority: crate::notes::priority::Priority::None, + items: Vec::new(), + } + } + /// A library on disk as a real one is: its key file beside it, one note, one attachment. + fn library(directory: &Path) -> (Library, String) { + let vault = file::create(directory, PHRASE, Cost::FOR_TESTS).unwrap(); let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); - let space = spaces::create(&mut connection, "Perso").unwrap().id; - let note = notes::create( - &mut connection, - crate::notes::model::NoteDraft { - space_id: space, - folder_id: None, - title: "À sauvegarder".to_string(), - language: crate::notes::language::Language::Txt, - content: "psql -h prod".to_string(), - source: String::new(), - tags: Vec::new(), - pinned: false, - lifecycle: crate::notes::model::NoteLifecycle::Permanent, - kind: crate::notes::kind::NoteKind::Snippet, - priority: crate::notes::priority::Priority::None, - items: Vec::new(), - }, - at(0), - ) - .unwrap() - .id; + let space = spaces::create(&mut connection, "Work").unwrap().id; + let note = notes::create(&mut connection, draft(&space, "Kept"), at(0)).unwrap().id; + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"png").unwrap(); (connection, note) } - /// A copy that cannot be opened is not a backup. - #[test] - fn a_copy_opens_as_a_library_and_holds_the_notes() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note_id) = library(&directory); - - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - - let reopened = crate::vault::file::unlock(&target, "a passphrase").unwrap(); - let mut copy = db::open(&target.join(layout::DATABASE), reopened).unwrap(); - let written = notes::all(&mut copy, None).unwrap(); + fn titles_in(directory: &Path, passphrase: &str) -> Vec { + let vault = file::unlock(directory, passphrase).unwrap(); + let mut copy = db::open(&directory.join(layout::DATABASE), vault).unwrap(); + let read = notes::all(&mut copy, None).unwrap(); + read.into_iter().map(|note| note.title).collect() + } - assert_eq!(written.len(), 1); - assert_eq!(written[0].id, note_id); - assert_eq!(written[0].title, "À sauvegarder"); + fn ids(directory: &Path) -> Vec { + list(directory).into_iter().map(|backup| backup.id).collect() } + /// A copy that cannot be opened is no backup: its key file travels, its attachments too. #[test] - fn the_key_file_travels_with_the_database() { + fn a_copy_opens_on_its_own_with_the_notes_and_the_attachments() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let (mut connection, _) = library(scratch.path()); - assert!(target.join(KEY_FILE).is_file()); - assert!(target.join(layout::DATABASE).is_file()); - } + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); - fn attach(directory: &Path, name: &str, bytes: &[u8]) { - std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); - std::fs::write(directory.join(ATTACHMENTS).join(name), bytes).unwrap(); + assert_eq!(target, scratch.path().join(BACKUPS).join(layout::stamp(at(0)))); + assert_eq!(titles_in(&target, PHRASE), ["Kept"]); + assert_eq!(std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), b"png"); } - /// Purged from the library afterwards, an attachment is still whole in the copy: the link - /// is what goes, not the bytes. + /// One file under two names: the copy costs no disk, and a purge in the library only + /// unlinks, leaving the copy whole. #[test] - fn the_attachments_travel_with_the_copy_and_outlive_a_purge() { + fn a_copy_links_the_attachments_rather_than_copying_them() { + use std::io::Write; + let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"\x89PNG sealed"); + let (mut connection, _) = library(scratch.path()); + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let live = scratch.path().join(ATTACHMENTS).join("a-1.png"); + let copied = target.join(ATTACHMENTS).join("a-1.png"); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::remove_file(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(); + let mut through_the_library = std::fs::OpenOptions::new().append(true).open(&live).unwrap(); + through_the_library.write_all(b", once").unwrap(); + drop(through_the_library); + std::fs::remove_file(&live).unwrap(); - assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"\x89PNG sealed" - ); + assert_eq!(std::fs::read(&copied).unwrap(), b"png, once"); } - /// One file under two names, not two files: what is written through one reads through the - /// other. Nothing in the application writes an attachment twice; this shows the copy is free. + /// `attachments/` is flat: a folder found in it is no attachment, and fails nothing. #[test] - fn the_copy_shares_the_attachments_rather_than_duplicating_them() { - use std::io::Write; - + fn a_folder_inside_the_attachments_is_passed_over() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"linked"); - - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::OpenOptions::new() - .append(true) - .open(directory.join(ATTACHMENTS).join("a-1.png")) - .unwrap() - .write_all(b", once") - .unwrap(); - - assert_eq!( - std::fs::read(target.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"linked, once" - ); + let (mut connection, _) = library(scratch.path()); + std::fs::create_dir_all(scratch.path().join(ATTACHMENTS).join("stray")).unwrap(); + + let target = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + + assert!(target.join(ATTACHMENTS).join("a-1.png").is_file()); + assert!(!target.join(ATTACHMENTS).join("stray").exists()); } - /// Counting the shared attachments in each copy would make three copies look like three - /// times the disk. + /// A library with no attachment folder yet, and a copy taken before it had one. #[test] - fn a_copy_is_listed_at_the_size_of_its_database() { + fn a_library_without_an_attachments_folder_is_copied_and_put_back() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", &[0u8; 4096]); + let (mut connection, _) = library(scratch.path()); + std::fs::remove_dir_all(scratch.path().join(ATTACHMENTS)).unwrap(); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); + drop(connection); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + replace(scratch.path(), &layout::stamp(at(0)), at(1)).unwrap(); - let database = std::fs::metadata(target.join(layout::DATABASE)) - .unwrap() - .len(); - assert_eq!(list(&directory)[0].bytes, database); + assert_eq!(titles_in(scratch.path(), PHRASE), ["Kept"]); } + /// ⚠️ A failed restore must never leave no library at all: what was set aside goes back, + /// directories included, over whatever half of the copy had landed. Private: nothing + /// public can fail once the attachments have moved, the copy's files being checked first. #[test] - fn linking_onto_a_name_already_there_leaves_both_whole() { + fn putting_back_undoes_a_half_finished_restore() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - attach(&directory, "a-1.png", b"the bytes"); - let into = directory.join("into"); + let directory = scratch.path(); + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("a-1.png"), b"live").unwrap(); + std::fs::write(directory.join(KEY_FILE), b"live key").unwrap(); + let aside = directory.join(REPLACED).join(layout::stamp(at(0))); + std::fs::create_dir_all(&aside).unwrap(); + let mut moved = Vec::new(); + for name in [KEY_FILE, ATTACHMENTS] { + std::fs::rename(directory.join(name), aside.join(name)).unwrap(); + moved.push((directory.join(name), aside.join(name))); + } + std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); + std::fs::create_dir_all(directory.join(ATTACHMENTS)).unwrap(); + std::fs::write(directory.join(ATTACHMENTS).join("from-the-copy.png"), b"half").unwrap(); - link_files(&directory.join(ATTACHMENTS), &into).unwrap(); - link_files(&directory.join(ATTACHMENTS), &into).unwrap(); + put_back(&moved, &aside); - assert_eq!(std::fs::read(into.join("a-1.png")).unwrap(), b"the bytes"); - assert_eq!( - std::fs::read(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"the bytes" - ); + assert_eq!(std::fs::read(directory.join(KEY_FILE)).unwrap(), b"live key"); + assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); + assert!(!directory.join(ATTACHMENTS).join("from-the-copy.png").exists()); + assert!(!aside.exists()); } + /// A half-written copy would be the newest, and hold the next rotation off. #[test] - fn a_second_launch_the_same_day_takes_nothing() { + fn a_copy_that_cannot_take_the_key_file_leaves_nothing_behind() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); + let (mut connection, _) = library(scratch.path()); + let (key, moved) = (scratch.path().join(KEY_FILE), scratch.path().join("moved")); + std::fs::rename(&key, &moved).unwrap(); - let again = rotate(&directory, &mut connection, at(3)).unwrap(); + let failed = rotate(scratch.path(), &mut connection, at(0)); + std::fs::rename(&moved, &key).unwrap(); + let retried = rotate(scratch.path(), &mut connection, at(1)).unwrap(); - assert!(again.is_none()); - assert_eq!(existing(&directory.join(BACKUPS)).len(), 1); + assert!(matches!(failed, Err(StorageError::File(_)))); + assert_eq!(retried, Some(scratch.path().join(BACKUPS).join(layout::stamp(at(1))))); + assert_eq!(list(scratch.path()).len(), 1); } + /// Five launches in an hour must not rotate every older copy out. #[test] - fn a_launch_the_next_day_takes_another() { + fn a_copy_is_taken_at_most_once_a_day() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); + let (mut connection, _) = library(scratch.path()); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); - rotate(&directory, &mut connection, at(25)) - .unwrap() - .unwrap(); + let soon = rotate(scratch.path(), &mut connection, at(23)).unwrap(); + let next_day = rotate(scratch.path(), &mut connection, at(24)).unwrap(); - assert_eq!(existing(&directory.join(BACKUPS)).len(), 2); + assert_eq!(soon, None); + assert!(next_day.is_some()); + assert_eq!(list(scratch.path()).len(), 2); } + /// Enough to reach past the launch that went wrong without becoming a second library. #[test] - fn only_the_last_few_are_kept() { + fn three_copies_are_kept_newest_first() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); + let (mut connection, _) = library(scratch.path()); - for day in 0..6 { - rotate(&directory, &mut connection, at(day * 25)).unwrap(); + for day in 0..5 { + rotate(scratch.path(), &mut connection, at(24 * day)).unwrap(); } - let kept = existing(&directory.join(BACKUPS)); - assert_eq!(kept.len(), KEEP); - // The newest survive, not the first ones taken. - assert_eq!(taken_at(&kept[0]).unwrap(), at(5 * 25)); + let kept: Vec = [4, 3, 2].iter().map(|day| layout::stamp(at(24 * day))).collect(); + assert_eq!(ids(scratch.path()), kept); } - /// Changing the phrase is what somebody does when they believe the old one leaked, and each - /// copy in the same profile holds a key file wrapped under it. + /// Whether the key file travelled says whether a restore can open it; the database alone is + /// weighed, the attachments being shared. #[test] - fn changing_the_passphrase_stops_the_old_one_opening_a_backup() { + fn a_copy_is_listed_with_its_size_and_whether_it_opens() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - - let vault = crate::vault::file::change_passphrase( - &directory, - "a passphrase", - "a new one", - Cost::FOR_TESTS, - ) - .unwrap(); - - // Rewrapping the live file alone revokes nothing. - crate::vault::file::unlock(&target, "a passphrase") - .expect("the copy still opens with the retired phrase before the rewrap"); - - let tally = rewrap(&directory, &vault, "a new one", Cost::FOR_TESTS); - - assert_eq!(tally, Rewrapped { done: 1, left: 0 }); - assert!( - crate::vault::file::unlock(&target, "a passphrase").is_err(), - "the retired passphrase still opens the backup" - ); - // And the copy is not merely shut: it opens under the new one, on the same key. - crate::vault::file::unlock(&target, "a new one").unwrap(); + let (mut connection, _) = library(scratch.path()); + let whole = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); + std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); + std::fs::create_dir_all(scratch.path().join(BACKUPS).join("not a stamp")).unwrap(); + + let listed = list(scratch.path()); + + let shown: Vec<(&str, bool)> = + listed.iter().map(|backup| (backup.id.as_str(), backup.openable)).collect(); + let (whole_id, keyless_id) = (layout::stamp(at(0)), layout::stamp(at(48))); + assert_eq!(shown, [(keyless_id.as_str(), false), (whole_id.as_str(), true)]); + assert_eq!(listed[1].taken_at, at(0)); + let size = std::fs::metadata(whole.join(layout::DATABASE)).unwrap().len(); + assert_eq!(listed[1].bytes, size); } - /// A copy is rewrapped from the key, not opened with the phrase being retired, so one taken - /// two changes ago is reached as well. + /// Moved aside, never deleted, its key file with it; an attachment added since kept aside. #[test] - fn a_copy_left_over_from_an_older_phrase_is_reached_too() { + fn a_copy_put_back_sets_the_live_library_aside_whole() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let first = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - - let vault = crate::vault::file::change_passphrase( - &directory, - "a passphrase", - "the second", - Cost::FOR_TESTS, - ) - .unwrap(); - // No rewrap here: the first copy stays under the very first phrase. - let second = rotate(&directory, &mut connection, at(25)) - .unwrap() - .unwrap(); - crate::vault::file::write_wrapped( - &second.join(KEY_FILE), - &vault, - "the second", - Cost::FOR_TESTS, - ) - .unwrap(); - - let vault = crate::vault::file::change_passphrase( - &directory, - "the second", - "the third", - Cost::FOR_TESTS, - ) - .unwrap(); - let tally = rewrap(&directory, &vault, "the third", Cost::FOR_TESTS); - - assert_eq!(tally.done, 2); - for copy in [&first, &second] { - assert!(crate::vault::file::unlock(copy, "a passphrase").is_err()); - assert!(crate::vault::file::unlock(copy, "the second").is_err()); - crate::vault::file::unlock(copy, "the third").unwrap(); - } + let library_at = scratch.path(); + let (mut connection, _) = library(library_at); + rotate(library_at, &mut connection, at(0)).unwrap(); + let space = spaces::list(&mut connection).unwrap()[0].id.clone(); + notes::create(&mut connection, draft(&space, "Since"), at(1)).unwrap(); + std::fs::write(library_at.join(ATTACHMENTS).join("a-2.png"), b"new").unwrap(); + drop(connection); + + let aside = replace(library_at, &layout::stamp(at(0)), at(2)).unwrap(); + + assert_eq!(aside, library_at.join(REPLACED).join(layout::stamp(at(2)))); + assert_eq!(titles_in(library_at, PHRASE), ["Kept"]); + let mut set_aside = titles_in(&aside, PHRASE); + set_aside.sort(); + assert_eq!(set_aside, ["Kept", "Since"]); + assert!(aside.join(ATTACHMENTS).join("a-2.png").is_file()); + assert!(!library_at.join(ATTACHMENTS).join("a-2.png").exists()); + assert!(library_at.join(ATTACHMENTS).join("a-1.png").is_file()); } - /// A copy taken before the library was sealed has no key file to retire. #[test] - fn a_copy_with_no_key_file_is_left_alone_rather_than_counted() { + fn a_copy_not_there_or_without_its_key_is_not_put_back() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let target = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - std::fs::remove_file(target.join(KEY_FILE)).unwrap(); - - let vault = crate::vault::file::unlock(&directory, "a passphrase").unwrap(); - let tally = rewrap(&directory, &vault, "a new one", Cost::FOR_TESTS); - - assert_eq!(tally, Rewrapped { done: 0, left: 0 }); + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); + drop(connection); + + let missing = replace(scratch.path(), "missing", at(1)); + let keyless = replace(scratch.path(), &layout::stamp(at(0)), at(1)); + + assert!(matches!(missing, Err(StorageError::BackupNotFound(id)) if id == "missing")); + assert!(matches!(keyless, Err(StorageError::BackupUnopenable(_)))); + assert!(!scratch.path().join(REPLACED).exists()); + assert_eq!(titles_in(scratch.path(), PHRASE), ["Kept"]); } - mod restoring { - use super::*; - - /// Reads the one note's title straight out of a library on disk. - fn title_in(directory: &Path, passphrase: &str) -> String { - let vault = crate::vault::file::unlock(directory, passphrase).unwrap(); - let mut connection = db::open(&directory.join(layout::DATABASE), vault).unwrap(); - - notes::all(&mut connection, None).unwrap()[0].title.clone() - } - - fn retitle(connection: &mut Library, id: &str, title: &str) { - notes::update( - connection, - id, - &crate::notes::model::NotePatch { - title: Some(title.to_string()), - ..Default::default() - }, - at(1), - ) - .unwrap(); - } - - #[test] - fn the_copy_takes_the_place_of_the_live_library() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - retitle(&mut connection, ¬e, "écrit après la copie"); - drop(connection); - - replace(&directory, &id, at(30)).unwrap(); - - assert_eq!(title_in(&directory, "a passphrase"), "À sauvegarder"); + /// ⚠️ The id comes from the front end, and `../` still parses as a stamp. + #[test] + fn a_copy_is_found_by_its_listing_never_by_a_path() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + drop(connection); + let stamp = layout::stamp(at(0)); + let outside = scratch.path().join(&stamp); + std::fs::create_dir_all(&outside).unwrap(); + for name in [layout::DATABASE, KEY_FILE] { + std::fs::copy(copy.join(name), outside.join(name)).unwrap(); } - #[test] - fn the_library_it_replaced_is_still_readable_where_it_was_put() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, note) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - retitle(&mut connection, ¬e, "écrit après la copie"); - drop(connection); - - let aside = replace(&directory, &id, at(30)).unwrap(); - - assert!(aside.starts_with(directory.join(REPLACED))); - assert_eq!(title_in(&aside, "a passphrase"), "écrit après la copie"); - } + let refused = replace(scratch.path(), &format!("../{stamp}"), at(1)); - /// A database from one wrapping and a key file from another open nothing. - #[test] - fn the_key_file_goes_one_way_and_comes_back_the_other() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); + assert!(matches!(refused, Err(StorageError::BackupNotFound(_)))); + assert!(!scratch.path().join(REPLACED).exists()); + } - let aside = replace(&directory, &id, at(30)).unwrap(); + /// ⚠️ A restore that cannot finish must never leave no library at all. + #[test] + fn a_restore_that_cannot_set_the_live_key_aside_leaves_the_library_where_it_was() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + rotate(scratch.path(), &mut connection, at(0)).unwrap(); + drop(connection); + let database = std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(); + std::fs::rename(scratch.path().join(KEY_FILE), scratch.path().join("moved")).unwrap(); - assert!(directory.join(KEY_FILE).is_file()); - assert!(aside.join(KEY_FILE).is_file()); - } + let failed = replace(scratch.path(), &layout::stamp(at(0)), at(1)); - /// The live ones go aside with the database: one written since the copy is not lost, - /// and the restored records name only what the copy brought. - #[test] - fn the_attachments_come_back_with_the_copy() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - attach(&directory, "a-1.png", b"as copied"); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); - std::fs::remove_file(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(); - attach(&directory, "a-2.png", b"added since"); - - let aside = replace(&directory, &id, at(30)).unwrap(); - - assert_eq!( - std::fs::read(directory.join(ATTACHMENTS).join("a-1.png")).unwrap(), - b"as copied" - ); - assert!(!directory.join(ATTACHMENTS).join("a-2.png").exists()); - assert!(aside.join(ATTACHMENTS).join("a-2.png").is_file()); - } + assert!(matches!(failed, Err(StorageError::File(_)))); + assert_eq!(std::fs::read(scratch.path().join(layout::DATABASE)).unwrap(), database); + assert!(!scratch.path().join(REPLACED).join(layout::stamp(at(1))).exists()); + } - /// A failed copy leaves both halves as they were, directories included. - #[test] - fn putting_back_undoes_a_half_finished_restore() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - attach(&directory, "a-1.png", b"live"); - std::fs::write(directory.join(KEY_FILE), b"live key").unwrap(); - let aside = directory.join(REPLACED).join("2026-07-25_09-00-00"); - std::fs::create_dir_all(&aside).unwrap(); - let mut moved = Vec::new(); - for name in [KEY_FILE, ATTACHMENTS] { - std::fs::rename(directory.join(name), aside.join(name)).unwrap(); - moved.push((directory.join(name), aside.join(name))); - } - std::fs::write(directory.join(KEY_FILE), b"half copied").unwrap(); - attach(&directory, "from-the-copy.png", b"half"); + /// ⚠️ What makes a new phrase revoke anything: every retained copy's key file is rewrapped + /// from the key, so one wrapped under an older phrase goes too; a copy without one is + /// passed over. + #[test] + fn a_new_phrase_reaches_every_copy_s_key_file() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + let first = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let keyless = rotate(scratch.path(), &mut connection, at(48)).unwrap().unwrap(); + std::fs::remove_file(keyless.join(KEY_FILE)).unwrap(); + let vault = file::unlock(scratch.path(), PHRASE).unwrap(); + file::write_wrapped(&first.join(KEY_FILE), &vault, "an older one", Cost::FOR_TESTS).unwrap(); - put_back(&moved, &aside); + let tally = rewrap(scratch.path(), &vault, "the next passphrase", Cost::FOR_TESTS); - assert_eq!( - std::fs::read(directory.join(KEY_FILE)).unwrap(), - b"live key" - ); - assert!(directory.join(ATTACHMENTS).join("a-1.png").is_file()); - assert!( - !directory - .join(ATTACHMENTS) - .join("from-the-copy.png") - .exists() - ); - assert!(!aside.exists()); - } + assert_eq!(tally, Rewrapped { done: 1, left: 0 }); + assert!(matches!(file::unlock(&first, "an older one"), Err(StorageError::WrongPassphrase))); + assert_eq!(titles_in(&first, "the next passphrase"), ["Kept"]); + assert!(!keyless.join(KEY_FILE).exists()); + } - #[test] - fn an_id_cannot_name_a_directory_outside_the_copies() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); - drop(connection); - let outside = directory.join("2026-07-25_09-00-00"); - std::fs::create_dir_all(&outside).unwrap(); - std::fs::write(outside.join(layout::DATABASE), b"not a library").unwrap(); - std::fs::write(outside.join(KEY_FILE), b"{}").unwrap(); - - let refused = replace(&directory, "../2026-07-25_09-00-00", at(30)); - - assert!(refused.is_err()); - assert!( - directory.join(layout::DATABASE).is_file(), - "the library is still there" - ); - } + /// Counted rather than failed: a key file that cannot be rewritten must not block the + /// revocation at the moment it is asked for. + #[test] + fn a_key_file_that_cannot_be_rewritten_is_counted_as_left() { + let scratch = tempfile::tempdir().unwrap(); + let (mut connection, _) = library(scratch.path()); + let copy = rotate(scratch.path(), &mut connection, at(0)).unwrap().unwrap(); + let vault = file::unlock(scratch.path(), PHRASE).unwrap(); + let refused = Cost { memory_kib: 0, passes: 0, lanes: 0 }; - #[test] - fn a_copy_with_no_key_file_is_refused_rather_than_swapped_in() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - let copy = rotate(&directory, &mut connection, at(0)).unwrap().unwrap(); - let id = copy.file_name().unwrap().to_str().unwrap().to_string(); - drop(connection); - std::fs::remove_file(copy.join(KEY_FILE)).unwrap(); - - let refused = replace(&directory, &id, at(30)); - - assert!(refused.is_err()); - assert!(directory.join(layout::DATABASE).is_file()); - assert!(!directory.join(REPLACED).exists(), "nothing was set aside"); - } + let tally = rewrap(scratch.path(), &vault, "the next passphrase", refused); - #[test] - fn a_listing_says_when_each_copy_was_taken_and_whether_it_opens() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - rotate(&directory, &mut connection, at(0)).unwrap(); - rotate(&directory, &mut connection, at(25)).unwrap(); - - let copies = list(&directory); - - assert_eq!(copies.len(), 2); - // Newest first, the order the panel wants and the pruning uses. - assert_eq!(copies[0].taken_at, at(25)); - assert!(copies[0].bytes > 0); - assert!(copies.iter().all(|copy| copy.openable)); - } + assert_eq!(tally, Rewrapped { done: 0, left: 1 }); + assert_eq!(titles_in(©, PHRASE), ["Kept"]); } - /// A stray directory must not hold the rotation off by looking like the newest copy. + /// ⚠️ A name already there is the same attachment, often the very same file: copying over + /// it would truncate the source being read. #[test] - fn something_that_is_not_a_copy_is_ignored() { + fn linking_onto_a_name_already_there_leaves_both_whole() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let (mut connection, _) = library(&directory); - std::fs::create_dir_all(directory.join(BACKUPS).join("notes de Valentin")).unwrap(); + let (from, into) = (scratch.path().join("from"), scratch.path().join("into")); + std::fs::create_dir_all(&from).unwrap(); + std::fs::write(from.join("a-1.png"), b"the bytes").unwrap(); - let target = rotate(&directory, &mut connection, at(0)).unwrap(); + link_files(&from, &into).unwrap(); + link_files(&from, &into).unwrap(); - assert!(target.is_some()); + assert_eq!(std::fs::read(into.join("a-1.png")).unwrap(), b"the bytes"); + assert_eq!(std::fs::read(from.join("a-1.png")).unwrap(), b"the bytes"); } } diff --git a/crates/engine/src/changelog.rs b/crates/engine/src/changelog.rs index fc10237cc..eb67f7e05 100644 --- a/crates/engine/src/changelog.rs +++ b/crates/engine/src/changelog.rs @@ -33,11 +33,7 @@ mod tests { assert!(!releases.is_empty(), "the file describes no release"); for release in &releases { - assert!( - !release.sections.is_empty(), - "release {} carries no entry", - release.version - ); + assert!(!release.sections.is_empty(), "release {} carries no entry", release.version); for section in &release.sections { assert!( !section.items.is_empty(), @@ -68,36 +64,25 @@ mod tests { spans.iter().any(|span| span.kind == SpanKind::Code), "no entry in the file carries code any more" ); - assert!( - !spans.iter().any(|span| span.text.contains("**")), - "a marker reached the panel as text" - ); + assert!(!spans.iter().any(|span| span.text.contains("**")), "a marker reached the panel as text"); } /// What `release.yml` hands the updater is the newest section of this very file. #[test] fn the_newest_section_reads_the_same_alone_as_in_the_file() { let start = CHANGELOG.find("\n## ").expect("a release heading") + 1; - let body_start = CHANGELOG[start..] - .find('\n') - .map_or(CHANGELOG.len(), |at| start + at + 1); + let body_start = CHANGELOG[start..].find('\n').map_or(CHANGELOG.len(), |at| start + at + 1); let body_end = CHANGELOG[body_start..] .find("\n## ") .map_or(CHANGELOG.len(), |at| body_start + at); - assert_eq!( - release_notes(&CHANGELOG[body_start..body_end]), - app_changelog().remove(0).sections - ); + assert_eq!(release_notes(&CHANGELOG[body_start..body_end]), app_changelog().remove(0).sections); } #[test] fn the_shipped_file_shows_neither_the_site_nor_its_pages() { for heading in model::NOT_IN_THE_APP { - assert!( - CHANGELOG.contains(&format!("### {heading}\n")), - "{heading} is in no release" - ); + assert!(CHANGELOG.contains(&format!("### {heading}\n")), "{heading} is in no release"); } let shown: Vec<_> = app_changelog() .into_iter() @@ -105,27 +90,17 @@ mod tests { .map(|section| section.title) .collect(); - assert!( - !shown - .iter() - .any(|title| model::NOT_IN_THE_APP.contains(&title.as_str())) - ); + assert!(!shown.iter().any(|title| model::NOT_IN_THE_APP.contains(&title.as_str()))); } /// Written by the script, recognised here: a heading renamed on one side alone would reach /// the panel. #[test] fn the_headings_left_out_are_the_ones_the_release_script_writes() { - let script = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../scripts/release-notes.mjs" - )); + let script = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../scripts/release-notes.mjs")); for heading in model::NOT_IN_THE_APP { - assert!( - script.contains(&format!("heading: '{heading}'")), - "{heading}" - ); + assert!(script.contains(&format!("heading: '{heading}'")), "{heading}"); } } diff --git a/crates/engine/src/changelog/model.rs b/crates/engine/src/changelog/model.rs index 2e0df4df8..1d86adbeb 100644 --- a/crates/engine/src/changelog/model.rs +++ b/crates/engine/src/changelog/model.rs @@ -70,11 +70,7 @@ pub fn parse(markdown: &str) -> Vec { release.sections = sections.take(); } let (version, date) = split_heading(heading); - releases.push(ChangelogRelease { - version, - date, - sections: Vec::new(), - }); + releases.push(ChangelogRelease { version, date, sections: Vec::new() }); } else if !releases.is_empty() { // The preamble sits above the first release, with nothing to attach to. sections.read(line); @@ -128,10 +124,8 @@ impl Sections { /// `false` for a line the grammar has no place for. fn read(&mut self, line: &str) -> bool { if let Some(title) = line.strip_prefix("### ") { - self.sections.push(ChangelogSection { - title: title.trim().to_string(), - items: Vec::new(), - }); + self.sections + .push(ChangelogSection { title: title.trim().to_string(), items: Vec::new() }); self.item_open = false; } else if let Some(entry) = bullet(line) { self.current().items.push(spans(entry)); @@ -152,15 +146,10 @@ impl Sections { fn current(&mut self) -> &mut ChangelogSection { if self.sections.is_empty() { - self.sections.push(ChangelogSection { - title: String::new(), - items: Vec::new(), - }); + self.sections.push(ChangelogSection { title: String::new(), items: Vec::new() }); } - self.sections - .last_mut() - .expect("a section was just pushed if there was none") + self.sections.last_mut().expect("a section was just pushed if there was none") } fn take(&mut self) -> Vec { @@ -268,16 +257,9 @@ fn split_heading(heading: &str) -> (String, Option) { }, }; - let date = rest - .trim() - .trim_start_matches(['-', '–', '—']) - .trim() - .to_string(); + let date = rest.trim().trim_start_matches(['-', '–', '—']).trim().to_string(); - ( - version.trim().to_string(), - (!date.is_empty()).then_some(date), - ) + (version.trim().to_string(), (!date.is_empty()).then_some(date)) } #[cfg(test)] @@ -341,10 +323,7 @@ Everything above the first release is preamble. drop_what_is_not_in_the_app(&mut sections); - let titles: Vec<_> = sections - .iter() - .map(|section| section.title.as_str()) - .collect(); + let titles: Vec<_> = sections.iter().map(|section| section.title.as_str()).collect(); assert_eq!(titles, ["✨ Added", "🧰 Under the hood"]); } @@ -379,10 +358,7 @@ Everything above the first release is preamble. #[test] fn keeps_a_dash_inside_a_version_out_of_the_date() { - assert_eq!( - split_heading("1.0.0-rc.1"), - ("1.0.0-rc.1".to_string(), None) - ); + assert_eq!(split_heading("1.0.0-rc.1"), ("1.0.0-rc.1".to_string(), None)); assert_eq!( split_heading("[1.0.0-rc.1] - 2026-01-01"), ("1.0.0-rc.1".to_string(), Some("2026-01-01".to_string())) @@ -410,9 +386,7 @@ Everything above the first release is preamble. use super::*; fn only(markdown: &str) -> ChangelogEntry { - parse(&format!("## 0.1.0\n\n- {markdown}\n")) - .remove(0) - .sections[0] + parse(&format!("## 0.1.0\n\n- {markdown}\n")).remove(0).sections[0] .items .remove(0) } @@ -445,22 +419,14 @@ Everything above the first release is preamble. fn the_pull_request_number_is_dropped() { assert_eq!( only("Let the library rail go down to 160px (#213)"), - vec![ChangelogSpan::plain( - "Let the library rail go down to 160px".to_string() - )] + vec![ChangelogSpan::plain("Let the library rail go down to 160px".to_string())] ); } #[test] fn something_that_only_looks_like_a_number_is_left_alone() { - assert_eq!( - read(&only("Read the guide (#start here)")), - "Read the guide (#start here)" - ); - assert_eq!( - read(&only("Nothing in brackets (#)")), - "Nothing in brackets (#)" - ); + assert_eq!(read(&only("Read the guide (#start here)")), "Read the guide (#start here)"); + assert_eq!(read(&only("Nothing in brackets (#)")), "Nothing in brackets (#)"); } /// Unclosed is text: an entry about `5 * 3` has to stay readable. @@ -468,9 +434,7 @@ Everything above the first release is preamble. fn a_lone_marker_is_text() { assert_eq!( only("5 * 3 and a ** that closes nothing"), - vec![ChangelogSpan::plain( - "5 * 3 and a ** that closes nothing".to_string() - )] + vec![ChangelogSpan::plain("5 * 3 and a ** that closes nothing".to_string())] ); } @@ -499,10 +463,7 @@ Everything above the first release is preamble. use super::*; fn titles(sections: &[ChangelogSection]) -> Vec<&str> { - sections - .iter() - .map(|section| section.title.as_str()) - .collect() + sections.iter().map(|section| section.title.as_str()).collect() } #[test] @@ -552,4 +513,25 @@ Everything above the first release is preamble. assert!(parse_section("\n \n").is_empty()); } } + + /// Glued to the entry above, a line of the next section would read as its end. + #[test] + fn a_heading_closes_the_entry_above_it() { + for heading in ["# Titre", "## [0.9.2]"] { + let sections = parse_section(&format!("- One.\n{heading}\n Loose.\n")); + assert_eq!(reads(§ions[0]), ["One.", "Loose."], "{heading}"); + } + let sections = parse_section("- One.\n### Fixed\n Loose.\n"); + assert_eq!( + (reads(§ions[0]), reads(§ions[1])), + (vec!["One.".to_owned()], vec!["Loose.".to_owned()]) + ); + } + + #[test] + fn a_dash_with_nothing_after_it_is_no_entry() { + let releases = parse("## 0.1.0\n\n- \n* Starred.\n-\n"); + + assert_eq!(reads(&releases[0].sections[0]), ["Starred. -"]); + } } diff --git a/crates/engine/src/closed_enum.rs b/crates/engine/src/closed_enum.rs index 8cfa4c41a..308438846 100644 --- a/crates/engine/src/closed_enum.rs +++ b/crates/engine/src/closed_enum.rs @@ -57,3 +57,41 @@ macro_rules! closed_enum { } pub(crate) use crate::closed_enum; + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + closed_enum! { + enum Shade { + #[default] + Light = "light", + Dark = "dark-ish", + } + } + + #[test] + fn every_variant_is_listed_once_in_declaration_order() { + assert_eq!(Shade::ALL, [Shade::Light, Shade::Dark]); + } + + #[test] + fn one_spelling_serves_display_parsing_and_serde() { + for shade in Shade::ALL { + let spelling = shade.as_str(); + + assert_eq!(shade.to_string(), spelling); + assert_eq!(Shade::from_str(spelling), Ok(shade)); + assert_eq!(serde_json::to_string(&shade).unwrap(), format!("\"{spelling}\"")); + assert_eq!(serde_json::from_str::(&format!("\"{spelling}\"")).unwrap(), shade); + } + } + + #[test] + fn a_spelling_it_never_heard_of_is_refused() { + for unknown in ["", "Light", "dark", "dark-ish "] { + assert_eq!(Shade::from_str(unknown), Err(()), "{unknown:?}"); + assert!(serde_json::from_str::(&format!("\"{unknown}\"")).is_err()); + } + } +} diff --git a/crates/engine/src/db.rs b/crates/engine/src/db.rs index 13cdf82b6..f2e1b15eb 100644 --- a/crates/engine/src/db.rs +++ b/crates/engine/src/db.rs @@ -79,9 +79,7 @@ impl Library { F: FnOnce(&mut SqliteConnection, &Vault) -> Result, { // Destructured so the two disjoint fields borrow separately. - let Self { - connection, vault, .. - } = self; + let Self { connection, vault, .. } = self; connection.transaction(|connection| f(connection, vault)) } } @@ -95,10 +93,7 @@ pub type Db = Mutex>; /// ⚠️ On the db thread alone (`queue`), checked in debug builds; the crate's own unit tests /// lock their in-memory libraries on the test thread. pub(crate) fn lock(db: &Db) -> Result, StorageError> { - debug_assert!( - cfg!(test) || queue::on_db_thread(), - "the library is locked off the db thread" - ); + debug_assert!(cfg!(test) || queue::on_db_thread(), "the library is locked off the db thread"); let guard = db.lock().map_err(|_| StorageError::Unavailable)?; if guard.is_none() { return Err(StorageError::Locked); @@ -120,10 +115,7 @@ where /// [`run`], queued at the call rather than at the first poll: the interface sends from its /// thread and waits elsewhere, and two jobs sent in a row must still run in that order. -pub fn submit( - engine: &Arc, - job: F, -) -> impl Future> + use +pub fn submit(engine: &Arc, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce(&Engine) -> Result + Send + 'static, @@ -189,25 +181,30 @@ pub(crate) fn quick_check(connection: &mut SqliteConnection) -> Result<(), Stora )) } +/// A file whose first page SQLite cannot read: the check that names a damage never runs, and +/// diesel hands SQLite's words without their code. +fn is_unreadable(error: &StorageError) -> bool { + let said = error.to_string(); + ["file is not a database", "database disk image is malformed"] + .iter() + .any(|words| said.contains(words)) +} + /// Every failure names the file: this is the error a user meets before any window has /// anything in it, and the database sits in a directory they have never opened. pub fn open(path: &Path, vault: Vault) -> Result { - let named = |error: &dyn std::fmt::Display| { - StorageError::Migration(format!("{}: {error}", path.display())) - }; + let named = + |error: &dyn std::fmt::Display| StorageError::Migration(format!("{}: {error}", path.display())); let mut connection = SqliteConnection::establish(&path.to_string_lossy()).map_err(|error| named(&error))?; - configure(&mut connection).map_err(|error| named(&error))?; + let damaged = |error: &StorageError| StorageError::Damaged(format!("{}: {error}", path.display())); + configure(&mut connection) + .map_err(|error| if is_unreadable(&error) { damaged(&error) } else { named(&error) })?; // ⚠️ Before the migrations, which write: running them over a damaged file is how a // salvageable database becomes an unsalvageable one. - if let Err(error) = quick_check(&mut connection) { - return Err(StorageError::Damaged(format!( - "{}: {error}", - path.display() - ))); - } + quick_check(&mut connection).map_err(|error| damaged(&error))?; migration::run(&mut connection).map_err(|error| named(&error))?; @@ -231,8 +228,7 @@ pub fn open_in_memory() -> Result { connection, vault: Arc::new(test_vault()?), // Named, never created: a test writing beside the library fails loudly. - directory: std::env::temp_dir() - .join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), + directory: std::env::temp_dir().join(format!("devnotes-in-memory-{}", uuid::Uuid::new_v4())), number: next_number(), }) } @@ -241,8 +237,7 @@ impl Library { /// Once the index holds every body, nothing reads the file end to end again, and what stays /// mapped stays in the process. Before that, the mapping is what makes the fill fast. pub(crate) fn map_less(&mut self) -> Result<(), StorageError> { - self.connection - .batch_execute("PRAGMA mmap_size = 67108864;")?; + self.connection.batch_execute("PRAGMA mmap_size = 67108864;")?; Ok(()) } } @@ -251,11 +246,7 @@ impl Library { /// what the tests and the benchmarks need. #[doc(hidden)] pub fn test_vault() -> Result { - Vault::derive( - "in-memory", - b"0123456789abcdef", - crate::vault::key::Cost::FOR_TESTS, - ) + Vault::derive("in-memory", b"0123456789abcdef", crate::vault::key::Cost::FOR_TESTS) } fn configure(connection: &mut SqliteConnection) -> Result<(), StorageError> { @@ -326,174 +317,171 @@ pub mod iso8601 { #[cfg(test)] mod tests { use super::*; - use diesel::sql_types::{BigInt, Integer}; + use diesel::sql_types::BigInt; - fn in_memory() -> Db { - Mutex::new(Some(open_in_memory().unwrap())) + /// A pragma of this connection, as SQLite answers it. + fn pragma(library: &mut Library, name: &str) -> i64 { + #[derive(QueryableByName)] + struct Value { + #[diesel(sql_type = BigInt)] + value: i64, + } + + diesel::sql_query(format!( + "WITH found(value) AS (SELECT * FROM pragma_{name}) SELECT value FROM found" + )) + .get_result::(library.db()) + .unwrap() + .value } - /// Stays here rather than in `tests/`: `configure` is private. - #[test] - fn foreign_keys_are_enforced() { + /// Apart: SQLite has no table of this one. + fn mapped(library: &mut Library) -> i64 { #[derive(QueryableByName)] - struct ForeignKeys { - #[diesel(sql_type = Integer)] - foreign_keys: i32, + struct Value { + #[diesel(sql_type = BigInt)] + mmap_size: i64, } - let mut connection = open_in_memory().unwrap(); - - let enabled = diesel::sql_query("PRAGMA foreign_keys") - .get_result::(connection.db()) + diesel::sql_query("PRAGMA mmap_size") + .get_result::(library.db()) .unwrap() - .foreign_keys; - - assert_eq!(enabled, 1); + .mmap_size } - /// SQLite would otherwise meet the damage on whichever query reads the broken page, days - /// later, with every launch copy a copy of the broken file. - #[test] - fn a_damaged_file_is_named_as_such_rather_than_opened() { - let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); - let path = directory.join(crate::layout::DATABASE); + fn opened(scratch: &tempfile::TempDir) -> Library { + let path = scratch.path().join(crate::layout::DATABASE); + open(&path, test_vault().unwrap()).unwrap() + } - // A real library, with enough in it to fill more than the first page. - { - let mut library = open(&path, test_vault().unwrap()).unwrap(); - for at in 0..40 { - crate::spaces::store::create(&mut library, &format!("Space {at}")).unwrap(); - } - } + fn spaces(library: &mut Library) -> usize { + crate::spaces::store::list(library).unwrap().len() + } - // Garbage past the header: a broken header fails to open rather than to check. - let mut bytes = std::fs::read(&path).unwrap(); - assert!(bytes.len() > 4096, "the corpus did not reach a second page"); - for byte in bytes.iter_mut().skip(4096).take(512) { - *byte = 0x42; + /// Why opening was refused. Not `unwrap_err`: it would want `Library: Debug`, and a library + /// holds the key. + fn refusal(path: &Path) -> StorageError { + match open(path, test_vault().unwrap()) { + Ok(_) => panic!("{} opened", path.display()), + Err(error) => error, } - std::fs::write(&path, &bytes).unwrap(); - - let Err(error) = open(&path, test_vault().unwrap()) else { - panic!("a damaged database opened as if it were sound"); - }; - - assert!(matches!(error, StorageError::Damaged(_)), "{error}"); - assert!( - format!("{error}").contains(&path.display().to_string()), - "the failure does not name the file: {error}" - ); } - /// A sound library answers the check and says nothing about it. + /// Each is per connection and not SQLite's default: cascades enforced, a file another + /// process holds waited for, commits not flushed one by one, the file read through a mapping. #[test] - fn a_sound_library_passes_the_check_it_runs_at_every_open() { - let mut library = open_in_memory().unwrap(); + fn a_library_is_opened_with_its_pragmas() { + let scratch = tempfile::tempdir().unwrap(); + let mut library = opened(&scratch); - assert!(quick_check(library.db()).is_ok()); + for (name, value) in [("foreign_keys", 1), ("busy_timeout", 5000), ("synchronous", 1)] { + assert_eq!(pragma(&mut library, name), value, "{name}"); + } + // A build of SQLite whose ceiling is lower answers that ceiling. + assert_eq!(mapped(&mut library), 1 << 30); } #[test] - fn a_database_that_will_not_open_says_which_file() { + fn the_mapping_shrinks_once_the_index_is_read() { let scratch = tempfile::tempdir().unwrap(); - let directory = scratch.path().to_path_buf(); + let mut library = opened(&scratch); - // A directory fails to open the way a corrupt file or a permission would. - // Destructured: `unwrap_err` would want `Library: Debug`, and a library holds the key. - let Err(error) = open(&directory, test_vault().unwrap()) else { - panic!("a directory opened as a database"); - }; + library.map_less().unwrap(); - assert!( - format!("{error}").contains(&directory.display().to_string()), - "the failure does not name the file: {error}" - ); + assert_eq!(mapped(&mut library), 1 << 26); } - /// SQLite's default of zero turns a file another process holds for a moment into a - /// storage error on the first write. #[test] - fn a_locked_database_is_waited_on_rather_than_reported() { - #[derive(QueryableByName)] - struct BusyTimeout { - #[diesel(sql_type = Integer)] - timeout: i32, - } + fn a_library_knows_the_folder_it_is_in_and_is_numbered_once() { + let scratch = tempfile::tempdir().unwrap(); - let mut connection = open_in_memory().unwrap(); + let (first, second) = (opened(&scratch), opened(&scratch)); - let timeout = diesel::sql_query("PRAGMA busy_timeout") - .get_result::(connection.db()) - .unwrap() - .timeout; - - assert_eq!(timeout, 5000); + assert_eq!(first.directory(), scratch.path()); + assert!(first.number() > 0 && second.number() > first.number()); } - /// `NORMAL` can lose the last commit to a power cut, and cannot corrupt the file. + /// Every function that writes several rows counts on it. #[test] - fn commits_are_not_fsynced_one_by_one() { - #[derive(QueryableByName)] - struct Synchronous { - #[diesel(sql_type = Integer)] - synchronous: i32, - } - - let mut connection = open_in_memory().unwrap(); + fn a_transaction_that_fails_keeps_nothing_of_what_it_wrote() { + let mut library = open_in_memory().unwrap(); + crate::spaces::store::create(&mut library, "Kept").unwrap(); + let before = spaces(&mut library); - let level = diesel::sql_query("PRAGMA synchronous") - .get_result::(connection.db()) - .unwrap() - .synchronous; + let failed: Result<(), StorageError> = library.transaction(|connection, _| { + diesel::sql_query("DELETE FROM spaces").execute(connection)?; + Err(StorageError::Unavailable) + }); - assert_eq!(level, 1); + assert!(matches!(failed, Err(StorageError::Unavailable))); + assert_eq!(spaces(&mut library), before); } - /// Asked of a file: an in-memory database has nothing to map. A build of SQLite whose - /// ceiling is lower answers that ceiling, and the corpus would be read through the cache. #[test] - fn the_file_is_read_through_a_mapping() { - #[derive(QueryableByName)] - struct MmapSize { - #[diesel(sql_type = BigInt)] - mmap_size: i64, - } + fn a_sound_library_passes_the_check_run_at_every_open() { + let mut library = open_in_memory().unwrap(); + + assert!(quick_check(library.db()).is_ok()); + } + /// SQLite would otherwise meet the damage on whichever query reads the broken page, days + /// later, with every launch copy a copy of the broken file. + #[test] + fn a_damaged_file_is_named_as_such_rather_than_opened() { let scratch = tempfile::tempdir().unwrap(); - let mut library = open(&scratch.path().join("notes.db"), test_vault().unwrap()).unwrap(); + let path = scratch.path().join(crate::layout::DATABASE); + // A real library, with enough in it to fill more than the first page. + { + let mut library = opened(&scratch); + for at in 0..40 { + crate::spaces::store::create(&mut library, &format!("Space {at}")).unwrap(); + } + } + let mut bytes = std::fs::read(&path).unwrap(); + assert!(bytes.len() > 4096, "the corpus did not reach a second page"); + bytes[4096..4096 + 512].fill(0x42); + std::fs::write(&path, &bytes).unwrap(); - let size = diesel::sql_query("PRAGMA mmap_size") - .get_result::(library.db()) - .unwrap() - .mmap_size; + let error = refusal(&path); - assert_eq!(size, 1 << 30); + assert!(matches!(error, StorageError::Damaged(_)), "{error}"); + let named = path.display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); } + /// The check never runs on a first page nothing reads: the first statement fails. #[test] - fn the_mapping_shrinks_once_the_index_is_read() { - #[derive(QueryableByName)] - struct MmapSize { - #[diesel(sql_type = BigInt)] - mmap_size: i64, + fn a_file_whose_first_page_is_damaged_is_named_as_such_too() { + for from in [0, 100] { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join(crate::layout::DATABASE); + drop(opened(&scratch)); + let mut bytes = std::fs::read(&path).unwrap(); + bytes[from..].fill(0x42); + std::fs::write(&path, &bytes).unwrap(); + + let error = refusal(&path); + + assert!(matches!(error, StorageError::Damaged(_)), "{from}: {error}"); + let named = path.display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); } + } + /// A directory fails to open the way a permission would. + #[test] + fn a_database_that_will_not_open_says_which_file() { let scratch = tempfile::tempdir().unwrap(); - let mut library = open(&scratch.path().join("notes.db"), test_vault().unwrap()).unwrap(); - library.map_less().unwrap(); + let error = refusal(scratch.path()); - let size = diesel::sql_query("PRAGMA mmap_size") - .get_result::(library.db()) - .unwrap() - .mmap_size; - assert_eq!(size, 1 << 26); + let named = scratch.path().display().to_string(); + assert!(error.to_string().contains(&named), "{error}"); } #[test] - fn a_healthy_connection_is_handed_over() { - let db = in_memory(); + fn the_library_open_is_handed_over() { + let db: Db = Mutex::new(Some(open_in_memory().unwrap())); assert!(lock(&db).is_ok()); } @@ -503,10 +491,34 @@ mod tests { fn a_library_still_locked_is_reported_rather_than_unwrapped() { let db: Db = Mutex::new(None); - let Err(error) = lock(&db) else { - panic!("a locked library must be reported, not handed over"); - }; + assert!(matches!(lock(&db).map(drop), Err(StorageError::Locked))); + let sent = lock_library(&db, 1).map(drop); + assert!(matches!(sent, Err(StorageError::Locked))); + } + + #[test] + fn a_lock_a_panic_left_behind_is_unavailable() { + let db: Arc = Arc::new(Mutex::new(None)); + let holding = Arc::clone(&db); + let _ = std::thread::spawn(move || { + let _held = holding.lock(); + panic!("while holding the library"); + }) + .join(); + + assert!(matches!(lock(&db).map(drop), Err(StorageError::Unavailable))); + } + + /// A send writes only into the library it read from. + #[test] + fn a_library_opened_since_is_not_the_one_a_send_read_from() { + let library = open_in_memory().unwrap(); + let number = library.number(); + let db: Db = Mutex::new(Some(library)); + + assert!(lock_library(&db, number).unwrap().is_some()); - assert!(matches!(error, StorageError::Locked)); + *db.lock().unwrap() = Some(open_in_memory().unwrap()); + assert!(lock_library(&db, number).unwrap().is_none()); } } diff --git a/crates/engine/src/db/migration.rs b/crates/engine/src/db/migration.rs index c0335d6cc..e0accd159 100644 --- a/crates/engine/src/db/migration.rs +++ b/crates/engine/src/db/migration.rs @@ -88,11 +88,9 @@ mod tests { #[test] fn a_migration_this_binary_does_not_know_is_refused() { let mut connection = open_in_memory().unwrap(); - diesel::sql_query( - "INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')", - ) - .execute(connection.db()) - .unwrap(); + diesel::sql_query("INSERT INTO __diesel_schema_migrations (version) VALUES ('2099-01-01-000000')") + .execute(connection.db()) + .unwrap(); let error = run(connection.db()).unwrap_err(); diff --git a/crates/engine/src/db/queue.rs b/crates/engine/src/db/queue.rs index d8b66c5b9..bc92febec 100644 --- a/crates/engine/src/db/queue.rs +++ b/crates/engine/src/db/queue.rs @@ -60,10 +60,7 @@ impl DbQueue { /// Queues `job` now, in the caller's order, and answers a future of its result: what /// keeps two calls made one after the other in that order when the waiting is done /// elsewhere. - pub(crate) fn submit( - &self, - job: F, - ) -> impl Future> + use + pub(crate) fn submit(&self, job: F) -> impl Future> + use where T: Send + 'static, F: FnOnce() -> Result + Send + 'static, @@ -86,12 +83,10 @@ mod tests { use std::sync::{Arc, Mutex}; use super::*; + use crate::error::ErrorCode; fn block_on(future: impl Future) -> T { - tokio::runtime::Builder::new_current_thread() - .build() - .unwrap() - .block_on(future) + tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(future) } #[test] @@ -115,4 +110,63 @@ mod tests { assert_eq!(*order.lock().unwrap(), [(1, true), (2, true), (3, true)]); assert!(!on_db_thread()); } + + /// The interface sends from its thread and waits elsewhere, in whatever order. + #[test] + fn a_job_submitted_is_queued_at_the_call_whenever_it_is_waited_for() { + let queue = DbQueue::start(); + let order = Arc::new(Mutex::new(Vec::new())); + let job = |n: u32| { + let order = Arc::clone(&order); + queue.submit(move || { + order.lock().unwrap().push(n); + Ok(n) + }) + }; + let (first, second) = (job(1), job(2)); + + let answers = block_on(async { (second.await.unwrap(), first.await.unwrap()) }); + + assert_eq!(answers, (2, 1)); + assert_eq!(*order.lock().unwrap(), [1, 2]); + } + + #[test] + fn a_job_s_own_failure_is_its_answer() { + let queue = DbQueue::start(); + + let failed = block_on(queue.run(|| Err::<(), _>(StorageError::Locked.into()))); + + assert_eq!(failed.unwrap_err().code, ErrorCode::Locked); + } + + /// A panic ends the process (D18); what waits meanwhile is answered rather than held. + #[test] + fn a_job_that_panics_and_those_after_it_are_answered_unavailable() { + let queue = DbQueue::start(); + + let fell = block_on(queue.run(|| -> Result<(), AppError> { panic!("a job fell") })); + let after = block_on(queue.run(|| Ok(()))); + + assert_eq!(fell.unwrap_err().code, ErrorCode::StorageUnavailable); + assert_eq!(after.unwrap_err().code, ErrorCode::StorageUnavailable); + } + + #[test] + fn a_queue_dropped_still_runs_what_it_was_sent() { + let queue = DbQueue::start(); + let sent = queue.submit(|| Ok(1)); + drop(queue); + + assert_eq!(block_on(sent).unwrap(), 1); + } + + /// Nested, as an integration test calling one data function inside another. + #[test] + fn a_thread_taken_for_the_db_one_is_itself_again_after() { + let nested = as_db_thread(|| as_db_thread(on_db_thread) && on_db_thread()); + + assert!(nested); + assert!(!on_db_thread()); + } } diff --git a/crates/engine/src/docs.rs b/crates/engine/src/docs.rs index 30b41b527..1a0340186 100644 --- a/crates/engine/src/docs.rs +++ b/crates/engine/src/docs.rs @@ -10,10 +10,7 @@ use model::{Index, Page}; // `SOURCES`: each file of `docs/content/`, by language and page, written by `build.rs`. include!(concat!(env!("OUT_DIR"), "/docs.rs")); -const INDEX: &str = include_str!(concat!( - env!("CARGO_MANIFEST_DIR"), - "/../../docs/content/index.json" -)); +const INDEX: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../docs/content/index.json")); static READ_INDEX: LazyLock = LazyLock::new(|| serde_json::from_str(INDEX).expect("compiled in, and held by a test")); @@ -29,12 +26,8 @@ pub fn docs_index() -> &'static Index { /// A page in a language, by its name in the index. pub fn docs_page(language: &str, id: &str) -> Option<&'static Page> { - let at = SOURCES - .iter() - .position(|source| source.0 == language && source.1 == id)?; - PAGES[at] - .get_or_init(|| model::read(id, SOURCES[at].2).ok()) - .as_ref() + let at = SOURCES.iter().position(|source| source.0 == language && source.1 == id)?; + PAGES[at].get_or_init(|| model::read(id, SOURCES[at].2).ok()).as_ref() } #[cfg(test)] @@ -47,10 +40,7 @@ mod tests { const LANGUAGES: [&str; 2] = ["fr", "en"]; fn ids() -> Vec<&'static str> { - docs_index() - .pages() - .map(|entry| entry.id.as_str()) - .collect() + docs_index().pages().map(|entry| entry.id.as_str()).collect() } fn runs(block: &Block) -> Vec<&Inline> { @@ -124,10 +114,7 @@ mod tests { let mut sections = Vec::new(); for block in &page.body { if let Block::Heading { id: section, .. } = block { - assert!( - !sections.contains(§ion), - "{language}/{id}.md: {section}" - ); + assert!(!sections.contains(§ion), "{language}/{id}.md: {section}"); sections.push(section); } } @@ -137,17 +124,8 @@ mod tests { #[test] fn every_link_leads_to_a_page_and_a_section_that_exist() { for (language, id, _) in SOURCES { - for run in docs_page(language, id) - .expect(id) - .body - .iter() - .flat_map(runs) - { - let Inline::Link { - text, - to: Target::Page { id: to, section }, - } = run - else { + for run in docs_page(language, id).expect(id).body.iter().flat_map(runs) { + let Inline::Link { text, to: Target::Page { id: to, section } } = run else { continue; }; let name = format!("docs/content/{language}/{id}.md: « {text} »"); @@ -170,11 +148,7 @@ mod tests { Block::Pages(pages) => Some(pages.clone()), _ => None, }); - assert_eq!( - listed.unwrap_or_default(), - ids()[1..], - "{language}/overview.md" - ); + assert_eq!(listed.unwrap_or_default(), ids()[1..], "{language}/overview.md"); } } diff --git a/crates/engine/src/docs/model.rs b/crates/engine/src/docs/model.rs index 33f55321f..2ceda14e4 100644 --- a/crates/engine/src/docs/model.rs +++ b/crates/engine/src/docs/model.rs @@ -163,9 +163,7 @@ pub fn read(id: &str, markdown: &str) -> Reading { let mut reader = Reader { id, markdown, - events: Parser::new_ext(markdown, options) - .into_offset_iter() - .collect(), + events: Parser::new_ext(markdown, options).into_offset_iter().collect(), at: 0, }; reader.page() @@ -181,10 +179,7 @@ struct Reader<'a> { impl<'a> Reader<'a> { fn page(&mut self) -> Reading { let title = match self.next() { - Some(Event::Start(Tag::Heading { - level: HeadingLevel::H1, - .. - })) => self.plain()?, + Some(Event::Start(Tag::Heading { level: HeadingLevel::H1, .. })) => self.plain()?, _ => return self.refuse("a page begins with # and its title"), }; let summary = match self.next() { @@ -196,21 +191,13 @@ impl<'a> Reader<'a> { while self.at < self.events.len() { body.push(self.titled_block()?); } - Ok(Page { - id: self.id.to_owned(), - title, - summary, - body, - }) + Ok(Page { id: self.id.to_owned(), title, summary, body }) } /// A block, and the title of a table or a code block: the bold line just above it. fn titled_block(&mut self) -> Reading { let first = self.block(None)?; - let titled = matches!( - self.peek(), - Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_))) - ); + let titled = matches!(self.peek(), Some(Event::Start(Tag::Table(_) | Tag::CodeBlock(_)))); match first { Block::Paragraph(text) if titled => match text.as_slice() { [Inline::Strong(title)] => self.block(Some(title)), @@ -248,11 +235,7 @@ impl<'a> Reader<'a> { _ => return self.refuse("a section is ## or ###"), }; let text = self.plain()?; - Ok(Block::Heading { - level, - id: slug(&text), - text, - }) + Ok(Block::Heading { level, id: slug(&text), text }) } fn list(&mut self, ordered: bool) -> Reading { @@ -289,11 +272,7 @@ impl<'a> Reader<'a> { CodeBlockKind::Fenced(language) => language.to_string(), CodeBlockKind::Indented => return self.refuse("a code block is between ```"), }; - Ok(Block::Code { - title: title.to_owned(), - language, - text: text.trim_end_matches('\n').to_owned(), - }) + Ok(Block::Code { title: title.to_owned(), language, text: text.trim_end_matches('\n').to_owned() }) } fn table(&mut self, title: &str) -> Reading { @@ -319,29 +298,21 @@ impl<'a> Reader<'a> { .collect::>(); let title = title.to_owned(); if !SHORTCUTS.contains(&head[0].as_str()) { - return Ok(Block::Table { - title, - head, - rows: rows.collect(), - }); + return Ok(Block::Table { title, head, rows: rows.collect() }); } let mut shortcuts = Vec::new(); for row in rows { match row.as_slice() { [keys, does] => match keys.as_slice() { - [Inline::Keys(keys)] => shortcuts.push(Shortcut { - keys: keys.clone(), - does: text_of(does), - }), + [Inline::Keys(keys)] => { + shortcuts.push(Shortcut { keys: keys.clone(), does: text_of(does) }); + } _ => return self.refuse("a table of shortcuts holds one per row"), }, _ => return self.refuse("a table of shortcuts has two columns"), } } - Ok(Block::Shortcuts { - title, - rows: shortcuts, - }) + Ok(Block::Shortcuts { title, rows: shortcuts }) } /// What an item or a note holds: one paragraph, marked as such or not. @@ -368,10 +339,9 @@ impl<'a> Reader<'a> { Some(Event::Code(code)) => Inline::Code(code.to_string()), Some(Event::Start(Tag::Strong)) => Inline::Strong(self.plain()?), Some(Event::Start(Tag::Emphasis)) => Inline::Label(self.plain()?), - Some(Event::Start(Tag::Link { dest_url, .. })) => Inline::Link { - text: self.plain()?, - to: self.target(&dest_url)?, - }, + Some(Event::Start(Tag::Link { dest_url, .. })) => { + Inline::Link { text: self.plain()?, to: self.target(&dest_url)? } + } Some(Event::InlineHtml(tag)) if &*tag == "" => Inline::Keys(self.keys()?), Some(other) => return self.refuse(format!("{other:?} is not read")), }; @@ -417,10 +387,7 @@ impl<'a> Reader<'a> { None if file.is_empty() && section.is_some() => self.id, _ => return self.refuse(format!("{href} leads nowhere")), }; - Ok(Target::Page { - id: id.to_owned(), - section, - }) + Ok(Target::Page { id: id.to_owned(), section }) } fn peek(&self) -> Option<&Event<'a>> { @@ -435,26 +402,15 @@ impl<'a> Reader<'a> { /// At the event just read. fn refuse(&self, message: impl Into) -> Reading { - let at = self - .events - .get(self.at.saturating_sub(1)) - .map_or(0, |(_, range)| range.start); - Err(Refusal { - line: self.markdown[..at].matches('\n').count() + 1, - message: message.into(), - }) + let at = self.events.get(self.at.saturating_sub(1)).map_or(0, |(_, range)| range.start); + Err(Refusal { line: self.markdown[..at].matches('\n').count() + 1, message: message.into() }) } } /// The page an item leads to, when it is a link to it and nothing more. fn only_page(item: &[Inline]) -> Option { match item { - [ - Inline::Link { - to: Target::Page { id, section: None }, - .. - }, - ] => Some(id.clone()), + [Inline::Link { to: Target::Page { id, section: None }, .. }] => Some(id.clone()), _ => None, } } @@ -499,10 +455,7 @@ mod tests { #[test] fn a_page_opens_on_its_title_and_its_summary() { let page = read("page", HEAD).expect("a page"); - assert_eq!( - (page.title.as_str(), page.summary.as_str()), - ("Titre", "Résumé.") - ); + assert_eq!((page.title.as_str(), page.summary.as_str()), ("Titre", "Résumé.")); assert!(page.body.is_empty()); let refusal = read("page", "Sans titre.\n").expect_err("no title"); @@ -530,10 +483,7 @@ mod tests { text(" ou "), Inline::Link { text: "là".to_owned(), - to: Target::Page { - id: "start".to_owned(), - section: Some("cle-maitre".to_owned()), - }, + to: Target::Page { id: "start".to_owned(), section: Some("cle-maitre".to_owned()) }, }, text("."), ])] @@ -549,13 +499,7 @@ mod tests { }, other => panic!("{other:?}"), }; - assert_eq!( - to("[a](#ici)"), - Target::Page { - id: "page".to_owned(), - section: Some("ici".to_owned()), - } - ); + assert_eq!(to("[a](#ici)"), Target::Page { id: "page".to_owned(), section: Some("ici".to_owned()) }); assert_eq!( to("[a](https://devnotes.fr/telecharger)"), Target::Address("https://devnotes.fr/telecharger".to_owned()) @@ -567,10 +511,7 @@ mod tests { fn a_list_of_nothing_but_pages_is_the_list_of_them() { assert_eq!( body("- [Écrire](writing.md)\n- [Ranger](organising.md)\n"), - [Block::Pages(vec![ - "writing".to_owned(), - "organising".to_owned() - ])] + [Block::Pages(vec!["writing".to_owned(), "organising".to_owned()])] ); assert_eq!( body("1. un\n2. *deux*\n"), @@ -600,10 +541,7 @@ mod tests { [Block::Table { title: "Fichiers".to_owned(), head: vec!["Système".to_owned(), "Fichier".to_owned()], - rows: vec![vec![ - vec![text("Linux")], - vec![Inline::Code("a|b".to_owned())] - ]], + rows: vec![vec![vec![text("Linux")], vec![Inline::Code("a|b".to_owned())]]], }] ); assert_eq!( @@ -621,9 +559,8 @@ mod tests { #[test] fn a_table_headed_by_the_keys_is_one_of_shortcuts() { for head in SHORTCUTS { - let table = format!( - "**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n" - ); + let table = + format!("**Palette**\n\n| {head} | Action |\n| --- | --- |\n| ↑ ↓ | Choisir |\n"); assert_eq!( body(&table), [Block::Shortcuts { @@ -649,9 +586,7 @@ mod tests { "- un\n - dedans\n", "> [!TIP]\n> un\n>\n> deux\n", ] { - assert!( - refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8']) - ); + assert!(refused(markdown).starts_with('5') || refused(markdown).starts_with(['6', '8'])); } } @@ -661,4 +596,33 @@ mod tests { assert_eq!(slug("où-vont-mes-notes-"), "ou-vont-mes-notes"); assert_eq!(slug("L’API : `GET`, « v1 »"), "lapi-get-v1"); } + + #[test] + fn a_link_is_an_address_by_its_scheme_and_a_page_by_its_name() { + let to = |href: &str| match body(&format!("[a]({href})")).remove(0) { + Block::Paragraph(mut runs) => runs.remove(0), + other => panic!("{other:?}"), + }; + for address in ["https://devnotes.fr", "http://localhost:8080"] { + assert!( + matches!(to(address), Inline::Link { to: Target::Address(found), .. } if found == address) + ); + } + for page in ["start.md", "start.md#a"] { + assert!( + matches!(to(page), Inline::Link { to: Target::Page { id, .. }, .. } if id == "start"), + "{page}" + ); + } + for nowhere in ["", "start", "a/start.md", "a.b.md", "ftp://a"] { + assert!(refused(&format!("[a]({nowhere})")).contains("leads nowhere"), "{nowhere}"); + } + } + + #[test] + fn a_name_is_given_in_its_language_or_in_english() { + let names = Names { fr: "Début".to_owned(), en: "Start".to_owned() }; + + assert_eq!([names.of("fr"), names.of("en"), names.of("de")], ["Début", "Start", "Start"]); + } } diff --git a/crates/engine/src/docs/search.rs b/crates/engine/src/docs/search.rs index a5e668bf6..883b98f7f 100644 --- a/crates/engine/src/docs/search.rs +++ b/crates/engine/src/docs/search.rs @@ -44,15 +44,13 @@ pub fn search_docs(language: &str, query: &str) -> Vec { let mut found: Vec<_> = sections(language) .iter() .filter(|section| { - terms.iter().all(|term| { - section.folded_heading.contains(term) || section.folded_text.contains(term) - }) + terms + .iter() + .all(|term| section.folded_heading.contains(term) || section.folded_text.contains(term)) }) .collect(); found.sort_by_key(|section| { - let named = terms - .iter() - .filter(|term| section.folded_heading.contains(**term)); + let named = terms.iter().filter(|term| section.folded_heading.contains(**term)); std::cmp::Reverse(named.count()) }); found @@ -97,14 +95,7 @@ fn cut(page: &'static Page) -> Vec

{ .into_iter() .map(|(id, heading, words)| { let text = words.join(" "); - Section { - page, - id, - heading, - folded_heading: fold(heading), - folded_text: fold(&text), - text, - } + Section { page, id, heading, folded_heading: fold(heading), folded_text: fold(&text), text } }) .collect() } @@ -116,9 +107,7 @@ fn said(block: &Block) -> String { Block::List { items, .. } => join(items.iter().map(|item| text_of(item))), Block::Code { title, text, .. } => format!("{title} {text}"), Block::Shortcuts { title, rows } => { - let rows = rows - .iter() - .map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); + let rows = rows.iter().map(|Shortcut { keys, does }| format!("{} {does}", keys.join(" "))); format!("{title} {}", join(rows)) } Block::Table { title, rows, .. } => { @@ -159,10 +148,7 @@ mod tests { #[test] fn a_heading_comes_before_a_mention() { let hits = search_docs("en", "palette"); - assert_eq!( - (hits[0].page.id.as_str(), hits[0].heading), - ("paste", "The palette") - ); + assert_eq!((hits[0].page.id.as_str(), hits[0].heading), ("paste", "The palette")); } #[test] @@ -187,10 +173,26 @@ mod tests { #[test] fn an_excerpt_says_where_it_was_cut() { let text = "un deux trois quatre cinq six sept huit neuf dix"; - assert_eq!( - excerpt(text, "huit"), - "…deux trois quatre cinq six sept huit neuf dix" - ); + assert_eq!(excerpt(text, "huit"), "…deux trois quatre cinq six sept huit neuf dix"); assert_eq!(excerpt(text, "absent"), text); } + + /// Whether or not its own text says the word again. + #[test] + fn a_section_is_found_by_its_heading_alone() { + for language in ["fr", "en"] { + for section in sections(language) { + let word = section + .folded_heading + .split_whitespace() + .find(|word| !section.folded_text.contains(*word)); + let Some(word) = word else { continue }; + let hits = search_docs(language, word); + assert!( + hits.len() >= AT_MOST || hits.iter().any(|hit| hit.heading == section.heading), + "{language}: {word}" + ); + } + } + } } diff --git a/crates/engine/src/durable.rs b/crates/engine/src/durable.rs index bf889978a..6a71b6e9a 100644 --- a/crates/engine/src/durable.rs +++ b/crates/engine/src/durable.rs @@ -59,7 +59,7 @@ fn sync_folder(path: &Path) -> io::Result<()> { mod tests { use super::*; - fn names(folder: &Path) -> Vec { + fn names_in(folder: &Path) -> Vec { let mut names: Vec = std::fs::read_dir(folder) .unwrap() .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()) @@ -68,43 +68,48 @@ mod tests { names } + /// The new bytes in the old file's place, and nothing staged left beside it. #[test] - fn a_file_is_replaced_whole_and_nothing_is_left_beside_it() { - let folder = tempfile::tempdir().unwrap(); - let path = folder.path().join("vault.json"); + fn a_file_written_takes_the_old_one_s_place_whole() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("libraries.json"); std::fs::write(&path, b"old").unwrap(); write(&path, b"new").unwrap(); assert_eq!(std::fs::read(&path).unwrap(), b"new"); - assert_eq!(names(folder.path()), ["vault.json"]); + assert_eq!(names_in(scratch.path()), ["libraries.json"]); } #[test] - fn a_failed_rename_leaves_no_staged_file() { - let folder = tempfile::tempdir().unwrap(); - let taken = folder.path().join("registry.json"); - std::fs::create_dir(&taken).unwrap(); - std::fs::write(taken.join("inside"), b"x").unwrap(); - let source = folder.path().join("source"); - std::fs::write(&source, b"copied").unwrap(); - - assert!(write(&taken, b"new").is_err()); - assert!(copy(&source, &taken).is_err()); - - assert_eq!(names(folder.path()), ["registry.json", "source"]); - } + fn a_file_copied_takes_the_old_one_s_place_and_leaves_its_source() { + let scratch = tempfile::tempdir().unwrap(); + let (from, to) = (scratch.path().join("from"), scratch.path().join("to")); + std::fs::write(&from, b"bytes").unwrap(); + std::fs::write(&to, b"old").unwrap(); - #[test] - fn a_copy_takes_the_place_of_the_file() { - let folder = tempfile::tempdir().unwrap(); - let source = folder.path().join("library.db"); - let target = folder.path().join("restored.db"); - std::fs::write(&source, b"pages").unwrap(); + copy(&from, &to).unwrap(); - copy(&source, &target).unwrap(); + assert_eq!(std::fs::read(&to).unwrap(), b"bytes"); + assert_eq!(std::fs::read(&from).unwrap(), b"bytes"); + assert_eq!(names_in(scratch.path()), ["from", "to"]); + } - assert_eq!(std::fs::read(&target).unwrap(), b"pages"); - assert_eq!(names(folder.path()), ["library.db", "restored.db"]); + /// A staged file left behind is a stray copy of what was being written — a key file, an + /// export — beside the person's own files. + #[test] + fn nothing_staged_is_left_when_a_write_or_a_copy_fails() { + let scratch = tempfile::tempdir().unwrap(); + let occupied = scratch.path().join("occupied"); + std::fs::create_dir_all(occupied.join("inside")).unwrap(); + let source = scratch.path().join("source"); + std::fs::write(&source, b"bytes").unwrap(); + + let written = write(&occupied, b"bytes"); + let copied = copy(&source, &occupied); + let from_nothing = copy(&scratch.path().join("missing"), &scratch.path().join("to")); + + assert!(written.is_err() && copied.is_err() && from_nothing.is_err()); + assert_eq!(names_in(scratch.path()), ["occupied", "source"]); } } diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 02aa6896f..221ace81e 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -16,10 +16,7 @@ pub struct ValidationError { impl ValidationError { pub fn new(field: &'static str, detail: impl Into) -> Self { - Self { - field, - detail: detail.into(), - } + Self { field, detail: detail.into() } } } @@ -200,11 +197,7 @@ pub struct AppError { impl AppError { pub(crate) fn new(code: ErrorCode, detail: String) -> Self { - Self { - code, - params: BTreeMap::new(), - detail, - } + Self { code, params: BTreeMap::new(), detail } } pub(crate) fn with(code: ErrorCode, detail: String, key: &str, value: &str) -> Self { @@ -249,29 +242,13 @@ impl AppError { | C::HttpScriptSkipped | C::HttpRunData ); - if plain { - format!("{:?}: {}", self.code, self.detail) - } else { - format!("{:?}", self.code) - } - } - - pub fn storage_unavailable() -> Self { - Self::new( - ErrorCode::StorageUnavailable, - "Storage unavailable: a previous operation failed".to_string(), - ) + if plain { format!("{:?}: {}", self.code, self.detail) } else { format!("{:?}", self.code) } } } impl From for AppError { fn from(error: ValidationError) -> Self { - Self::with( - ErrorCode::InvalidInput, - error.to_string(), - "field", - error.field, - ) + Self::with(ErrorCode::InvalidInput, error.to_string(), "field", error.field) } } @@ -280,27 +257,19 @@ impl From for AppError { let detail = error.to_string(); match error { - StorageError::NoteNotFound(id) => { - Self::with(ErrorCode::NoteNotFound, detail, "id", &id) - } - StorageError::SpaceNotFound(id) => { - Self::with(ErrorCode::SpaceNotFound, detail, "id", &id) - } + StorageError::NoteNotFound(id) => Self::with(ErrorCode::NoteNotFound, detail, "id", &id), + StorageError::SpaceNotFound(id) => Self::with(ErrorCode::SpaceNotFound, detail, "id", &id), StorageError::DuplicateSpaceName(name) => { Self::with(ErrorCode::DuplicateSpaceName, detail, "name", &name) } - StorageError::FolderNotFound(id) => { - Self::with(ErrorCode::FolderNotFound, detail, "id", &id) - } + StorageError::FolderNotFound(id) => Self::with(ErrorCode::FolderNotFound, detail, "id", &id), StorageError::DuplicateFolderName(name) => { Self::with(ErrorCode::DuplicateFolderName, detail, "name", &name) } StorageError::AttachmentNotFound(id) => { Self::with(ErrorCode::AttachmentNotFound, detail, "id", &id) } - StorageError::HttpItemNotFound(id) => { - Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id) - } + StorageError::HttpItemNotFound(id) => Self::with(ErrorCode::HttpItemNotFound, detail, "id", &id), StorageError::HttpEnvironmentNotFound(id) => { Self::with(ErrorCode::HttpEnvironmentNotFound, detail, "id", &id) } @@ -308,23 +277,15 @@ impl From for AppError { Self::with(ErrorCode::DuplicateEnvironmentName, detail, "name", &name) } StorageError::Invalid(error) => error.into(), - StorageError::RevisionNotFound(id) => { - Self::with(ErrorCode::RevisionNotFound, detail, "id", &id) - } - StorageError::LibraryNotFound(id) => { - Self::with(ErrorCode::LibraryNotFound, detail, "id", &id) - } + StorageError::RevisionNotFound(id) => Self::with(ErrorCode::RevisionNotFound, detail, "id", &id), + StorageError::LibraryNotFound(id) => Self::with(ErrorCode::LibraryNotFound, detail, "id", &id), StorageError::LibraryOpen => Self::new(ErrorCode::LibraryOpen, detail), StorageError::LastLibrary => Self::new(ErrorCode::LastLibrary, detail), StorageError::NothingToSetAside(path) => { Self::with(ErrorCode::NothingToSetAside, detail, "path", &path) } - StorageError::BackupNotFound(id) => { - Self::with(ErrorCode::BackupNotFound, detail, "id", &id) - } - StorageError::BackupUnopenable(id) => { - Self::with(ErrorCode::BackupUnopenable, detail, "id", &id) - } + StorageError::BackupNotFound(id) => Self::with(ErrorCode::BackupNotFound, detail, "id", &id), + StorageError::BackupUnopenable(id) => Self::with(ErrorCode::BackupUnopenable, detail, "id", &id), StorageError::Unavailable => Self::new(ErrorCode::StorageUnavailable, detail), StorageError::WrongPassphrase => Self::new(ErrorCode::WrongPassphrase, detail), StorageError::PassphraseRequired => Self::new(ErrorCode::PassphraseRequired, detail), @@ -332,8 +293,7 @@ impl From for AppError { StorageError::Damaged(_) => Self::new(ErrorCode::LibraryDamaged, detail), StorageError::File(_) => Self::new(ErrorCode::FileAccess, detail), StorageError::TooLarge { name, limit_mb } => { - Self::with(ErrorCode::FileTooLarge, detail, "name", &name) - .and("limit", &limit_mb.to_string()) + Self::with(ErrorCode::FileTooLarge, detail, "name", &name).and("limit", &limit_mb.to_string()) } StorageError::ImportFormat(_) => Self::new(ErrorCode::ImportFormat, detail), // Nothing here gives the front anything to do beyond reporting the failure. @@ -345,3 +305,146 @@ impl From for AppError { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::http::runner::DataFault; + use crate::http::send::SendError; + + fn text(text: &str) -> String { + text.to_string() + } + + /// Each failure of the storage, with the code it answers and the value its sentence states. + fn storage_errors() -> Vec<(StorageError, ErrorCode, Option<&'static str>)> { + use ErrorCode as C; + use StorageError as E; + vec![ + (E::NoteNotFound(text("x")), C::NoteNotFound, Some("id")), + (E::SpaceNotFound(text("x")), C::SpaceNotFound, Some("id")), + (E::DuplicateSpaceName(text("x")), C::DuplicateSpaceName, Some("name")), + (E::FolderNotFound(text("x")), C::FolderNotFound, Some("id")), + (E::DuplicateFolderName(text("x")), C::DuplicateFolderName, Some("name")), + (E::AttachmentNotFound(text("x")), C::AttachmentNotFound, Some("id")), + (E::HttpItemNotFound(text("x")), C::HttpItemNotFound, Some("id")), + (E::HttpEnvironmentNotFound(text("x")), C::HttpEnvironmentNotFound, Some("id")), + (E::DuplicateEnvironmentName(text("x")), C::DuplicateEnvironmentName, Some("name")), + (E::RevisionNotFound(text("x")), C::RevisionNotFound, Some("id")), + (E::LibraryNotFound(text("x")), C::LibraryNotFound, Some("id")), + (E::LibraryOpen, C::LibraryOpen, None), + (E::LastLibrary, C::LastLibrary, None), + (E::NothingToSetAside(text("x")), C::NothingToSetAside, Some("path")), + (E::BackupNotFound(text("x")), C::BackupNotFound, Some("id")), + (E::BackupUnopenable(text("x")), C::BackupUnopenable, Some("id")), + (E::File(text("x")), C::FileAccess, None), + (E::ImportFormat(text("x")), C::ImportFormat, None), + (E::Damaged(text("x")), C::LibraryDamaged, None), + (E::WrongPassphrase, C::WrongPassphrase, None), + (E::PassphraseRequired, C::PassphraseRequired, None), + (E::Unavailable, C::StorageUnavailable, None), + (E::Locked, C::Locked, None), + // Nothing here gives the interface anything to do beyond reporting the failure. + (E::CorruptRow { id: text("x"), field: "tags" }, C::Storage, None), + (E::SchemaTooRecent(text("x")), C::Storage, None), + (E::Migration(text("x")), C::Storage, None), + (E::Vault(text("x")), C::Storage, None), + (E::Sqlite(diesel::result::Error::NotFound), C::Storage, None), + ] + } + + #[test] + fn a_failure_of_the_storage_answers_its_code_and_what_its_sentence_states() { + for (error, code, named) in storage_errors() { + let answered = AppError::from(error); + + assert_eq!(answered.code, code); + let stated: Vec<_> = answered + .params + .iter() + .map(|(key, value)| (key.as_str(), value.as_str())) + .collect(); + let expected: Vec<_> = named.iter().map(|key| (*key, "x")).collect(); + assert_eq!(stated, expected, "{code:?}"); + assert!(!answered.detail.is_empty()); + } + } + + #[test] + fn a_file_too_large_says_its_name_and_the_limit() { + let answered = AppError::from(StorageError::TooLarge { name: text("film.mp4"), limit_mb: 25 }); + + assert_eq!(answered.code, ErrorCode::FileTooLarge); + assert_eq!((answered.params["name"].as_str(), answered.params["limit"].as_str()), ("film.mp4", "25")); + } + + #[test] + fn an_input_refused_names_its_field_wherever_it_was_refused() { + let refused = || ValidationError::new("folderId", "a folder cannot move into itself"); + + for answered in [AppError::from(refused()), AppError::from(StorageError::from(refused()))] { + assert_eq!( + (answered.code, answered.params["field"].as_str()), + (ErrorCode::InvalidInput, "folderId") + ); + } + } + + /// It aborts startup: `storage` is the honest code, and its version is in the detail. + #[test] + fn a_schema_too_recent_says_the_migration_it_does_not_know() { + let answered = AppError::from(StorageError::SchemaTooRecent(text("2099-01-01-000000"))); + + assert_eq!(answered.code, ErrorCode::Storage); + assert!(answered.detail.contains("2099-01-01-000000")); + } + + /// ⚠️ Never a name, a file, a URL or a script's words: a log is read by others. + #[test] + fn a_log_never_says_what_was_typed() { + let typed = || text("s3cret-typed"); + let errors = [ + AppError::from(StorageError::DuplicateSpaceName(typed())), + StorageError::DuplicateFolderName(typed()).into(), + StorageError::DuplicateEnvironmentName(typed()).into(), + StorageError::NothingToSetAside(typed()).into(), + StorageError::File(typed()).into(), + StorageError::TooLarge { name: typed(), limit_mb: 1 }.into(), + StorageError::ImportFormat(typed()).into(), + ValidationError::new("title", typed()).into(), + SendError::Variable(typed()).into(), + SendError::InvalidUrl(typed()).into(), + SendError::Unresolved(typed()).into(), + SendError::Refused(typed()).into(), + SendError::Tls(typed()).into(), + SendError::FileUnreadable(typed()).into(), + SendError::FileTooLarge(typed()).into(), + SendError::GraphqlVariables(typed()).into(), + SendError::Network(typed()).into(), + SendError::SocketScheme { twin: Some(typed()) }.into(), + ]; + for error in errors { + let line = error.for_log(); + assert!(!line.contains("s3cret"), "{line}"); + assert_eq!(line, format!("{:?}", error.code)); + } + } + + /// An identifier, an instant, a count: nothing anyone typed. + #[test] + fn a_log_says_the_detail_of_a_failure_that_holds_nothing_typed() { + let errors = [ + AppError::from(StorageError::NoteNotFound(text("n-1"))), + StorageError::BackupNotFound(text("2026-07-25_09-05-07")).into(), + StorageError::Locked.into(), + StorageError::Damaged(text("page 3")).into(), + StorageError::CorruptRow { id: text("n-1"), field: "tags" }.into(), + SendError::Handshake(403).into(), + SendError::Fell.into(), + DataFault::Empty.into(), + ]; + for error in errors { + assert_eq!(error.for_log(), format!("{:?}: {}", error.code, error.detail)); + } + } +} diff --git a/crates/engine/src/folders.rs b/crates/engine/src/folders.rs index 763d0c12d..24ed9d2fc 100644 --- a/crates/engine/src/folders.rs +++ b/crates/engine/src/folders.rs @@ -69,12 +69,7 @@ pub fn save_board_layout( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::board::save_layout( - &mut connection, - root_id.map(std::string::String::as_str), - zones, - cards, - )?) + Ok(store::board::save_layout(&mut connection, root_id.map(std::string::String::as_str), zones, cards)?) } /// `None` = every space, like [`crate::notes::view::NotesQuery::space_id`]. @@ -82,10 +77,7 @@ pub fn list_folders(engine: &Engine, space_id: Option<&String>) -> Result Result { @@ -94,17 +86,9 @@ pub fn create_folder(engine: &Engine, draft: &FolderDraft) -> Result Result Result { +pub fn recolour_folder(engine: &Engine, id: &str, colour: FolderColour) -> Result { engine.write(|db| { let mut connection = lock(db)?; let answer = store::recolour(&mut connection, id, colour)?; - let changed = Changed { - folders: true, - ..Changed::default() - }; + let changed = Changed { folders: true, ..Changed::default() }; Ok((answer, changed)) }) } @@ -152,15 +126,9 @@ pub fn move_folder( engine.write(|db| { let mut connection = lock(db)?; - let answer = store::move_to( - &mut connection, - id, - (space_id, parent_id.map(std::string::String::as_str)), - )?; - let changed = Changed { - folders: true, - ..Changed::notes(answer.notes.clone()) - }; + let answer = + store::move_to(&mut connection, id, (space_id, parent_id.map(std::string::String::as_str)))?; + let changed = Changed { folders: true, ..Changed::notes(answer.notes.clone()) }; Ok((answer, changed)) }) } @@ -171,10 +139,7 @@ pub fn move_folder_back(engine: &Engine, was: &FolderMove) -> Result BoardFrame { #[must_use] pub fn clamp_point(point: BoardPoint) -> BoardPoint { - BoardPoint { - x: point.x.clamp(0, MAX_SIDE), - y: point.y.clamp(0, MAX_SIDE), - } + BoardPoint { x: point.x.clamp(0, MAX_SIDE), y: point.y.clamp(0, MAX_SIDE) } } /// Big enough for the header and one card, or nothing can be dropped in. @@ -360,12 +357,7 @@ pub fn arrange_zones(contents: &[ZoneContents], card: i32) -> Vec { let height = default_zone_height(zone.notes, zone.nested, card); row_height = row_height.max(height); - frames.push(BoardFrame { - x: BOARD_MARGIN + px(column) * (width + GAP), - y: row_top, - width, - height, - }); + frames.push(BoardFrame { x: BOARD_MARGIN + px(column) * (width + GAP), y: row_top, width, height }); } frames @@ -404,12 +396,7 @@ fn overlaps(at: BoardPoint, card: i32, frame: BoardFrame) -> bool { } fn card_frame(at: BoardPoint, card: i32) -> BoardFrame { - BoardFrame { - x: at.x, - y: at.y, - width: CARD_WIDTH, - height: card, - } + BoardFrame { x: at.x, y: at.y, width: CARD_WIDTH, height: card } } /// Below everything already on the board — where a seat goes when the grid has none free. @@ -421,26 +408,17 @@ fn under_everything(taken: &[BoardPoint], zones: &[BoardFrame], card: i32) -> Bo .max() .unwrap_or(BOARD_MARGIN); - BoardPoint { - x: BOARD_MARGIN, - y: bottom + GAP, - } + BoardPoint { x: BOARD_MARGIN, y: bottom + GAP } } -/// Where a card that has never been placed goes: the first seat of the flow grid nothing -/// is standing on, neither a card that already has a place nor a zone. +/// Where a card that has never been placed goes, with its seat: the first of the flow grid, from +/// `first` on, nothing is standing on, neither a card that already has a place nor a zone. A run +/// of cards starts each from the seat of the one before: from zero, 5,000 take nine seconds. /// /// ⚠️ Not the seat of its index: a new note is the most recently updated, arrives at index 0, /// and would land on whichever card sits on seat 0. A rectangle test, because a card dragged /// by hand half covers the seats it straddles. #[must_use] -pub fn free_slot(top: i32, taken: &[BoardPoint], zones: &[BoardFrame], card: i32) -> BoardPoint { - free_slot_from(0, top, (taken, zones), card).1 -} - -/// As [`free_slot`], with the seat it stopped on: a run of cards seated one after the other -/// starts each from there, as a seat given stays taken. From zero, 5,000 cards take nine seconds. -#[must_use] pub fn free_slot_from( first: usize, top: i32, @@ -453,9 +431,7 @@ pub fn free_slot_from( (first..=limit) .map(|index| (index, slot(index, top, card))) .find(|(_, at)| { - !taken - .iter() - .any(|other| overlaps(*at, card, card_frame(*other, card))) + !taken.iter().any(|other| overlaps(*at, card, card_frame(*other, card))) && !zones.iter().any(|frame| overlaps(*at, card, *frame)) }) .unwrap_or_else(|| (first, under_everything(taken, zones, card))) @@ -565,11 +541,7 @@ pub fn build( let hit = criteria.passes(¬e); matched += usize::from(hit); - let entry = BoardNote { - note: model::decorate(note, request.now), - matches: hit, - position: None, - }; + let entry = BoardNote { note: model::decorate(note, request.now), matches: hit, position: None }; match seat { Seat::Zone(id) => by_folder.entry(id).or_default().push(entry), @@ -581,10 +553,7 @@ pub fn build( entry.position = positions.get(&entry.note.id).copied(); } - let by_id: HashMap<&str, &Folder> = folders - .iter() - .map(|folder| (folder.id.as_str(), folder)) - .collect(); + let by_id: HashMap<&str, &Folder> = folders.iter().map(|folder| (folder.id.as_str(), folder)).collect(); let zones: Vec = lineage .children(root) .iter() @@ -601,12 +570,7 @@ pub fn build( height: default_zone_height(notes.len(), !children.is_empty(), card), }); - BoardZone { - folder: (*folder).clone(), - frame, - notes, - children, - } + BoardZone { folder: (*folder).clone(), frame, notes, children } }) .collect(); @@ -696,10 +660,7 @@ pub fn arrange_everything( zones: folder_counts .iter() .zip(frames.iter()) - .map(|((folder_id, _), frame)| ZonePlacement { - folder_id: folder_id.clone(), - frame: *frame, - }) + .map(|((folder_id, _), frame)| ZonePlacement { folder_id: folder_id.clone(), frame: *frame }) .collect(), cards: flowed(loose_ids, loose_top(&frames), card), } @@ -710,497 +671,516 @@ pub fn arrange_everything( /// `zones` comes back empty: nothing placed or sized by hand is touched. #[must_use] pub fn arrange_loose_cards(frames: &[BoardFrame], loose_ids: &[String], card: i32) -> BoardLayout { - BoardLayout { - zones: Vec::new(), - cards: flowed(loose_ids, loose_top(frames), card), - } + BoardLayout { zones: Vec::new(), cards: flowed(loose_ids, loose_top(frames), card) } } fn flowed(loose_ids: &[String], top: i32, card: i32) -> Vec { loose_ids .iter() .zip(arrange_loose(loose_ids.len(), top, card)) - .map(|(note_id, position)| CardPlacement { - note_id: note_id.clone(), - position, - }) + .map(|(note_id, position)| CardPlacement { note_id: note_id.clone(), position }) .collect() } #[cfg(test)] mod tests { use super::*; + use crate::folders::model::NoteFolder; use crate::notes::fixtures::{NOW, at, note}; + use crate::notes::view::FacetCount; - /// The default card, four lines. const CARD: i32 = 140; - fn notes(count: usize) -> ZoneContents { - ZoneContents { - notes: count, - nested: false, + fn folder(id: &str, parent: Option<&str>, name: &str) -> Folder { + Folder { + id: id.to_string(), + space_id: "s-1".to_string(), + name: name.to_string(), + colour: FolderColour::Blue, + created_at: at(NOW), + parent_id: parent.map(str::to_string), } } - fn holding(counts: &[usize]) -> Vec { - counts.iter().copied().map(notes).collect() + fn filed(id: &str, folder_id: Option<&str>) -> Note { + Note { id: id.to_string(), folder_id: folder_id.map(str::to_string), ..note() } } - /// Everything but the space and the instant is neutral: the board dims, it never narrows. - #[test] - fn the_board_reads_the_whole_space_whatever_it_is_asked() { - let request = BoardQuery { + fn request(root: Option<&str>) -> BoardQuery { + BoardQuery { space_id: "s-1".to_string(), - root_id: Some("f-1".to_string()), - search: "deploy".to_string(), - filter: NoteFilter::Pinned, - tags: vec!["ops".to_string()], - languages: vec![Language::Sql], - kinds: vec![NoteKind::Note], + root_id: root.map(str::to_string), + search: String::new(), + filter: NoteFilter::All, + tags: Vec::new(), + languages: Vec::new(), + kinds: Vec::new(), priorities: Vec::new(), now: at(NOW), tz_offset_minutes: 0, - preview_lines: PreviewLines::default(), - }; + preview_lines: PreviewLines::Four, + } + } - let wide = request.whole_space(); + /// Infra ─ Perf, and Docs beside it. + fn folders() -> Vec { + vec![ + folder("infra", None, "Infra"), + folder("perf", Some("infra"), "Perf"), + folder("docs", None, "Docs"), + ] + } - assert_eq!(wide.space_id.as_deref(), Some("s-1")); - assert!(wide.search.is_empty() && wide.tags.is_empty() && wide.languages.is_empty()); - assert!(wide.kinds.is_empty() && wide.priorities.is_empty()); - assert_eq!(wide.filter, NoteFilter::All); - assert_eq!(wide.now, at(NOW)); + fn board(notes: Vec, positions: &HashMap, query: &BoardQuery) -> BoardView { + build(notes, &folders(), &HashMap::new(), positions, &Facets::default(), query) } - #[test] - fn every_card_of_a_board_is_reached_once_zones_first() { - let card = |id: &str| BoardNote { - note: model::decorate( - Note { - id: id.to_string(), - ..note() - }, - at(NOW), - ), - matches: true, - position: None, - }; - let mut view = BoardView { - zones: vec![BoardZone { - folder: Folder { - id: "f-1".to_string(), - space_id: "s-1".to_string(), - name: "Ops".to_string(), - colour: super::super::model::FolderColour::nth(0), - created_at: at(NOW), - parent_id: None, - }, - frame: BoardFrame { - x: 0, - y: 0, - width: 400, - height: 300, - }, - notes: vec![card("filed")], - children: Vec::new(), - }], - loose: vec![card("loose")], - available_tags: Vec::new(), - available_languages: Vec::new(), - is_filtering: false, - matched: 2, - width: 0, - height: 0, - }; + fn ids(notes: &[BoardNote]) -> Vec<&str> { + notes.iter().map(|entry| entry.note.id.as_str()).collect() + } - let ids: Vec = view.notes_mut().map(|note| note.id.clone()).collect(); + fn frame(x: i32, y: i32, width: i32, height: i32) -> BoardFrame { + BoardFrame { x, y, width, height } + } - assert_eq!(ids, ["filed", "loose"]); + fn point(x: i32, y: i32) -> BoardPoint { + BoardPoint { x, y } } #[test] - fn the_occupancy_counts_each_folder_and_lists_the_loose_notes() { - let filed = |id: &str, folder: Option<&str>| Note { - id: id.to_string(), - folder_id: folder.map(str::to_string), - ..note() - }; + fn a_card_is_as_tall_as_the_lines_it_shows() { + let cases = + [(PreviewLines::Three, 3, 120), (PreviewLines::Four, 4, 140), (PreviewLines::Five, 5, 160)]; - let notes = [ - filed("a", Some("f-1")), - filed("b", Some("f-1")), - filed("c", None), - filed("d", Some("f-2")), - filed("e", Some("f-1a")), - ]; - let lineage = Lineage::new([ - ("f-1".to_string(), None), - ("f-2".to_string(), None), - ("f-1a".to_string(), Some("f-1".to_string())), - ]); - - let space = Occupancy::on(¬es, &lineage, None); - assert_eq!(space.per_folder.get("f-1"), Some(&3)); - assert_eq!(space.per_folder.get("f-2"), Some(&1)); - assert_eq!(space.loose, ["c"]); - - let inside = Occupancy::on(¬es, &lineage, Some("f-1")); - assert_eq!(inside.per_folder.get("f-1a"), Some(&1)); - assert_eq!(inside.loose, ["a", "b"]); - assert!(!inside.per_folder.contains_key("f-2")); + for (lines, count, height) in cases { + assert_eq!((lines.count(), lines.card_height()), (count, height)); + } + assert_eq!(PreviewLines::default(), PreviewLines::Four); } - /// Two cards and room for the scrollbar: at exactly the inner width the second card wraps. + /// The board dims rather than narrows: what it reads is the whole space. #[test] - fn a_zone_is_two_cards_wide_with_room_for_the_scrollbar() { - assert_eq!(default_zone_width(), 12 + 240 + 12 + 240 + 12 + SCROLLBAR); - assert!(default_zone_width() - ZONE_PADDING * 2 > ZONE_COLUMNS * CARD_WIDTH + GAP); + fn a_board_reads_its_whole_space_whatever_it_is_asked_to_dim() { + let query = BoardQuery { + search: "pg".to_string(), + filter: NoteFilter::Pinned, + tags: vec!["sql".to_string()], + tz_offset_minutes: -120, + ..request(Some("infra")) + }; + + let read = query.whole_space(); + + assert_eq!(read.space_id.as_deref(), Some("s-1")); + assert_eq!((read.folder_id, read.search.as_str()), (None, "")); + assert_eq!(read.filter, NoteFilter::All); + assert!(read.tags.is_empty()); + assert_eq!((read.now, read.tz_offset_minutes), (at(NOW), -120)); } #[test] - fn a_zone_grows_a_row_at_a_time() { - let one_row = default_zone_height(2, false, CARD); - let two_rows = default_zone_height(3, false, CARD); + fn a_board_counts_each_zone_s_notes_and_lists_the_free_ones() { + let lineage = Lineage::of(&folders()); + let notes = [ + filed("in-infra", Some("infra")), + filed("in-perf", Some("perf")), + filed("in-docs", Some("docs")), + filed("loose", None), + ]; - assert_eq!(two_rows - one_row, CARD + GAP); - assert_eq!(default_zone_height(4, false, CARD), two_rows); + let space = Occupancy::on(¬es, &lineage, None); + let infra = Occupancy::on(¬es, &lineage, Some("infra")); + + assert_eq!(space.per_folder, HashMap::from([("infra".to_string(), 2), ("docs".to_string(), 1)])); + assert_eq!(space.loose, ["loose"]); + assert_eq!(infra.per_folder, HashMap::from([("perf".to_string(), 1)])); + assert_eq!(infra.loose, ["in-infra"]); } - /// One pixel short of two rows brings a vertical scrollbar that wraps the second card. + /// Clamped rather than refused: an error mid-gesture would leave the screen holding a frame + /// the library refused. #[test] - fn a_zone_is_tall_enough_for_its_rows_once_its_own_hairlines_are_paid_for() { - let body = zone_height(3, 2, false, CARD) - ZONE_BORDER * 2 - ZONE_HEADER; + fn a_frame_is_kept_on_the_board_and_big_enough_to_drop_a_card_into() { + let cases = [ + (frame(-5, -1, 10, 10), frame(0, 0, MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT)), + (frame(40, 60, 600, 400), frame(40, 60, 600, 400)), + (frame(0, 0, i32::MAX, i32::MAX), frame(0, 0, MAX_SIDE, MAX_SIDE)), + ]; - assert!( - body >= ZONE_PADDING * 2 + CARD * 2 + GAP, - "{body}px of body for two rows that need {}", - ZONE_PADDING * 2 + CARD * 2 + GAP - ); + for (asked, kept) in cases { + assert_eq!(clamp(asked), kept, "{asked:?}"); + } + assert_eq!(clamp_point(point(-3, i32::MAX)), point(0, MAX_SIDE)); } - /// `border-box`, and no scrollbar once the zone is tall enough: two cards still flow across. + /// A zone drawn on top of another wins the point they share; the right and bottom edges + /// belong to the ground. #[test] - fn a_zone_shaved_narrower_than_nominal_still_fits_two_across() { - let shaved = default_zone_width() - 14; + fn a_point_falls_in_the_topmost_zone_that_holds_it() { + let frames = + [("under".to_string(), frame(0, 0, 100, 100)), ("over".to_string(), frame(50, 50, 100, 100))]; + let cases = [ + (point(10, 10), Some("under")), + (point(60, 60), Some("over")), + (point(0, 0), Some("under")), + (point(150, 60), None), + (point(10, 100), None), + ]; - assert_eq!(columns_in(shaved), 2); - assert_eq!( - zone_height(3, columns_in(shaved), false, CARD), - zone_height(3, ZONE_COLUMNS, false, CARD) - ); + for (at, zone) in cases { + assert_eq!(zone_at(&frames, at).as_deref(), zone, "{at:?}"); + } } - /// The narrowest width that still flows two, and the widest that does not. + /// Counted the way the zone's body lays them: hairlines and padding off, the scrollbar's + /// allowance kept, so the count turns over exactly where the flow does. #[test] - fn the_count_turns_over_where_the_flow_does() { + fn a_first_zone_holds_two_cards_across_and_a_narrow_one_at_least_one() { let two = ZONE_BORDER * 2 + ZONE_PADDING * 2 + CARD_WIDTH * 2 + GAP; - assert_eq!(columns_in(two), 2); - assert_eq!(columns_in(two - 1), 1); + assert_eq!(columns_in(default_zone_width()), ZONE_COLUMNS); + assert_eq!((columns_in(two), columns_in(two - 1)), (2, 1)); + assert_eq!(columns_in(MIN_ZONE_WIDTH), 1); + assert_eq!(columns_in(0), 1); } - /// A zone widened by hand fits more across, and needs fewer rows. + /// One pixel short, the body shows a scrollbar that wraps the second card. #[test] - fn a_wider_zone_needs_fewer_rows_for_the_same_notes() { - let nominal = default_zone_width(); - let wider = nominal + CARD_WIDTH + GAP; - - assert_eq!(columns_in(nominal), ZONE_COLUMNS); - assert_eq!(columns_in(wider), ZONE_COLUMNS + 1); - assert!( - zone_height(6, columns_in(wider), false, CARD) - < zone_height(6, columns_in(nominal), false, CARD) - ); + fn a_zone_s_body_is_its_rows_once_its_hairlines_and_header_are_paid_for() { + let body = zone_height(3, 2, false, CARD) - ZONE_BORDER * 2 - ZONE_HEADER; + + assert_eq!(body, ZONE_PADDING * 2 + CARD * 2 + GAP); } - /// Below one card across, the flow still has to have a column. #[test] - fn a_zone_squashed_narrow_still_counts_one_column() { - assert_eq!(columns_in(0), 1); - assert_eq!(columns_in(MIN_ZONE_WIDTH), 1); + fn a_zone_is_tall_enough_for_its_rows_of_cards_and_never_less_than_one() { + let height = |notes: usize, columns: i32, nested: bool| zone_height(notes, columns, nested, CARD); + + assert_eq!(height(0, 2, false), height(1, 2, false)); + assert_eq!(height(2, 2, false), height(1, 2, false)); + assert_eq!(height(3, 2, false) - height(2, 2, false), CARD + GAP); + assert_eq!(height(2, 0, false), height(2, 1, false)); + assert_eq!(height(1, 2, true) - height(1, 2, false), ZONE_SUBFOLDERS); + assert_eq!(zone_height(1, 1, false, MIN_CARD_HEIGHT), MIN_ZONE_HEIGHT); + assert_eq!(default_zone_height(3, true, CARD), height(3, ZONE_COLUMNS, true)); } - /// A zone with nothing in it is still a target to drop a card into. + /// Three across in the order handed over; a row starts under the tallest of the one above. #[test] - fn an_empty_zone_is_still_a_row_tall() { + fn zones_are_laid_out_in_reading_order_three_across() { + let contents = [5, 0, 0, 0].map(|notes| ZoneContents { notes, nested: false }); + let width = default_zone_width(); + + let frames = arrange_zones(&contents, CARD); + + let corners: Vec<(i32, i32)> = frames.iter().map(|frame| (frame.x, frame.y)).collect(); + let second_row = BOARD_MARGIN + default_zone_height(5, false, CARD) + GAP; assert_eq!( - default_zone_height(0, false, CARD), - default_zone_height(1, false, CARD) + corners, + [ + (BOARD_MARGIN, BOARD_MARGIN), + (BOARD_MARGIN + width + GAP, BOARD_MARGIN), + (BOARD_MARGIN + 2 * (width + GAP), BOARD_MARGIN), + (BOARD_MARGIN, second_row), + ] ); + assert!(frames.iter().all(|frame| frame.width == width)); + assert_eq!(frames[1].height, default_zone_height(0, false, CARD)); } #[test] - fn zones_are_laid_out_in_reading_order() { - let frames = arrange_zones(&holding(&[1, 1, 1]), CARD); + fn loose_cards_flow_four_across_clear_of_the_lowest_zone() { + assert_eq!(loose_top(&[]), BOARD_MARGIN); + let top = loose_top(&[frame(0, 0, 10, 300), frame(0, 100, 10, 50)]); + assert_eq!(top, 300 + 2 * GAP); - assert_eq!(frames[0].y, frames[1].y); - assert!(frames[0].x < frames[1].x); - assert!(frames[1].x < frames[2].x); - } + let seats = arrange_loose(5, top, CARD); - #[test] - fn the_layout_wraps_after_three_zones() { - let frames = arrange_zones(&holding(&[1, 1, 1, 1]), CARD); + assert_eq!(seats[0], point(BOARD_MARGIN, top)); + assert_eq!(seats[3], point(BOARD_MARGIN + 3 * (CARD_WIDTH + GAP), top)); + assert_eq!(seats[4], point(BOARD_MARGIN, top + CARD + GAP)); + } - assert_eq!(frames[3].x, frames[0].x); - assert!(frames[3].y > frames[0].y); + fn free_slot(top: i32, taken: &[BoardPoint], zones: &[BoardFrame], card: i32) -> BoardPoint { + free_slot_from(0, top, (taken, zones), card).1 } - /// A row advances by its tallest zone, or the next row lands on top of it. + /// Not the seat of its index: a new note would land on whichever card sits on seat 0. #[test] - fn a_wrapped_row_clears_the_tallest_zone_above_it() { - let frames = arrange_zones(&holding(&[1, 9, 1, 1]), CARD); + fn a_card_never_placed_takes_the_first_seat_nothing_stands_on() { + let seats = arrange_loose(4, 100, CARD); + let half_way = point(seats[1].x + CARD_WIDTH / 2, seats[1].y); + let cases = [ + (vec![], vec![], seats[0]), + (vec![seats[0]], vec![], seats[1]), + (vec![half_way], vec![], seats[0]), + (vec![seats[0], half_way], vec![], seats[3]), + (vec![seats[0], seats[2]], vec![], seats[1]), + (vec![], vec![frame(0, 100, 2 * CARD_WIDTH, CARD)], seats[2]), + ]; - let tallest = frames[..3].iter().map(|f| f.y + f.height).max().unwrap(); - assert!(frames[3].y >= tallest); + for (taken, zones, seat) in cases { + assert_eq!(free_slot(100, &taken, &zones, CARD), seat, "{taken:?} {zones:?}"); + } } #[test] - fn the_layout_is_the_same_every_time() { - assert_eq!( - arrange_zones(&holding(&[3, 1, 7]), CARD), - arrange_zones(&holding(&[3, 1, 7]), CARD) - ); + fn a_card_with_no_seat_left_goes_under_everything() { + let zone = frame(0, 0, 10_000, 5_000); + + assert_eq!(free_slot(100, &[], &[zone], CARD), point(BOARD_MARGIN, 5_000 + GAP)); } + /// The run starts each search where the last stopped, and gives the seats one by one would. #[test] - fn loose_cards_flow_under_the_zones_with_room_for_their_label() { - let frames = arrange_zones(&holding(&[1]), CARD); - let top = loose_top(&frames); - - assert!(top > frames[0].y + frames[0].height); + fn seats_given_in_a_run_are_the_ones_given_one_by_one() { + let seats = arrange_loose(6, 100, CARD); + let wall = [frame(seats[2].x, seats[2].y, CARD_WIDTH, CARD)]; + let mut one_by_one = vec![seats[5]]; + let mut run = one_by_one.clone(); + let mut seat = 0; - let points = arrange_loose(5, top, CARD); - assert_eq!( - points[0], - BoardPoint { - x: BOARD_MARGIN, - y: top - } - ); - assert_eq!(points[3].y, top); - assert_eq!(points[4].x, BOARD_MARGIN); - assert_eq!(points[4].y, top + CARD + GAP); - } + for _ in 0..40 { + one_by_one.push(free_slot(100, &one_by_one, &wall, CARD)); + let (reached, at) = free_slot_from(seat, 100, (&run, &wall), CARD); + seat = reached; + run.push(at); + } - #[test] - fn an_empty_board_still_puts_its_loose_cards_somewhere() { - assert_eq!(loose_top(&[]), BOARD_MARGIN); + assert_eq!(run, one_by_one); } - /// A new note must not land under a card that is already there. #[test] - fn a_card_with_no_place_never_takes_one_that_is_occupied() { - let top = loose_top(&[]); - let first = slot(0, top, CARD); + fn the_surface_reaches_past_the_furthest_zone_or_card_and_is_never_less_than_a_screen() { + let zone = BoardZone { + folder: folder("infra", None, "Infra"), + frame: frame(1_000, 0, 500, 100), + notes: Vec::new(), + children: Vec::new(), + }; + let card = BoardNote { + note: model::decorate(note(), at(NOW)), + matches: true, + position: Some(point(0, 600)), + }; - assert_eq!(free_slot(top, &[], &[], CARD), first); - assert_eq!(free_slot(top, &[first], &[], CARD), slot(1, top, CARD)); + assert_eq!(surface(&[], &[], CARD), (960 + BOARD_MARGIN, 540 + BOARD_MARGIN)); + assert_eq!(surface(&[zone], &[card], CARD), (1_500 + BOARD_MARGIN, 600 + CARD + BOARD_MARGIN)); } - /// A card dragged by hand hides the seats it straddles. #[test] - fn a_seat_half_covered_is_a_seat_taken() { - let top = loose_top(&[]); - let nudged = BoardPoint { - x: BOARD_MARGIN + 20, - y: top + 20, - }; + fn the_space_s_board_draws_its_top_folders_each_gathering_what_is_under_it() { + let notes = + vec![filed("in-infra", Some("infra")), filed("in-perf", Some("perf")), filed("loose", None)]; - let at = free_slot(top, &[nudged], &[], CARD); + let view = board(notes, &HashMap::new(), &request(None)); - assert!(!overlaps(at, CARD, card_frame(nudged, CARD))); - assert_eq!(at, slot(2, top, CARD)); + let zones: Vec<(&str, Vec<&str>)> = view + .zones + .iter() + .map(|zone| (zone.folder.id.as_str(), ids(&zone.notes))) + .collect(); + assert_eq!(zones, [("infra", vec!["in-infra", "in-perf"]), ("docs", vec![])]); + assert_eq!(ids(&view.loose), ["loose"]); + assert!(view.zones[0].notes.iter().all(|entry| entry.position.is_none())); } + /// Nothing from outside it: a note of a sibling folder, or loose in the space, is not drawn. #[test] - fn a_zone_standing_on_a_seat_takes_it_too() { - let top = loose_top(&[]); - let over = BoardFrame { - x: BOARD_MARGIN, - y: top, - width: CARD_WIDTH, - height: CARD, - }; + fn a_folder_s_board_draws_its_sub_folders_and_its_own_notes_free_on_its_ground() { + let notes = vec![ + filed("in-infra", Some("infra")), + filed("in-perf", Some("perf")), + filed("in-docs", Some("docs")), + filed("loose", None), + ]; - assert_eq!( - free_slot(top, &[], std::slice::from_ref(&over), CARD), - slot(1, top, CARD) - ); + let view = board(notes, &HashMap::new(), &request(Some("infra"))); + + assert_eq!(view.zones.len(), 1); + assert_eq!(ids(&view.zones[0].notes), ["in-perf"]); + assert_eq!(ids(&view.loose), ["in-infra"]); + assert_eq!(view.matched, 2); } #[test] - fn seats_given_in_a_run_are_the_ones_given_one_by_one() { - let top = 100; - let wall = BoardFrame { - x: slot(2, top, CARD).x, - y: slot(2, top, CARD).y, - width: CARD_WIDTH, - height: CARD, - }; - let zones = [wall]; - let mut one_by_one = vec![slot(5, top, CARD)]; - let mut run = one_by_one.clone(); - let mut seat = 0; + fn a_zone_names_its_sub_folders_by_name_with_what_each_one_holds_below() { + let folders = [ + folder("infra", None, "Infra"), + folder("zeta", Some("infra"), "zeta"), + folder("alpha", Some("infra"), "Alpha"), + folder("deep", Some("zeta"), "Deep"), + ]; + let notes = vec![filed("a", Some("zeta")), filed("b", Some("deep")), filed("c", Some("infra"))]; - for _ in 0..40 { - one_by_one.push(free_slot(top, &one_by_one, &zones, CARD)); - let (reached, at) = free_slot_from(seat, top, (&run, &zones), CARD); - seat = reached; - run.push(at); - } + let view = + build(notes, &folders, &HashMap::new(), &HashMap::new(), &Facets::default(), &request(None)); - assert_eq!(run, one_by_one); + let children: Vec<(&str, u32)> = view.zones[0] + .children + .iter() + .map(|child| (child.name.as_str(), child.count)) + .collect(); + assert_eq!(children, [("Alpha", 0), ("zeta", 2)]); } + /// A zone with sub-folders is taller by their row; a stored frame is kept as it is. #[test] - fn a_seat_freed_in_the_middle_is_the_next_one_given() { - let top = loose_top(&[]); - let taken = [slot(0, top, CARD), slot(2, top, CARD)]; + fn a_zone_never_laid_out_is_sized_for_its_notes_and_its_sub_folders() { + let stored = frame(300, 300, 600, 600); + let frames = HashMap::from([("docs".to_string(), stored)]); + let notes = vec![filed("a", Some("infra")), filed("b", Some("infra")), filed("c", Some("infra"))]; + + let view = build(notes, &folders(), &frames, &HashMap::new(), &Facets::default(), &request(None)); - assert_eq!(free_slot(top, &taken, &[], CARD), slot(1, top, CARD)); + assert_eq!( + view.zones[0].frame, + frame(BOARD_MARGIN, BOARD_MARGIN, default_zone_width(), default_zone_height(3, true, CARD)) + ); + assert_eq!(view.zones[1].frame, stored); } #[test] - fn a_card_with_nowhere_to_sit_goes_below_everything() { - let top = loose_top(&[]); - let wall = BoardFrame { - x: 0, - y: top, - width: MAX_SIDE, - height: MAX_SIDE, - }; + fn a_free_card_keeps_its_place_and_one_without_takes_a_free_seat_under_the_zones() { + let placed = point(BOARD_MARGIN, 2_000); + let positions = HashMap::from([("placed".to_string(), placed)]); + let notes = vec![filed("new", None), filed("placed", None)]; - let at = free_slot(top, &[], std::slice::from_ref(&wall), CARD); + let view = board(notes, &positions, &request(None)); - assert_eq!(at.x, BOARD_MARGIN); - assert!(at.y >= wall.y + wall.height); + let at: HashMap<&str, BoardPoint> = view + .loose + .iter() + .map(|entry| (entry.note.id.as_str(), entry.position.unwrap())) + .collect(); + assert_eq!(at["placed"], placed); + let zones: Vec = view.zones.iter().map(|zone| zone.frame).collect(); + assert_eq!(at["new"], free_slot(loose_top(&zones), &[placed], &zones, CARD)); } + /// Spatial memory is what the board has that the list does not: a card is dimmed in place. #[test] - fn the_surface_covers_the_furthest_zone() { - let zone = BoardZone { - folder: crate::folders::model::Folder { - id: "f-1".to_string(), - space_id: "s-1".to_string(), - name: "Perf".to_string(), - colour: crate::folders::model::FolderColour::Blue, - created_at: Utc::now(), - parent_id: None, - }, - frame: BoardFrame { - x: 2000, - y: 1500, - width: 300, - height: 200, - }, - notes: Vec::new(), - children: Vec::new(), - }; + fn a_card_that_does_not_match_is_dimmed_not_dropped() { + let notes = + vec![Note { title: "Postgres".to_string(), ..filed("hit", Some("infra")) }, filed("miss", None)]; + let query = BoardQuery { search: "postgres".to_string(), ..request(None) }; - let (width, height) = surface(std::slice::from_ref(&zone), &[], CARD); + let view = board(notes, &HashMap::new(), &query); - assert_eq!(width, 2300 + BOARD_MARGIN); - assert_eq!(height, 1700 + BOARD_MARGIN); + assert_eq!(view.matched, 1); + assert!(view.is_filtering); + assert!(view.zones[0].notes[0].matches); + assert!(!view.loose[0].matches); } #[test] - fn the_surface_is_never_smaller_than_a_screen() { - let (width, height) = surface(&[], &[], CARD); + fn the_quick_filter_alone_counts_as_filtering() { + let cases = [(NoteFilter::All, false), (NoteFilter::Pinned, true), (NoteFilter::Untriaged, true)]; - assert!(width >= 960); - assert!(height >= 540); + for (filter, filtering) in cases { + let query = BoardQuery { filter, ..request(None) }; + assert_eq!(board(Vec::new(), &HashMap::new(), &query).is_filtering, filtering, "{filter:?}"); + } } #[test] - fn tidying_up_puts_every_zone_back_in_reading_order() { - let counts = vec![ - ("a".into(), notes(1)), - ("b".into(), notes(2)), - ("c".into(), notes(3)), + fn a_pinned_card_comes_first_in_its_zone() { + let notes = vec![ + filed("first", Some("infra")), + Note { pinned: true, ..filed("pinned", Some("infra")) }, + filed("second", Some("infra")), ]; - let layout = arrange_everything(&counts, &[], CARD); + let view = board(notes, &HashMap::new(), &request(None)); - let xs: Vec = layout.zones.iter().map(|zone| zone.frame.x).collect(); - assert_eq!(xs[0], BOARD_MARGIN); - assert!(xs[1] > xs[0] && xs[2] > xs[1]); - assert!(layout.zones.iter().all(|zone| zone.frame.y == BOARD_MARGIN)); + assert_eq!(ids(&view.zones[0].notes), ["pinned", "first", "second"]); } - /// A zone stretched or squashed by hand comes back at the height its contents need. + /// Drawn from the space, so the first choice on a rail does not empty it. #[test] - fn tidying_up_resizes_a_zone_to_what_it_holds() { - let layout = arrange_everything(&[("a".into(), notes(5))], &[], CARD); + fn the_rails_offer_the_space_s_tags_and_languages() { + let facets = Facets { + tags: vec![FacetCount { value: "sql".to_string(), count: 2 }], + languages: vec![FacetCount { value: Language::Sql, count: 2 }], + ..Facets::default() + }; - assert_eq!( - layout.zones[0].frame.height, - default_zone_height(5, false, CARD) - ); - assert_eq!(layout.zones[0].frame.width, default_zone_width()); + let view = build(Vec::new(), &folders(), &HashMap::new(), &HashMap::new(), &facets, &request(None)); + + assert_eq!(view.available_tags, ["sql"]); + assert_eq!(view.available_languages, [Language::Sql]); } + /// A card shows a preview; opening the note reads it whole. #[test] - fn tidied_loose_cards_flow_under_the_zones() { - let layout = - arrange_everything(&[("a".into(), notes(2))], &["n1".into(), "n2".into()], CARD); - - let zone = layout.zones[0].frame; - assert!( - layout - .cards - .iter() - .all(|card| card.position.y > zone.y + zone.height) - ); - assert_eq!(layout.cards[0].position.x, BOARD_MARGIN); - assert!(layout.cards[1].position.x > layout.cards[0].position.x); + fn a_card_carries_only_its_preview() { + let long = Note { + content: (1..=20).map(|line| format!("line {line}")).collect::>().join("\n"), + ..filed("long", None) + }; + + let view = board(vec![long], &HashMap::new(), &request(None)); + + assert!(view.loose[0].note.content.lines().count() <= model::PREVIEW_LINES); } + /// The zone says where a card is, unless it comes from below it; the ground needs no chip. #[test] - fn the_same_board_tidied_twice_is_the_same_board() { - let counts = vec![("a".into(), notes(4)), ("b".into(), notes(1))]; - let loose = vec!["n1".to_string(), "n2".to_string()]; - - assert_eq!( - arrange_everything(&counts, &loose, CARD), - arrange_everything(&counts, &loose, CARD) + fn a_card_names_its_folder_only_when_it_comes_from_below_its_zone() { + let chip = |id: &str| NoteFolder { + id: id.to_string(), + name: id.to_string(), + colour: FolderColour::Blue, + path: vec![id.to_string()], + }; + let mut view = board( + vec![filed("own", Some("infra")), filed("below", Some("perf")), filed("loose", None)], + &HashMap::new(), + &request(None), ); + for entry in view.notes_mut() { + entry.folder = Some(chip(entry.note.folder_id.as_deref().unwrap_or("none"))); + } + + view.keep_chips_from_below(); + + let chips: Vec<(String, bool)> = view + .notes_mut() + .map(|entry| (entry.note.id.clone(), entry.folder.is_some())) + .collect(); + let expected = [("own", false), ("below", true), ("loose", false)]; + assert_eq!(chips, expected.map(|(id, chip)| (id.to_string(), chip))); } + /// The same board tidied twice is the same board. #[test] - fn tidying_an_empty_space_writes_nothing() { - let layout = arrange_everything(&[], &[], CARD); - - assert!(layout.zones.is_empty() && layout.cards.is_empty()); + fn tidying_everything_lays_the_zones_out_again_and_flows_the_loose_cards_under_them() { + let counts = [ + ("infra".to_string(), ZoneContents { notes: 3, nested: true }), + ("docs".to_string(), ZoneContents::default()), + ]; + let loose = ["a".to_string(), "b".to_string()]; + + let layout = arrange_everything(&counts, &loose, CARD); + + let frames = arrange_zones(&[counts[0].1, counts[1].1], CARD); + let placed: Vec<(&str, BoardFrame)> = + layout.zones.iter().map(|zone| (zone.folder_id.as_str(), zone.frame)).collect(); + assert_eq!(placed, [("infra", frames[0]), ("docs", frames[1])]); + let seats = arrange_loose(2, loose_top(&frames), CARD); + let cards: Vec = layout.cards.iter().map(|card| card.position).collect(); + assert_eq!(cards, seats); + assert_eq!(arrange_everything(&counts, &loose, CARD), layout); } - /// 3, 4 or 5 lines: a zone's rows and the loose grid's pitch follow the card, on the grid. + /// A zone placed and sized by hand is the only manual work the board holds. #[test] - fn the_first_layout_follows_the_libraries_preview_lines() { - for (lines, card) in [ - (PreviewLines::Three, 120), - (PreviewLines::Four, 140), - (PreviewLines::Five, 160), - ] { - assert_eq!(lines.card_height(), card); - assert_eq!(card % 20, 0, "{lines}: off the board's grid"); - let layout = arrange_everything( - &[("a".into(), notes(3))], - &[ - "n1".into(), - "n2".into(), - "n3".into(), - "n4".into(), - "n5".into(), - ], - lines.card_height(), - ); - let zone = layout.zones[0].frame; - let body = zone.height - ZONE_BORDER * 2 - ZONE_HEADER - ZONE_PADDING * 2; - assert_eq!(body, card * 2 + GAP, "{lines}: two rows of cards"); - let cards = &layout.cards; - assert_eq!(cards[4].position.y - cards[0].position.y, card + GAP); - assert!(cards[0].position.y >= zone.y + zone.height); - } + fn tidying_the_loose_cards_leaves_every_zone_where_it_stands() { + let standing = [frame(0, 0, 600, 900)]; + + let layout = arrange_loose_cards(&standing, &["a".to_string()], CARD); + + assert!(layout.zones.is_empty()); + assert_eq!(layout.cards[0].position, point(BOARD_MARGIN, 900 + 2 * GAP)); } } diff --git a/crates/engine/src/folders/model.rs b/crates/engine/src/folders/model.rs index 7f28d7342..02aa06991 100644 --- a/crates/engine/src/folders/model.rs +++ b/crates/engine/src/folders/model.rs @@ -121,25 +121,15 @@ impl Lineage { let mut lineage = Self::default(); for (id, parent) in &links { - let parent = parent - .clone() - .filter(|parent| known.contains(parent.as_str())); - lineage - .children - .entry(parent.clone()) - .or_default() - .push(id.clone()); + let parent = parent.clone().filter(|parent| known.contains(parent.as_str())); + lineage.children.entry(parent.clone()).or_default().push(id.clone()); lineage.parents.insert(id.clone(), parent); } lineage } pub fn of(folders: &[Folder]) -> Self { - Self::new( - folders - .iter() - .map(|folder| (folder.id.clone(), folder.parent_id.clone())), - ) + Self::new(folders.iter().map(|folder| (folder.id.clone(), folder.parent_id.clone()))) } pub fn contains(&self, id: &str) -> bool { @@ -152,9 +142,7 @@ impl Lineage { /// In the order the folders were handed over: creation, for the board's zones. pub fn children(&self, parent: Option<&str>) -> &[String] { - self.children - .get(&parent.map(str::to_string)) - .map_or(&[], Vec::as_slice) + self.children.get(&parent.map(str::to_string)).map_or(&[], Vec::as_slice) } /// The folder and everything under it, the folder first. A cycle a damaged row could make @@ -225,8 +213,7 @@ impl Lineage { None => return Seat::Elsewhere, }, }; - path.get(start) - .map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) + path.get(start).map_or(Seat::Elsewhere, |zone| Seat::Zone(zone.clone())) } /// A folder made under `parent`: in this space, and not past [`MAX_DEPTH`]. @@ -240,20 +227,13 @@ impl Lineage { if let Some(parent) = parent && self.subtree(id).iter().any(|below| below == parent) { - return Err(ValidationError::new( - "parentId", - "a folder cannot move into itself", - )); + return Err(ValidationError::new("parentId", "a folder cannot move into itself")); } self.check_room(parent, self.height(id).max(1)) } /// A sub-tree `levels` deep arriving from another space under `parent` of this one. - pub fn check_arrival( - &self, - parent: Option<&str>, - levels: usize, - ) -> Result<(), ValidationError> { + pub fn check_arrival(&self, parent: Option<&str>, levels: usize) -> Result<(), ValidationError> { self.check_room(parent, levels) } @@ -262,17 +242,11 @@ impl Lineage { None => 0, Some(parent) if self.contains(parent) => self.depth(parent), Some(_) => { - return Err(ValidationError::new( - "parentId", - "the parent is not a folder of this space", - )); + return Err(ValidationError::new("parentId", "the parent is not a folder of this space")); } }; if above + levels > MAX_DEPTH { - return Err(ValidationError::new( - "parentId", - format!("folders nest at most {MAX_DEPTH} deep"), - )); + return Err(ValidationError::new("parentId", format!("folders nest at most {MAX_DEPTH} deep"))); } Ok(()) } @@ -292,138 +266,183 @@ impl FolderDraft { mod tests { use super::*; - #[test] - fn a_name_is_trimmed_before_being_stored() { - assert_eq!(validated_name(" Perf ").unwrap(), "Perf"); + fn tree(links: &[(&str, Option<&str>)]) -> Lineage { + Lineage::new(links.iter().map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string)))) + } + + /// a ─ b ─ c, and a ─ d, made in that order; e alone at the top. + fn sample() -> Lineage { + tree(&[("a", None), ("b", Some("a")), ("c", Some("b")), ("d", Some("a")), ("e", None)]) + } + + /// f1 ─ f2 ─ … ─ f8, as deep as folders nest, beside `others`. + fn deepest(others: &[(&str, Option<&str>)]) -> Lineage { + let ids: Vec = (1..=MAX_DEPTH).map(|n| format!("f{n}")).collect(); + let chain = ids + .iter() + .enumerate() + .map(|(at, id)| (id.clone(), at.checked_sub(1).map(|up| ids[up].clone()))); + let others = others + .iter() + .map(|(id, parent)| ((*id).to_string(), parent.map(str::to_string))); + Lineage::new(chain.chain(others)) } #[test] - fn the_palette_rotates_and_wraps() { - assert_eq!(FolderColour::nth(0), FolderColour::Blue); - assert_eq!(FolderColour::nth(1), FolderColour::Amber); + fn colours_are_handed_out_round_the_palette() { + let first: Vec = (0..6).map(FolderColour::nth).collect(); + assert_eq!( - FolderColour::nth(FolderColour::ALL.len()), - FolderColour::Blue + first, + [ + FolderColour::Blue, + FolderColour::Amber, + FolderColour::Purple, + FolderColour::Green, + FolderColour::Red, + FolderColour::Blue, + ] ); } - fn tree() -> Lineage { - // sql ─ perf ─ index - // └ migrations - // angular - Lineage::new([ - ("sql".to_string(), None), - ("perf".to_string(), Some("sql".to_string())), - ("migrations".to_string(), Some("sql".to_string())), - ("index".to_string(), Some("perf".to_string())), - ("angular".to_string(), None), - ("orphan".to_string(), Some("gone".to_string())), - ]) + /// A file written before folders nested or had a colour. + #[test] + fn a_folder_read_without_a_parent_or_a_colour_is_blue_at_the_top() { + let folder: Folder = serde_json::from_str( + r#"{"id":"f","spaceId":"s","name":"Perf","createdAt":"2026-07-25T09:00:00Z"}"#, + ) + .unwrap(); + + assert_eq!((folder.parent_id, folder.colour), (None, FolderColour::Blue)); } #[test] - fn a_sub_tree_holds_the_folder_and_everything_under_it() { - let lineage = tree(); + fn a_folder_s_name_is_read_trimmed_and_never_blank() { + let draft = + |name: &str| FolderDraft { space_id: "s".to_string(), name: name.to_string(), parent_id: None }; - assert_eq!( - lineage.subtree("sql"), - ["sql", "perf", "migrations", "index"] - ); - assert_eq!(lineage.subtree("index"), ["index"]); - assert!(lineage.subtree("nowhere").is_empty()); + assert_eq!(draft(" Perf\t").validated_name(), Ok("Perf".to_string())); + assert_eq!(validated_name(" ").unwrap_err().field, "name"); } #[test] - fn a_path_runs_from_the_top_down_and_a_lost_parent_is_the_top() { - let lineage = tree(); + fn a_folder_whose_parent_is_not_in_the_list_stands_at_the_top() { + let lineage = tree(&[("a", Some("gone"))]); - assert_eq!(lineage.path("index"), ["sql", "perf", "index"]); - assert_eq!(lineage.path("orphan"), ["orphan"]); - assert_eq!(lineage.children(None), ["sql", "angular", "orphan"]); - assert_eq!(lineage.depth("index"), 3); - assert_eq!(lineage.height("sql"), 3); - assert_eq!(lineage.height("angular"), 1); + assert_eq!(lineage.parent("a"), None); + assert_eq!(lineage.children(None), ["a"]); + assert!(!lineage.contains("gone")); } #[test] - fn a_cycle_a_damaged_row_makes_is_walked_once() { - let lineage = Lineage::new([ - ("a".to_string(), Some("b".to_string())), - ("b".to_string(), Some("a".to_string())), - ]); + fn children_are_listed_in_the_order_the_folders_were_handed_over() { + let lineage = sample(); - assert_eq!(lineage.subtree("a"), ["a", "b"]); - assert_eq!(lineage.path("a"), ["b", "a"]); + assert_eq!(lineage.children(None), ["a", "e"]); + assert_eq!(lineage.children(Some("a")), ["b", "d"]); + assert!(lineage.children(Some("c")).is_empty()); + assert!(lineage.children(Some("unknown")).is_empty()); } #[test] - fn a_note_sits_in_the_zone_of_the_child_that_holds_its_folder() { - let lineage = tree(); + fn a_subtree_is_the_folder_first_then_everything_under_it() { + let lineage = sample(); - assert_eq!( - lineage.seat(None, Some("index")), - Seat::Zone("sql".to_string()) - ); - assert_eq!(lineage.seat(None, None), Seat::Free); - assert_eq!( - lineage.seat(Some("sql"), Some("index")), - Seat::Zone("perf".to_string()) - ); - assert_eq!(lineage.seat(Some("sql"), Some("sql")), Seat::Free); - assert_eq!(lineage.seat(Some("sql"), Some("angular")), Seat::Elsewhere); - assert_eq!(lineage.seat(Some("sql"), None), Seat::Elsewhere); + assert_eq!(lineage.subtree("a"), ["a", "b", "d", "c"]); + assert_eq!(lineage.subtree("c"), ["c"]); + assert!(lineage.subtree("unknown").is_empty()); } #[test] - fn a_folder_never_moves_into_itself_nor_out_of_its_space() { - let lineage = tree(); + fn a_path_runs_from_the_top_of_the_space_down_and_its_length_is_the_depth() { + let lineage = sample(); - assert!(lineage.check_move("sql", Some("index")).is_err()); - assert!(lineage.check_move("sql", Some("sql")).is_err()); - assert!(lineage.check_move("perf", Some("elsewhere")).is_err()); - assert!(lineage.check_move("perf", None).is_ok()); - assert!(lineage.check_move("angular", Some("index")).is_ok()); + assert_eq!(lineage.path("c"), ["a", "b", "c"]); + assert_eq!((lineage.depth("a"), lineage.depth("c")), (1, 3)); + assert!(lineage.path("unknown").is_empty()); + assert_eq!(lineage.depth("unknown"), 0); } #[test] - fn nesting_stops_at_its_depth_and_counts_what_a_folder_brings() { - let chain: Vec<(String, Option)> = (0..MAX_DEPTH) - .map(|level| { - ( - format!("f{level}"), - level.checked_sub(1).map(|up| format!("f{up}")), - ) - }) - .chain([ - ("tall".to_string(), None), - ("below".to_string(), Some("tall".to_string())), - ]) - .collect(); - let lineage = Lineage::new(chain); - let deepest = format!("f{}", MAX_DEPTH - 1); - - assert!(lineage.check_child(Some(&deepest)).is_err()); - assert!( - lineage - .check_child(Some(&format!("f{}", MAX_DEPTH - 2))) - .is_ok() - ); - assert!( - lineage - .check_move("tall", Some(&format!("f{}", MAX_DEPTH - 2))) - .is_err() - ); - assert!( - lineage - .check_move("tall", Some(&format!("f{}", MAX_DEPTH - 3))) - .is_ok() - ); + fn the_height_is_how_many_levels_a_folder_takes_with_it() { + let lineage = sample(); + + assert_eq!(lineage.height("a"), 3); + assert_eq!(lineage.height("b"), 2); + assert_eq!(lineage.height("e"), 1); + assert_eq!(lineage.height("unknown"), 0); + } + + /// Two rows naming each other, which only a damaged library holds. + #[test] + fn a_cycle_is_walked_once() { + let lineage = tree(&[("x", Some("y")), ("y", Some("x"))]); + + assert_eq!(lineage.subtree("x"), ["x", "y"]); + assert_eq!(lineage.path("x"), ["y", "x"]); } #[test] - fn every_colour_survives_its_stored_spelling() { - for colour in FolderColour::ALL { - assert_eq!(colour.as_str().parse::(), Ok(colour)); + fn a_note_sits_in_the_zone_of_the_board_s_child_that_holds_its_folder() { + let lineage = sample(); + let zone = |id: &str| Seat::Zone(id.to_string()); + let cases = [ + (None, None, Seat::Free), + (Some("a"), Some("a"), Seat::Free), + (Some("a"), None, Seat::Elsewhere), + (None, Some("c"), zone("a")), + (Some("a"), Some("c"), zone("b")), + (Some("a"), Some("d"), zone("d")), + (Some("b"), Some("d"), Seat::Elsewhere), + (Some("e"), Some("c"), Seat::Elsewhere), + (None, Some("unknown"), Seat::Elsewhere), + ]; + + for (root, folder, seat) in cases { + assert_eq!(lineage.seat(root, folder), seat, "{root:?} {folder:?}"); } } + + #[test] + fn a_folder_is_made_at_the_top_or_under_a_folder_of_the_space_short_of_the_deepest() { + let lineage = deepest(&[]); + + assert_eq!(lineage.check_child(None), Ok(())); + assert_eq!(lineage.check_child(Some("f7")), Ok(())); + assert_eq!(lineage.check_child(Some("f8")).unwrap_err().field, "parentId"); + assert_eq!(lineage.check_child(Some("elsewhere")).unwrap_err().field, "parentId"); + } + + #[test] + fn a_folder_never_moves_into_itself_or_what_it_holds() { + let lineage = sample(); + + for into in ["a", "b", "c"] { + assert_eq!(lineage.check_move("a", Some(into)).unwrap_err().field, "parentId"); + } + assert_eq!(lineage.check_move("b", Some("e")), Ok(())); + assert_eq!(lineage.check_move("b", None), Ok(())); + } + + /// The sub-tree counts whole: f7 under f6 brings f8 with it. + #[test] + fn a_folder_moves_only_where_everything_it_holds_stays_within_the_deepest_level() { + let lineage = deepest(&[("g", None), ("h", Some("g"))]); + + assert_eq!(lineage.check_move("g", Some("f6")), Ok(())); + assert_eq!(lineage.check_move("g", Some("f7")).unwrap_err().field, "parentId"); + assert_eq!(lineage.check_move("h", Some("f7")), Ok(())); + assert_eq!(lineage.check_move("unknown", Some("f7")), Ok(())); + assert_eq!(lineage.check_move("g", Some("elsewhere")).unwrap_err().field, "parentId"); + } + + #[test] + fn a_sub_tree_arriving_from_another_space_counts_its_levels_under_its_new_parent() { + let lineage = deepest(&[]); + + assert_eq!(lineage.check_arrival(Some("f6"), 2), Ok(())); + assert_eq!(lineage.check_arrival(Some("f7"), 2).unwrap_err().field, "parentId"); + assert_eq!(lineage.check_arrival(None, MAX_DEPTH), Ok(())); + assert_eq!(lineage.check_arrival(Some("elsewhere"), 1).unwrap_err().field, "parentId"); + } } diff --git a/crates/engine/src/folders/store.rs b/crates/engine/src/folders/store.rs index d3781c8a3..99ca835b5 100644 --- a/crates/engine/src/folders/store.rs +++ b/crates/engine/src/folders/store.rs @@ -32,10 +32,8 @@ struct FolderRow { impl FolderRow { fn open(self, vault: &Vault) -> Result { Ok(Folder { - created_at: iso8601::parse(&self.created_at).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "createdAt", - })?, + created_at: iso8601::parse(&self.created_at) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "createdAt" })?, name: vault.open(&self.name)?, // Degrades like `notes.language`: a folder is worth more than its swatch. colour: self.colour.parse().unwrap_or_default(), @@ -122,22 +120,13 @@ pub fn by_id( .collect(); ( folder.id.clone(), - NoteFolder { - id: folder.id.clone(), - name: folder.name.clone(), - colour: folder.colour, - path, - }, + NoteFolder { id: folder.id.clone(), name: folder.name.clone(), colour: folder.colour, path }, ) }) .collect()) } -fn find( - connection: &mut SqliteConnection, - vault: &Vault, - id: &str, -) -> Result { +fn find(connection: &mut SqliteConnection, vault: &Vault, id: &str) -> Result { folders::table .find(id) .select(FolderRow::as_select()) @@ -158,11 +147,7 @@ pub fn exists(connection: &mut SqliteConnection, id: &str) -> Result Result { +pub fn belongs_to(connection: &mut SqliteConnection, id: &str, space_id: &str) -> Result { Ok(folders::table .find(id) .filter(folders::space_id.eq(space_id)) @@ -201,9 +186,7 @@ pub fn create( name: &str, now: DateTime, ) -> Result { - connection.transaction(|connection, vault| { - create_in(connection, vault, space_id, parent_id, name, now) - }) + connection.transaction(|connection, vault| create_in(connection, vault, space_id, parent_id, name, now)) } /// For a caller already inside a transaction — an import creates the folders it needs. @@ -252,31 +235,17 @@ pub(crate) fn create_in( pub fn rename(connection: &mut Library, id: &str, name: &str) -> Result { connection.transaction(|connection, vault| { let folder = find(connection, vault, id)?; - ensure_unique_name( - connection, - vault, - &folder.space_id, - folder.parent_id.as_deref(), - name, - Some(id), - )?; + ensure_unique_name(connection, vault, &folder.space_id, folder.parent_id.as_deref(), name, Some(id))?; diesel::update(folders::table.find(id)) .set(folders::name.eq(vault.seal(name)?)) .execute(connection)?; - Ok(Folder { - name: name.to_string(), - ..folder - }) + Ok(Folder { name: name.to_string(), ..folder }) }) } -pub fn recolour( - connection: &mut Library, - id: &str, - colour: FolderColour, -) -> Result { +pub fn recolour(connection: &mut Library, id: &str, colour: FolderColour) -> Result { connection.transaction(|connection, vault| { diesel::update(folders::table.find(id)) .set(folders::colour.eq(colour.as_str())) @@ -313,14 +282,7 @@ pub fn move_to( } else { lineage(connection, space_id)?.check_arrival(parent_id, from.height(id).max(1))?; } - ensure_unique_name( - connection, - vault, - space_id, - parent_id, - &folder.name, - Some(id), - )?; + ensure_unique_name(connection, vault, space_id, parent_id, &folder.name, Some(id))?; if folder.space_id != space_id { was.notes = cross(connection, &from.subtree(id), space_id)?; } @@ -333,10 +295,7 @@ pub fn move_to( /// The undo of [`move_to`]: back under the parent it left, in its space and in the frame it /// had; `None` when a parent deleted since, or one it now holds, leaves it where it is. The /// notes that went back: every note filed in it, none left in a folder of another space. -pub fn move_back( - connection: &mut Library, - was: &FolderMove, -) -> Result>, StorageError> { +pub fn move_back(connection: &mut Library, was: &FolderMove) -> Result>, StorageError> { connection.transaction(|connection, vault| { let folder = find(connection, vault, &was.folder_id)?; let here = lineage(connection, &folder.space_id)?; @@ -344,17 +303,10 @@ pub fn move_back( let room = if folder.space_id == was.space_id { here.check_move(&folder.id, parent) } else { - lineage(connection, &was.space_id)? - .check_arrival(parent, here.height(&folder.id).max(1)) + lineage(connection, &was.space_id)?.check_arrival(parent, here.height(&folder.id).max(1)) }; - let named = ensure_unique_name( - connection, - vault, - &was.space_id, - parent, - &folder.name, - Some(&folder.id), - ); + let named = + ensure_unique_name(connection, vault, &was.space_id, parent, &folder.name, Some(&folder.id)); if room.is_err() || named.is_err() { return Ok(None); } @@ -414,10 +366,7 @@ fn place( /// What it held goes to its parent — its notes, filed there, and its sub-folders, each to a /// free slot on that board — or loose at the top of the space. `updated_at` is not touched: /// the user aimed at the folder. -pub fn contents( - connection: &mut Library, - id: &str, -) -> Result { +pub fn contents(connection: &mut Library, id: &str) -> Result { let (connection, _vault) = connection.split(); let under = lineage_of(connection, id)?.subtree(id); Ok(super::model::FolderContents { @@ -591,20 +540,13 @@ pub fn move_into( .load::<(String, String, Option)>(connection)? .into_iter() .filter(|(_, _, current)| current.as_deref() != Some(folder_id)) - .map(|(note_id, space_id, folder_id)| NotePlacement { - note_id, - space_id, - folder_id, - }) + .map(|(note_id, space_id, folder_id)| NotePlacement { note_id, space_id, folder_id }) .collect(); let touched: Vec = moved.iter().map(|one| one.note_id.clone()).collect(); board::forget_positions(connection, &touched)?; diesel::update(notes::table.filter(notes::id.eq_any(&touched))) - .set(( - notes::space_id.eq(space_id), - notes::folder_id.eq(Some(folder_id)), - )) + .set((notes::space_id.eq(space_id), notes::folder_id.eq(Some(folder_id)))) .execute(connection)?; let lineage = lineage_of(connection, folder_id)?; @@ -615,10 +557,7 @@ pub fn move_into( } /// How many live notes these folders hold, which is what a zone has to be tall enough for. -fn count_filed( - connection: &mut SqliteConnection, - folder_ids: &[String], -) -> Result { +fn count_filed(connection: &mut SqliteConnection, folder_ids: &[String]) -> Result { let count: i64 = notes::table .filter(notes::folder_id.eq_any(folder_ids)) .filter(notes::deleted_at.is_null()) @@ -640,10 +579,7 @@ pub fn restore_filings( connection.transaction(|connection, _vault| { let mut restored = 0; - let ids: Vec = filings - .iter() - .map(|filing| filing.note_id.clone()) - .collect(); + let ids: Vec = filings.iter().map(|filing| filing.note_id.clone()).collect(); board::forget_positions(connection, &ids)?; for filing in filings { @@ -654,21 +590,22 @@ pub fn restore_filings( continue; } - restored += diesel::update( - notes::table - .find(&filing.note_id) - .filter(notes::deleted_at.is_null()), - ) - .set(notes::folder_id.eq(filing.folder_id.as_deref())) - .execute(connection)?; + restored += + diesel::update(notes::table.find(&filing.note_id).filter(notes::deleted_at.is_null())) + .set(notes::folder_id.eq(filing.folder_id.as_deref())) + .execute(connection)?; } - // Undoing puts notes back into zones that may no longer be tall enough for them. + // Undoing puts notes back into zones that may no longer be tall enough for them; a + // folder gone since has no zone left to grow. for folder_id in filings .iter() .filter_map(|filing| filing.folder_id.as_deref()) .collect::>() { + if !exists(connection, folder_id)? { + continue; + } let lineage = lineage_of(connection, folder_id)?; grow_with_ancestors(connection, &lineage, folder_id, card)?; } diff --git a/crates/engine/src/folders/store/board.rs b/crates/engine/src/folders/store/board.rs index e6a6cb024..34370fdea 100644 --- a/crates/engine/src/folders/store/board.rs +++ b/crates/engine/src/folders/store/board.rs @@ -10,8 +10,8 @@ use crate::db::Library; use crate::db::schema::{folders, note_positions, notes}; use crate::error::StorageError; use crate::folders::board::{ - self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, - Occupancy, ZoneContents, ZonePlacement, + self, BoardArrangement, BoardFrame, BoardLayout, BoardPoint, BoardScope, CardPlacement, Occupancy, + ZoneContents, ZonePlacement, }; /// What a board read resolves before anything can be drawn: where each zone sits, and @@ -23,12 +23,7 @@ type FrameColumns = (Option, Option, Option, Option); /// All four columns move together: a half-laid-out folder is not a state, and a folder /// never laid out answers `None`. fn frame_from((x, y, width, height): FrameColumns) -> Option { - Some(BoardFrame { - x: x?, - y: y?, - width: width?, - height: height?, - }) + Some(BoardFrame { x: x?, y: y?, width: width?, height: height? }) } pub fn frames( @@ -37,10 +32,7 @@ pub fn frames( ) -> Result, StorageError> { let rows = folders::table .filter(folders::space_id.eq(space_id)) - .select(( - folders::id, - (folders::x, folders::y, folders::w, folders::h), - )) + .select((folders::id, (folders::x, folders::y, folders::w, folders::h))) .load::<(String, FrameColumns)>(connection)?; Ok(rows @@ -81,14 +73,7 @@ pub fn grow_to_fit( return Ok(()); } - set_frame( - connection, - folder_id, - board::clamp(BoardFrame { - height: needed, - ..frame - }), - ) + set_frame(connection, folder_id, board::clamp(BoardFrame { height: needed, ..frame })) } pub fn set_frame( @@ -116,23 +101,13 @@ pub fn positions( ) -> Result, StorageError> { let rows = note_positions::table .filter( - note_positions::note_id.eq_any( - notes::table - .select(notes::id) - .filter(notes::space_id.eq(space_id.to_string())), - ), + note_positions::note_id + .eq_any(notes::table.select(notes::id).filter(notes::space_id.eq(space_id.to_string()))), ) - .select(( - note_positions::note_id, - note_positions::x, - note_positions::y, - )) + .select((note_positions::note_id, note_positions::x, note_positions::y)) .load::<(String, i32, i32)>(connection)?; - Ok(rows - .into_iter() - .map(|(note_id, x, y)| (note_id, BoardPoint { x, y })) - .collect()) + Ok(rows.into_iter().map(|(note_id, x, y)| (note_id, BoardPoint { x, y })).collect()) } pub fn set_position( @@ -152,10 +127,7 @@ pub fn set_position( } /// A row exists only for a loose note: filing one drops it, since a filed card flows. -pub fn forget_positions( - connection: &mut SqliteConnection, - note_ids: &[String], -) -> Result<(), StorageError> { +pub fn forget_positions(connection: &mut SqliteConnection, note_ids: &[String]) -> Result<(), StorageError> { if note_ids.is_empty() { return Ok(()); } @@ -183,11 +155,7 @@ pub fn save_layout( if !crate::folders::store::exists(connection, &placement.folder_id)? { return Err(StorageError::FolderNotFound(placement.folder_id.clone())); } - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } // ⚠️ Only a note filed in the root has a place on its board: one filed elsewhere between @@ -207,11 +175,7 @@ pub fn save_layout( continue; } - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } Ok(()) @@ -240,10 +204,8 @@ pub fn geometry( stored_positions.retain(|id, _| loose.contains(id.as_str())); let folder_ids: Vec<&String> = zones.iter().map(|(id, _)| id).collect(); - let missing: Vec<&&String> = folder_ids - .iter() - .filter(|id| !stored_frames.contains_key(**id)) - .collect(); + let missing: Vec<&&String> = + folder_ids.iter().filter(|id| !stored_frames.contains_key(**id)).collect(); if !missing.is_empty() { // Against every zone, so one added later takes its reading-order slot rather @@ -348,11 +310,7 @@ fn loose_ids( }; Ok(query - .order(( - notes::pinned.desc(), - notes::updated_at.desc(), - notes::id.asc(), - )) + .order((notes::pinned.desc(), notes::updated_at.desc(), notes::id.asc())) .select(notes::id) .load::(connection)?) } @@ -387,28 +345,19 @@ pub fn arrange( }; for placement in &next.zones { - set_frame( - connection, - &placement.folder_id, - board::clamp(placement.frame), - )?; + set_frame(connection, &placement.folder_id, board::clamp(placement.frame))?; } for placement in &next.cards { - set_position( - connection, - &placement.note_id, - board::clamp_point(placement.position), - )?; + set_position(connection, &placement.note_id, board::clamp_point(placement.position))?; } let zones: Vec = next .zones .iter() .filter_map(|placement| { - before.get(&placement.folder_id).map(|frame| ZonePlacement { - folder_id: placement.folder_id.clone(), - frame: *frame, - }) + before + .get(&placement.folder_id) + .map(|frame| ZonePlacement { folder_id: placement.folder_id.clone(), frame: *frame }) }) .collect(); let cards: Vec = next @@ -417,34 +366,27 @@ pub fn arrange( .filter_map(|placement| { places .get(&placement.note_id) - .map(|position| CardPlacement { - note_id: placement.note_id.clone(), - position: *position, - }) + .map(|position| CardPlacement { note_id: placement.note_id.clone(), position: *position }) }) .collect(); let moved = zones .iter() .filter(|was| { - next.zones.iter().any(|now| { - now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame - }) + next.zones + .iter() + .any(|now| now.folder_id == was.folder_id && board::clamp(now.frame) != was.frame) }) .count() + cards .iter() .filter(|was| { next.cards.iter().any(|now| { - now.note_id == was.note_id - && board::clamp_point(now.position) != was.position + now.note_id == was.note_id && board::clamp_point(now.position) != was.position }) }) .count(); - Ok(BoardArrangement { - moved: saturating_u32(moved), - previous: BoardLayout { zones, cards }, - }) + Ok(BoardArrangement { moved: saturating_u32(moved), previous: BoardLayout { zones, cards } }) }) } diff --git a/crates/engine/src/host.rs b/crates/engine/src/host.rs index db12d7fee..49044492a 100644 --- a/crates/engine/src/host.rs +++ b/crates/engine/src/host.rs @@ -42,10 +42,7 @@ pub struct RecordingSink(Mutex>); impl RecordingSink { pub fn events(&self) -> Vec { - self.0 - .lock() - .map(|events| events.clone()) - .unwrap_or_default() + self.0.lock().map(|events| events.clone()).unwrap_or_default() } } @@ -65,11 +62,7 @@ mod tests { fn finished(id: &str) -> EngineEvent { EngineEvent::Run(RunEvent { id: id.to_string(), - step: RunStep::Finished { - cancelled: false, - millis: 1, - capped: false, - }, + step: RunStep::Finished { cancelled: false, millis: 1, capped: false }, }) } diff --git a/crates/engine/src/http.rs b/crates/engine/src/http.rs index 818b659ac..6a3cfd783 100644 --- a/crates/engine/src/http.rs +++ b/crates/engine/src/http.rs @@ -48,17 +48,11 @@ pub fn http_tree(engine: &Engine) -> Result { } /// The palette's requests, ranked here: the URL is read from each sealed document. -pub fn search_http_requests( - engine: &Engine, - search: &str, -) -> Result, AppError> { +pub fn search_http_requests(engine: &Engine, search: &str) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(search::rank( - store::search_candidates(&mut connection)?, - search, - )) + Ok(search::rank(store::search_candidates(&mut connection)?, search)) } pub fn create_http_collection(engine: &Engine, name: &str) -> Result { @@ -67,11 +61,7 @@ pub fn create_http_collection(engine: &Engine, name: &str) -> Result Result { +pub fn create_http_request(engine: &Engine, draft: &HttpRequestDraft) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; let mut connection = lock(db)?; - Ok(store::create_request( - &mut connection, - draft, - &name, - Utc::now(), - )?) + Ok(store::create_request(&mut connection, draft, &name, Utc::now())?) } /// The first save of a request where nothing holds it yet: what `create` names is created @@ -121,16 +103,8 @@ pub fn create_http_request_in( ) -> Result { let db = &engine.db; let name = model::validated_name(&draft.name)?; - let collection = create - .collection - .as_deref() - .map(model::validated_name) - .transpose()?; - let folder = create - .folder - .as_deref() - .map(model::validated_name) - .transpose()?; + let collection = create.collection.as_deref().map(model::validated_name).transpose()?; + let folder = create.folder.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; @@ -157,21 +131,11 @@ pub fn save_http_request( patch: &HttpRequestPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(model::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(model::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(store::save_request( - &mut connection, - id, - patch, - name.as_deref(), - Utc::now(), - )?) + Ok(store::save_request(&mut connection, id, patch, name.as_deref(), Utc::now())?) } pub fn rename_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result<(), AppError> { @@ -199,11 +163,7 @@ pub fn delete_http_item(engine: &Engine, item: &HttpItem) -> Result<(), AppError } /// The copy's name comes from the front: no user-visible word is Rust's. -pub fn duplicate_http_item( - engine: &Engine, - item: &HttpItem, - name: &str, -) -> Result { +pub fn duplicate_http_item(engine: &Engine, item: &HttpItem, name: &str) -> Result { let db = &engine.db; let name = model::validated_name(name)?; @@ -219,10 +179,7 @@ pub fn move_http_item(engine: &Engine, item: &HttpItem, place: &HttpPlace) -> Re Ok(store::move_item(&mut connection, item, place)?) } -pub fn http_settings( - engine: &Engine, - item: &HttpItem, -) -> Result { +pub fn http_settings(engine: &Engine, item: &HttpItem) -> Result { let db = &engine.db; let mut connection = lock(db)?; @@ -252,10 +209,8 @@ pub fn save_http_settings( let mut connection = lock(db)?; // The dialog does not hold the run order: the one the runner left is kept. - let settings = model::ContainerSettings { - run_order: store::settings(&mut connection, item)?.run_order, - ..settings - }; + let settings = + model::ContainerSettings { run_order: store::settings(&mut connection, item)?.run_order, ..settings }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -269,11 +224,7 @@ pub fn inherited_http_settings( let db = &engine.db; let mut connection = lock(db)?; - Ok(store::inherited( - &mut connection, - collection_id, - folder_id.map(std::string::String::as_str), - )?) + Ok(store::inherited(&mut connection, collection_id, folder_id.map(std::string::String::as_str))?) } /// What a body implies, whether a JSON one reads, and whether its method seldom carries one: @@ -302,19 +253,6 @@ pub struct BodyAnswer { pub unusual: bool, } -/// Each header's fault by its rank, or none: the table marks the row and says why. The rule is -/// the model's; the table holds none. -pub fn check_http_headers( - rows: &[model::KeyValue], -) -> Result>, AppError> { - Ok(model::header_faults(rows)) -} - -/// `Nom: valeur` typed in a name, or lines pasted from a browser's network tab, as rows. -pub fn read_http_headers(text: &str) -> Result, AppError> { - Ok(model::headers_from_text(text)) -} - /// What a request sends without a row of its own — the body's type, what it inherits, the /// application's `User-Agent` — read as a send reads it: the editor lists the answer and /// decides none of it. @@ -329,26 +267,13 @@ pub fn implied_http_headers( let inherited = match collection_id { Some(collection_id) => { let mut connection = lock(db)?; - store::inherited( - &mut connection, - &collection_id, - folder_id.map(std::string::String::as_str), - )? + store::inherited(&mut connection, &collection_id, folder_id.map(std::string::String::as_str))? } None => settings::inherit(&[]), }; Ok(send::implied(kind, document, &inherited)) } -/// The edited side wins: the query string rewritten from the table, or the table from the URL. -pub fn sync_http_query( - url: &str, - params: &[model::KeyValue], - edited: query::QuerySide, -) -> Result { - Ok(query::sync(url, params, edited)) -} - pub fn reorder_http_collection(engine: &Engine, id: &str, index: u32) -> Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; @@ -388,12 +313,7 @@ fn resolver_for( inherited: &settings::Inherited, environment_id: Option<&str>, ) -> Result { - Ok(variables::Resolver::new(&layers_for( - connection, - own, - inherited, - environment_id, - )?)) + Ok(variables::Resolver::new(&layers_for(connection, own, inherited, environment_id)?)) } fn layers_for( @@ -405,11 +325,8 @@ fn layers_for( use variables::{VariableLayer, VariableScope}; let sets = environments::store::list(connection)?; - let mut layers = vec![VariableLayer { - scope: VariableScope::Request, - from: String::new(), - variables: own.to_vec(), - }]; + let mut layers = + vec![VariableLayer { scope: VariableScope::Request, from: String::new(), variables: own.to_vec() }]; layers.extend(inherited.variables.iter().cloned()); if let Some(environment) = sets .environments @@ -437,31 +354,12 @@ pub fn generate_http_code( request: CodeRequestOf, ) -> Result { let db = &engine.db; - let CodeRequestOf { - target, - options, - kind, - method, - document, - collection_id, - folder_id, - environment_id, - } = request; + let CodeRequestOf { target, options, kind, method, document, collection_id, folder_id, environment_id } = + request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let layers = layers_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; - Ok(codegen::generate( - target, options, kind, method, &document, &inherited, &layers, - )) + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let layers = layers_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; + Ok(codegen::generate(target, options, kind, method, &document, &inherited, &layers)) } #[derive(Debug, Clone)] @@ -483,25 +381,10 @@ pub fn http_variables( request: VariablesRequest, ) -> Result, AppError> { let db = &engine.db; - let VariablesRequest { - kind, - document, - collection_id, - folder_id, - environment_id, - } = request; + let VariablesRequest { kind, document, collection_id, folder_id, environment_id } = request; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; Ok(resolver.used(&variables::texts(kind, &document, &inherited))) } @@ -522,10 +405,7 @@ pub fn http_run_order(engine: &Engine, item: &HttpItem) -> Result Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; - let settings = model::ContainerSettings { - run_order: order, - ..store::settings(&mut connection, item)? - }; + let settings = model::ContainerSettings { run_order: order, ..store::settings(&mut connection, item)? }; Ok(store::save_settings(&mut connection, item, &settings)?) } @@ -547,10 +424,7 @@ pub fn save_http_run_order( /// A collection or a folder run, one request after the other, each sent as a send is — its /// scripts, its tests, its extractions — but written in no history. Each step is said as an /// event; answers once the run is over. The lock is held for reads alone, never over a send. -pub async fn run_http_collection( - engine: Arc, - run: runner::RunRequest, -) -> Result<(), AppError> { +pub async fn run_http_collection(engine: Arc, run: runner::RunRequest) -> Result<(), AppError> { let tree = db::run(Arc::clone(&engine), |engine| { let db = &engine.db; let mut connection = lock(db)?; @@ -563,16 +437,9 @@ pub async fn run_http_collection( .iter() .filter_map(|id| placed.iter().find(|known| &known.id == id).cloned()) .collect(); - let rows = run - .data - .as_ref() - .map(|data| data.rows.clone()) - .unwrap_or_default(); - let iterations = if rows.is_empty() { - run.iterations.max(1) - } else { - u32::try_from(rows.len()).unwrap_or(u32::MAX) - }; + let rows = run.data.as_ref().map(|data| data.rows.clone()).unwrap_or_default(); + let iterations = + if rows.is_empty() { run.iterations.max(1) } else { u32::try_from(rows.len()).unwrap_or(u32::MAX) }; let runs = &engine.runs; runs.start(&run.id); let started = std::time::Instant::now(); @@ -589,27 +456,13 @@ pub async fn run_http_collection( } steps += 1; let placed = &order[index]; - let step = RunStep { - run: &run, - iteration, - iterations, - index, - steps, - placed, - row: &row, - }; + let step = RunStep { run: &run, iteration, iterations, index, steps, placed, row: &row }; let Some((result, next)) = run_step(&engine, step, &mut overlay).await else { cancelled = true; break 'run; }; let failed = result.failed(); - say_run( - &engine, - &run.id, - runner::RunStep::Ended { - result: Box::new(result), - }, - ); + say_run(&engine, &run.id, runner::RunStep::Ended { result: Box::new(result) }); if run.stop_on_failure && failed { break 'run; } @@ -630,15 +483,7 @@ pub async fn run_http_collection( } runs.finish(&run.id); let millis = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); - say_run( - &engine, - &run.id, - runner::RunStep::Finished { - cancelled, - millis, - capped, - }, - ); + say_run(&engine, &run.id, runner::RunStep::Finished { cancelled, millis, capped }); Ok(()) } @@ -665,11 +510,7 @@ pub fn cancel_http_send(engine: &Engine, id: &str) -> Result { } /// The whole body of the last answer to `id`, not the text shown: `false` when there is none. -pub async fn save_http_response( - engine: Arc, - id: String, - path: String, -) -> Result { +pub async fn save_http_response(engine: Arc, id: String, path: String) -> Result { crate::transfer::model::validate_path(&path)?; off_thread(move || engine.sending.save(&id, Path::new(&path)).context(&path)) .await? @@ -683,10 +524,7 @@ pub fn forget_http_response(engine: &Engine, id: &str) -> Result<(), AppError> { } /// The last answer to `id` as an image to show, when it is one. -pub async fn http_response_image( - engine: Arc, - id: String, -) -> Result, AppError> { +pub async fn http_response_image(engine: Arc, id: String) -> Result, AppError> { off_thread(move || engine.sending.image(&id)).await } @@ -701,17 +539,11 @@ pub async fn http_response_note( } /// What was sent, newest first, a group a local day. -pub fn http_history( - engine: &Engine, - tz_offset_minutes: i32, -) -> Result, AppError> { +pub fn http_history(engine: &Engine, tz_offset_minutes: i32) -> Result, AppError> { let db = &engine.db; let mut connection = lock(db)?; - Ok(history::by_day( - history::store::list(&mut connection)?, - tz_offset_minutes, - )) + Ok(history::by_day(history::store::list(&mut connection)?, tz_offset_minutes)) } pub fn http_history_entry(engine: &Engine, id: &str) -> Result { @@ -737,20 +569,14 @@ pub fn clear_http_history(engine: &Engine) -> Result { } /// One entry gone, answered whole: its undo hands it back to `restore_http_history_entry`. -pub fn delete_http_history_entry( - engine: &Engine, - id: &str, -) -> Result { +pub fn delete_http_history_entry(engine: &Engine, id: &str) -> Result { let db = &engine.db; let mut connection = lock(db)?; Ok(history::store::delete(&mut connection, id)?) } -pub fn restore_http_history_entry( - engine: &Engine, - entry: &history::HistoryEntry, -) -> Result<(), AppError> { +pub fn restore_http_history_entry(engine: &Engine, entry: &history::HistoryEntry) -> Result<(), AppError> { let db = &engine.db; let mut connection = lock(db)?; @@ -775,11 +601,7 @@ pub fn http_history_onto_request( Err(crate::error::StorageError::HttpItemNotFound(_)) => return Ok(None), Err(error) => return Err(error.into()), }; - let above = store::inherited( - &mut connection, - ¤t.collection_id, - current.folder_id.as_deref(), - )?; + let above = store::inherited(&mut connection, ¤t.collection_id, current.folder_id.as_deref())?; Ok(Some(history::onto(&entry, ¤t, &above.headers))) } @@ -788,16 +610,11 @@ pub fn http_history_draft(engine: &Engine, id: &str) -> Result Result { +pub fn describe_graphql(document: &graphql::GraphqlDocument) -> Result { Ok(graphql::describe(document)) } @@ -818,54 +635,26 @@ pub struct WebsocketRequest { /// Its headers and auth composed like a request's, under the lock for what it inherits; the /// handshake waited on without it. Answers once the socket is open. -pub async fn connect_websocket( - engine: Arc, - request: WebsocketRequest, -) -> Result<(), AppError> { - let WebsocketRequest { - id, - mut document, - collection_id, - folder_id, - environment_id, - } = request; +pub async fn connect_websocket(engine: Arc, request: WebsocketRequest) -> Result<(), AppError> { + let WebsocketRequest { id, mut document, collection_id, folder_id, environment_id } = request; document.body = model::RequestBody::None; let outgoing = db::run(Arc::clone(&engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; - let resolver = resolver_for( - &mut connection, - &document.variables, - &inherited, - environment_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; + let resolver = + resolver_for(&mut connection, &document.variables, &inherited, environment_id.as_deref())?; let (mut document, inherited) = variables::resolve(&document, &inherited, &resolver); document.url = websocket::socket_url(&document.url)?; - Ok(send::compose( - model::RequestKind::Http, - model::HttpMethod::Get, - &document, - &inherited, - ) - .map(|outgoing| (outgoing, document.websocket.protocols))?) + Ok(send::compose(model::RequestKind::Http, model::HttpMethod::Get, &document, &inherited) + .map(|outgoing| (outgoing, document.websocket.protocols))?) }) .await?; let (outgoing, protocols) = outgoing; Ok(engine .sockets - .connect( - &engine.runtime, - Arc::clone(&engine.events), - id, - outgoing, - &protocols, - ) + .connect(&engine.runtime, Arc::clone(&engine.events), id, outgoing, &protocols) .await?) } @@ -923,20 +712,13 @@ pub fn http_environments(engine: &Engine) -> Result Result { +pub fn create_http_environment(engine: &Engine, name: &str) -> Result { let db = &engine.db; let name = environments::validated_name(name)?; let mut connection = lock(db)?; - Ok(environments::store::create( - &mut connection, - &name, - Utc::now(), - )?) + Ok(environments::store::create(&mut connection, &name, Utc::now())?) } pub fn save_http_environment( @@ -945,20 +727,11 @@ pub fn save_http_environment( patch: &environments::EnvironmentPatch, ) -> Result { let db = &engine.db; - let name = patch - .name - .as_deref() - .map(environments::validated_name) - .transpose()?; + let name = patch.name.as_deref().map(environments::validated_name).transpose()?; let mut connection = lock(db)?; - Ok(environments::store::save( - &mut connection, - id, - patch, - name.as_deref(), - )?) + Ok(environments::store::save(&mut connection, id, patch, name.as_deref())?) } pub fn save_http_globals( @@ -968,11 +741,7 @@ pub fn save_http_globals( let db = &engine.db; let mut connection = lock(db)?; - Ok(environments::store::save_globals( - &mut connection, - variables, - Utc::now(), - )?) + Ok(environments::store::save_globals(&mut connection, variables, Utc::now())?) } /// The copy's name comes from the front: no user-visible word is Rust's. @@ -986,12 +755,7 @@ pub fn duplicate_http_environment( let mut connection = lock(db)?; - Ok(environments::store::duplicate( - &mut connection, - id, - &name, - Utc::now(), - )?) + Ok(environments::store::duplicate(&mut connection, id, &name, Utc::now())?) } pub fn delete_http_environment(engine: &Engine, id: &str) -> Result<(), AppError> { @@ -1000,10 +764,3 @@ pub fn delete_http_environment(engine: &Engine, id: &str) -> Result<(), AppError Ok(environments::store::delete(&mut connection, id)?) } - -/// Each variable's fault by its rank, or none: the table marks the row, the rule is the model's. -pub fn check_http_variables( - variables: &[environments::Variable], -) -> Result>, AppError> { - Ok(environments::variable_faults(variables)) -} diff --git a/crates/engine/src/http/codegen.rs b/crates/engine/src/http/codegen.rs index 35aea7728..3ed77c8df 100644 --- a/crates/engine/src/http/codegen.rs +++ b/crates/engine/src/http/codegen.rs @@ -167,11 +167,7 @@ impl CodeRequest { /// starting on a variable left unresolved is written as typed: `{{base}}` holds its own scheme. fn with_scheme(url: &str) -> String { let url = url.trim(); - if url.contains("://") || url.starts_with("{{") { - url.to_string() - } else { - format!("http://{url}") - } + if url.contains("://") || url.starts_with("{{") { url.to_string() } else { format!("http://{url}") } } fn append_query(url: &mut String, pairs: &[(&str, &str)]) { @@ -195,11 +191,7 @@ pub fn request_of( ) -> CodeRequest { let mut url = with_scheme(&document.url); let auth = send::auth_of(document, inherited); - if let RequestAuth::ApiKey { - name, - value, - place: KeyPlace::Query, - } = auth + if let RequestAuth::ApiKey { name, value, place: KeyPlace::Query } = auth && !name.trim().is_empty() { append_query(&mut url, &[(name.trim(), value)]); @@ -215,12 +207,7 @@ pub fn request_of( if let Some(variables) = variables { pairs.push(("variables", variables)); } - if let Some(name) = document - .graphql - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.graphql.operation_name.as_deref().filter(|name| !name.is_empty()) { pairs.push(("operationName", name)); } append_query(&mut url, &pairs); @@ -228,10 +215,7 @@ pub fn request_of( } RequestKind::Graphql => { let variables = graphql::variables(&document.graphql).ok().flatten(); - ( - HttpMethod::Post, - CodeBody::Text(graphql::body(&document.graphql, variables)), - ) + (HttpMethod::Post, CodeBody::Text(graphql::body(&document.graphql, variables))) } RequestKind::Http | RequestKind::Websocket => (method, body_of(&document.body)), }; @@ -248,9 +232,7 @@ pub fn request_of( fn body_of(body: &RequestBody) -> CodeBody { match body { RequestBody::None => CodeBody::None, - RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => { - CodeBody::None - } + RequestBody::Json { text } | RequestBody::Text { text } if text.is_empty() => CodeBody::None, RequestBody::Json { text } | RequestBody::Text { text } => CodeBody::Text(text.clone()), RequestBody::Form { fields } => CodeBody::Form( fields @@ -316,22 +298,13 @@ pub fn generate( } } let (document, inherited) = if options.resolve_variables { - let resolver = if options.include_secrets { - everything - } else { - Resolver::new(&without_secrets(layers)) - }; + let resolver = + if options.include_secrets { everything } else { Resolver::new(&without_secrets(layers)) }; variables::resolve(document, inherited, &resolver) } else { (document.clone(), inherited.clone()) }; - let request = request_of( - kind, - method, - &document, - &inherited, - options.follow_redirects, - ); + let request = request_of(kind, method, &document, &inherited, options.follow_redirects); let notice = (!target.sends_multipart() && matches!(request.body, CodeBody::Multipart(_))) .then_some(CodeNotice::MultipartUnsupported); let code = match target { @@ -356,13 +329,7 @@ pub fn generate( CodeTarget::Dart => dart::write(&request), CodeTarget::Elixir => req::write(&request), }; - GeneratedCode { - code, - language: target.language(), - secrets, - unresolved, - notice, - } + GeneratedCode { code, language: target.language(), secrets, unresolved, notice } } /// `'…'` for a POSIX shell: a quote inside closes, escapes and reopens. @@ -388,13 +355,7 @@ pub fn shell_lines(first: &str, arguments: &[String], multiline: bool) -> String lines .iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} \\") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} \\") }) .collect::>() .join("\n") } @@ -423,10 +384,7 @@ pub(crate) mod golden { url: "https://api.exemple.fr/customers/cus_42/invoices?page=1&limit=50".to_string(), headers: vec![ ("Accept".to_string(), "application/json".to_string()), - ( - "Authorization".to_string(), - "Bearer {{accessToken}}".to_string(), - ), + ("Authorization".to_string(), "Bearer {{accessToken}}".to_string()), ], basic: None, body: CodeBody::None, @@ -443,10 +401,7 @@ pub(crate) mod golden { let form = CodeRequest { method: HttpMethod::Post, url: "https://auth.exemple.fr/token".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/x-www-form-urlencoded".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string())], basic: Some(("billing-web".to_string(), "{{clientSecret}}".to_string())), body: CodeBody::Form(vec![ ("grant_type".to_string(), "client_credentials".to_string()), @@ -460,11 +415,7 @@ pub(crate) mod golden { headers: Vec::new(), basic: None, body: CodeBody::Multipart(vec![ - CodePart { - name: "title".to_string(), - value: "Facture".to_string(), - file: false, - }, + CodePart { name: "title".to_string(), value: "Facture".to_string(), file: false }, CodePart { name: "scan".to_string(), value: "C:/Users/ada/facture.pdf".to_string(), @@ -476,21 +427,12 @@ pub(crate) mod golden { let file = CodeRequest { method: HttpMethod::Post, url: "https://api.exemple.fr/upload".to_string(), - headers: vec![( - "Content-Type".to_string(), - "application/octet-stream".to_string(), - )], + headers: vec![("Content-Type".to_string(), "application/octet-stream".to_string())], basic: None, body: CodeBody::File("/tmp/archive.zip".to_string()), follow_redirects: false, }; - vec![ - ("get", get), - ("json", json), - ("form", form), - ("multipart", multipart), - ("file", file), - ] + vec![("get", get), ("json", json), ("form", form), ("multipart", multipart), ("file", file)] } /// The file under `golden/`, or written there when `GOLDEN_WRITE` is set. @@ -514,182 +456,310 @@ pub(crate) mod golden { mod tests { use super::*; use crate::http::environments::Variable; - use crate::http::model::KeyValue; + use crate::http::model::{FormPart, KeyValue}; use crate::http::settings::inherit; use crate::http::variables::VariableScope; - fn layers() -> Vec { - let variable = |name: &str, value: &str, kind: VariableKind| Variable { - name: name.to_string(), - value: value.to_string(), - kind, - ..Variable::default() - }; - vec![VariableLayer { - scope: VariableScope::Environment, - from: "Staging".to_string(), - variables: vec![ - variable("baseUrl", "https://api.exemple.fr", VariableKind::Text), - variable("token", "t0k3n", VariableKind::Secret), - ], - }] + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } - fn document() -> RequestDocument { - RequestDocument { - url: "{{baseUrl}}/me?tenant={{tenant}}".to_string(), - headers: vec![KeyValue { - key: "Authorization".to_string(), - value: "Bearer {{token}}".to_string(), - ..KeyValue::default() - }], - ..RequestDocument::default() - } + fn off(key: &str) -> KeyValue { + KeyValue { enabled: false, ..row(key, "x") } } - fn options(resolve: bool, secrets: bool) -> CodeOptions { - CodeOptions { - resolve_variables: resolve, - include_secrets: secrets, - multiline: false, - follow_redirects: false, - } + fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } } - fn generated(options: CodeOptions) -> GeneratedCode { - generate( - CodeTarget::Curl, - options, - RequestKind::Http, - HttpMethod::Get, - &document(), - &inherit(&[]), - &layers(), - ) + fn http(document: &RequestDocument) -> CodeRequest { + request_of(RequestKind::Http, HttpMethod::Post, document, &inherit(&[]), false) } + fn layer(variables: Vec) -> VariableLayer { + VariableLayer { scope: VariableScope::Environment, from: "Prod".to_string(), variables } + } + + fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { + Variable { name: name.to_string(), value: value.to_string(), kind, ..Variable::default() } + } + + /// What a snippet of each target is saved as; the three that build no multipart body say so. #[test] - fn every_target_survives_its_stored_spelling() { + fn each_target_is_saved_in_its_language_and_says_what_it_cannot_send() { for target in CodeTarget::ALL { assert_eq!(target.as_str().parse::(), Ok(target)); + assert_eq!( + target.sends_multipart(), + !matches!(target, CodeTarget::Wget | CodeTarget::Java | CodeTarget::Swift), + "{target:?}" + ); + } + for (target, language) in [ + (CodeTarget::Curl, Language::Sh), + (CodeTarget::Powershell, Language::Ps1), + (CodeTarget::Undici, Language::Js), + (CodeTarget::Angular, Language::Ts), + (CodeTarget::Httpx, Language::Py), + (CodeTarget::Reqwest, Language::Rs), + (CodeTarget::Okhttp, Language::Kt), + (CodeTarget::Csharp, Language::Cs), + (CodeTarget::Guzzle, Language::Php), + (CodeTarget::Elixir, Language::Ex), + ] { + assert_eq!(target.language(), language, "{target:?}"); } } + /// As it is sent: a URL without a scheme over plain HTTP, one starting on a variable as + /// typed; an API key in the query added to it, encoded. #[test] - fn a_secret_stays_its_name_unless_asked_for_and_what_nothing_sets_is_said() { - let kept = generated(options(true, false)); - assert!( - kept.code - .contains("https://api.exemple.fr/me?tenant={{tenant}}") - ); - assert!(kept.code.contains("Bearer {{token}}")); - assert_eq!(kept.secrets, ["token"]); - assert_eq!(kept.unresolved, ["tenant"]); - assert_eq!(kept.language, Language::Sh); - - let clear = generated(options(true, true)); - assert!(clear.code.contains("Bearer t0k3n")); - assert!(clear.secrets.is_empty()); + fn the_url_is_written_as_it_is_sent() { + let bare = RequestDocument { + url: " api.shop.test/a?x=1 ".to_string(), + auth: RequestAuth::ApiKey { + name: " api key ".to_string(), + value: "k&1".to_string(), + place: KeyPlace::Query, + }, + ..RequestDocument::default() + }; + let variable = RequestDocument { url: "{{base}}/a".to_string(), ..RequestDocument::default() }; + let unnamed_key = RequestDocument { + url: "https://shop.test/".to_string(), + auth: RequestAuth::ApiKey { + name: " ".to_string(), + value: "k".to_string(), + place: KeyPlace::Query, + }, + ..RequestDocument::default() + }; - let typed = generated(options(false, false)); - assert!(typed.code.contains("'{{baseUrl}}/me"), "{}", typed.code); - assert!(!typed.code.contains("://{{"), "{}", typed.code); + assert_eq!(http(&bare).url, "http://api.shop.test/a?x=1&api+key=k%261"); + assert_eq!(http(&variable).url, "{{base}}/a"); + assert_eq!(http(&unnamed_key).url, "https://shop.test/"); } + /// A Basic auth apart, each target writing it its own way, and not as a header; the + /// application's own headers left out — the program names itself. #[test] - fn the_application_names_itself_and_a_basic_auth_is_written_apart() { + fn a_basic_auth_is_handed_apart_and_the_application_s_headers_left_out() { let document = RequestDocument { - url: "api.exemple.fr/x".to_string(), - auth: RequestAuth::Basic { - username: "ada".to_string(), - password: "pw".to_string(), - }, + url: "https://shop.test/".to_string(), + headers: vec![row("X-Trace", "1")], + auth: RequestAuth::Basic { username: "ada".to_string(), password: "pw".to_string() }, ..RequestDocument::default() }; - let request = request_of( - RequestKind::Http, - HttpMethod::Get, - &document, - &inherit(&[]), - false, - ); - assert_eq!(request.url, "http://api.exemple.fr/x"); + + let request = http(&document); + assert_eq!(request.basic, Some(("ada".to_string(), "pw".to_string()))); - assert!(request.headers.is_empty(), "{:?}", request.headers); + assert_eq!(request.headers, [("X-Trace".to_string(), "1".to_string())]); + assert!(!request.follow_redirects); } + /// What leaves as the body: a text, the fields and parts switched on and named, a file by + /// its path; an empty one none. #[test] - fn a_key_in_the_query_and_a_graphql_get_go_in_the_url() { - let keyed = RequestDocument { - url: "https://x/a?b=1".to_string(), - auth: RequestAuth::ApiKey { - name: "api key".to_string(), - value: "k&1".to_string(), - place: KeyPlace::Query, - }, - ..RequestDocument::default() - }; - let request = request_of( - RequestKind::Http, - HttpMethod::Get, - &keyed, - &inherit(&[]), - false, + fn the_body_is_what_a_send_would_write() { + for (body, expected) in [ + (RequestBody::None, CodeBody::None), + (RequestBody::Json { text: String::new() }, CodeBody::None), + (RequestBody::Text { text: "t".to_string() }, CodeBody::Text("t".to_string())), + ( + RequestBody::Form { fields: vec![row(" a ", "1"), off("b"), row(" ", "x")] }, + CodeBody::Form(vec![("a".to_string(), "1".to_string())]), + ), + ( + RequestBody::Multipart { + parts: vec![ + part(" f ", "/a.png", true, true), + part("off", "x", false, false), + part(" ", "x", false, true), + ], + }, + CodeBody::Multipart(vec![CodePart { + name: "f".to_string(), + value: "/a.png".to_string(), + file: true, + }]), + ), + (RequestBody::Binary { path: " ".to_string() }, CodeBody::None), + ( + RequestBody::Binary { path: " /dump.bin ".to_string() }, + CodeBody::File("/dump.bin".to_string()), + ), + ] { + let document = RequestDocument { body, ..RequestDocument::default() }; + + assert_eq!(http(&document).body, expected); + } + } + + /// A GraphQL request is a `POST` of its JSON body, or a `GET` carrying its parts in the + /// query, whatever method the document holds. + #[test] + fn a_graphql_request_is_written_as_it_is_sent() { + let mut document = + RequestDocument { url: "https://shop.test/graphql".to_string(), ..RequestDocument::default() }; + document.graphql.query = "{ me }".to_string(); + document.graphql.variables = "{\"a\":1}".to_string(); + document.graphql.operation_name = Some("Me".to_string()); + + let posted = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); + document.graphql.as_get = true; + let got = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); + document.graphql.operation_name = Some(String::new()); + document.graphql.variables = "[not an object]".to_string(); + let bare = request_of(RequestKind::Graphql, HttpMethod::Delete, &document, &inherit(&[]), true); + + assert_eq!(posted.method, HttpMethod::Post); + assert_eq!( + posted.body, + CodeBody::Text(r#"{"query":"{ me }","variables":{"a":1},"operationName":"Me"}"#.to_string()) ); - assert_eq!(request.url, "https://x/a?b=1&api+key=k%261"); + assert!(posted.follow_redirects); + assert_eq!((got.method, &got.body), (HttpMethod::Get, &CodeBody::None)); + assert_eq!( + got.url, + "https://shop.test/graphql?query=%7B+me+%7D&variables=%7B%22a%22%3A1%7D&operationName=Me" + ); + assert_eq!(bare.url, "https://shop.test/graphql?query=%7B+me+%7D"); + } - let mut graphql = RequestDocument { - url: "https://x/graphql".to_string(), - ..RequestDocument::default() + /// The type the headers set, case aside. + #[test] + fn the_content_type_is_read_from_the_headers() { + let request = CodeRequest { + headers: vec![("content-TYPE".to_string(), "text/csv".to_string())], + ..http(&RequestDocument::default()) }; - graphql.graphql.query = "{ me { id } }".to_string(); - graphql.graphql.as_get = true; - let request = request_of( - RequestKind::Graphql, - HttpMethod::Post, - &graphql, - &inherit(&[]), - false, + + assert_eq!(request.content_type(), Some("text/csv")); + assert_eq!(http(&RequestDocument::default()).content_type(), None); + } + + fn document_using(names: &str) -> RequestDocument { + RequestDocument { url: format!("https://shop.test/{names}"), ..RequestDocument::default() } + } + + /// A secret stays its `{{name}}` and is named, unless asked for in clear; a name nothing + /// sets is written as typed and named; off, nothing is resolved. + #[test] + fn variables_are_resolved_secrets_aside_unless_asked_for() { + let layers = [layer(vec![ + variable("host", "h", VariableKind::Text), + variable("token", "t0k3n", VariableKind::Secret), + ])]; + let document = document_using("{{host}}/{{token}}/{{nowhere}}"); + let resolve = CodeOptions { resolve_variables: true, ..CodeOptions::default() }; + let in_clear = CodeOptions { include_secrets: true, ..resolve }; + let generate_with = |options| { + generate( + CodeTarget::Curl, + options, + RequestKind::Http, + HttpMethod::Get, + &document, + &inherit(&[]), + &layers, + ) + }; + + let masked = generate_with(resolve); + let clear = generate_with(in_clear); + let typed = generate_with(CodeOptions::default()); + + assert!(masked.code.contains("https://shop.test/h/{{token}}/{{nowhere}}"), "{}", masked.code); + assert_eq!( + (masked.secrets, masked.unresolved), + (vec!["token".to_string()], vec!["nowhere".to_string()]) ); - assert_eq!(request.method, HttpMethod::Get); - assert_eq!(request.url, "https://x/graphql?query=%7B+me+%7B+id+%7D+%7D"); + assert!(clear.code.contains("https://shop.test/h/t0k3n/{{nowhere}}"), "{}", clear.code); + assert!(clear.secrets.is_empty()); + assert!(typed.code.contains("https://shop.test/{{host}}/{{token}}/{{nowhere}}"), "{}", typed.code); + assert_eq!(masked.language, Language::Sh); } + /// Wget, Java's client and `URLSession` build no multipart body: the interface says it. #[test] - fn wget_says_it_sends_no_multipart_form() { + fn a_target_that_cannot_send_a_multipart_body_says_so() { let document = RequestDocument { - url: "https://x".to_string(), - body: RequestBody::Multipart { - parts: vec![crate::http::model::FormPart { - key: "a".to_string(), - value: "1".to_string(), - ..Default::default() - }], - }, - ..RequestDocument::default() + body: RequestBody::Multipart { parts: vec![part("a", "1", false, true)] }, + ..document_using("") }; - let code = generate( + let notice = |target| { + generate( + target, + CodeOptions::default(), + RequestKind::Http, + HttpMethod::Post, + &document, + &inherit(&[]), + &[], + ) + .notice + }; + + for target in CodeTarget::ALL { + let expected = (!target.sends_multipart()).then_some(CodeNotice::MultipartUnsupported); + + assert_eq!(notice(target), expected, "{target:?}"); + } + let text = generate( CodeTarget::Wget, - options(true, false), + CodeOptions::default(), RequestKind::Http, - HttpMethod::Post, - &document, + HttpMethod::Get, + &document_using(""), &inherit(&[]), &[], ); - assert_eq!(code.notice, Some(CodeNotice::MultipartUnsupported)); + assert_eq!(text.notice, None); } + /// Every target writes something for the same request, each in its own language. #[test] - fn a_shell_quote_survives_a_quote_and_lines_end_on_a_backslash() { - assert_eq!(shell_quoted("O'Brien"), r"'O'\''Brien'"); - assert_eq!( - shell_lines("curl", &["-a".to_string(), "-b".to_string()], true), - "curl \\\n -a \\\n -b" - ); - assert_eq!( - shell_lines("curl", &["-a".to_string(), "-b".to_string()], false), - "curl -a -b" - ); + fn every_target_writes_the_request() { + let document = document_using("orders"); + + for target in CodeTarget::ALL { + let code = generate( + target, + CodeOptions::default(), + RequestKind::Http, + HttpMethod::Get, + &document, + &inherit(&[]), + &[], + ); + + assert!(code.code.contains("shop.test/orders"), "{target:?}: {}", code.code); + assert_eq!(code.language, target.language()); + } + } + + /// A quote inside closes, escapes and reopens. + #[test] + fn a_shell_argument_is_quoted_whatever_it_holds() { + assert_eq!(shell_quoted("O'Brien $HOME"), r"'O'\''Brien $HOME'"); + assert_eq!(shell_quoted(""), "''"); + } + + /// On one line, or one argument a line under the first, each but the last ending on `\`. + #[test] + fn arguments_are_written_on_one_line_or_one_a_line() { + let arguments = ["-X POST".to_string(), "'https://shop.test/'".to_string()]; + + assert_eq!(shell_lines("curl", &arguments, false), "curl -X POST 'https://shop.test/'"); + assert_eq!(shell_lines("curl", &arguments, true), "curl \\\n -X POST \\\n 'https://shop.test/'"); + assert_eq!(shell_lines("curl", &[], true), "curl"); + } + + #[test] + fn a_form_is_encoded_as_it_is_sent() { + let fields = [("a b".to_string(), "x&y=z".to_string()), ("c".to_string(), String::new())]; + + assert_eq!(form_encoded(&fields), "a+b=x%26y%3Dz&c="); } } diff --git a/crates/engine/src/http/codegen/angular.rs b/crates/engine/src/http/codegen/angular.rs index f38533ab2..d9c04125d 100644 --- a/crates/engine/src/http/codegen/angular.rs +++ b/crates/engine/src/http/codegen/angular.rs @@ -39,14 +39,9 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); - Some(format!( - "new URLSearchParams({}).toString()", - object(&entries, " ") - )) + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); + Some(format!("new URLSearchParams({}).toString()", object(&entries, " "))) } CodeBody::Multipart(parts) => { for part in parts.iter().filter(|part| part.file) { @@ -54,11 +49,7 @@ pub fn write(request: &CodeRequest) -> String { } lines.push("const form = new FormData();".to_string()); for part in parts { - let value = if part.file { - identifier(&part.name) - } else { - string(&part.value) - }; + let value = if part.file { identifier(&part.name) } else { string(&part.value) }; lines.push(format!("form.append({}, {value});", string(&part.name))); } Some("form".to_string()) @@ -73,10 +64,7 @@ pub fn write(request: &CodeRequest) -> String { } let mut options = Vec::new(); if !headers.is_empty() { - options.push(( - "headers".to_string(), - format!("new HttpHeaders({})", object(&headers, " ")), - )); + options.push(("headers".to_string(), format!("new HttpHeaders({})", object(&headers, " ")))); } if let Some(body) = body { options.push(("body".to_string(), body)); diff --git a/crates/engine/src/http/codegen/axios.rs b/crates/engine/src/http/codegen/axios.rs index ddf05c2dc..3ae8ad991 100644 --- a/crates/engine/src/http/codegen/axios.rs +++ b/crates/engine/src/http/codegen/axios.rs @@ -28,10 +28,7 @@ pub fn write(request: &CodeRequest) -> String { options.push(( "auth".to_string(), object( - &[ - ("username".to_string(), string(user)), - ("password".to_string(), string(password)), - ], + &[("username".to_string(), string(user)), ("password".to_string(), string(password))], " ", ), )); @@ -44,10 +41,7 @@ pub fn write(request: &CodeRequest) -> String { } // An answer of 4xx or 5xx is an answer to print, not an exception to catch. options.push(("validateStatus".to_string(), "() => true".to_string())); - lines.push(format!( - "const response = await axios.request({});", - object(&options, "") - )); + lines.push(format!("const response = await axios.request({});", object(&options, ""))); lines.push("console.log(response.status, response.data);".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/csharp.rs b/crates/engine/src/http/codegen/csharp.rs index 74a8504cf..186302af4 100644 --- a/crates/engine/src/http/codegen/csharp.rs +++ b/crates/engine/src/http/codegen/csharp.rs @@ -40,11 +40,7 @@ pub fn write(request: &CodeRequest) -> String { .iter() .filter(|(name, _)| !name.eq_ignore_ascii_case("content-type")) { - lines.push(format!( - "request.Headers.TryAddWithoutValidation({}, {});", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Headers.TryAddWithoutValidation({}, {});", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -61,8 +57,7 @@ pub fn write(request: &CodeRequest) -> String { )), CodeBody::Form(fields) => { lines.push( - "request.Content = new FormUrlEncodedContent(new Dictionary" - .to_string(), + "request.Content = new FormUrlEncodedContent(new Dictionary".to_string(), ); lines.push("{".to_string()); for (name, value) in fields { @@ -91,10 +86,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push("request.Content = form;".to_string()); } CodeBody::File(path) => { - lines.push(format!( - "request.Content = new StreamContent(File.OpenRead({}));", - quoted(path) - )); + lines.push(format!("request.Content = new StreamContent(File.OpenRead({}));", quoted(path))); if let Some(content_type) = content_type { lines.push(format!( "request.Content.Headers.ContentType = new MediaTypeHeaderValue({});", diff --git a/crates/engine/src/http/codegen/curl.rs b/crates/engine/src/http/codegen/curl.rs index 71c3454eb..d2635f351 100644 --- a/crates/engine/src/http/codegen/curl.rs +++ b/crates/engine/src/http/codegen/curl.rs @@ -18,26 +18,17 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--location".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--user {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--user {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("--data-raw {}", shell_quoted(text))), CodeBody::Form(fields) => { for (name, value) in fields { - arguments.push(format!( - "--data-urlencode {}", - shell_quoted(&format!("{name}={value}")) - )); + arguments.push(format!("--data-urlencode {}", shell_quoted(&format!("{name}={value}")))); } } CodeBody::Multipart(parts) => { @@ -52,10 +43,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } } CodeBody::File(path) => { - arguments.push(format!( - "--data-binary {}", - shell_quoted(&format!("@{path}")) - )); + arguments.push(format!("--data-binary {}", shell_quoted(&format!("@{path}")))); } } shell_lines(&first, &arguments, multiline) @@ -78,10 +66,7 @@ mod tests { follow_redirects: false, }; - let text = write( - &request(CodeBody::Text("@/etc/hostname".to_string())), - false, - ); + let text = write(&request(CodeBody::Text("@/etc/hostname".to_string())), false); let form = write( &request(CodeBody::Multipart(vec![super::super::CodePart { name: "a".to_string(), diff --git a/crates/engine/src/http/codegen/dart.rs b/crates/engine/src/http/codegen/dart.rs index 59afb2cda..2affd661c 100644 --- a/crates/engine/src/http/codegen/dart.rs +++ b/crates/engine/src/http/codegen/dart.rs @@ -27,19 +27,12 @@ pub fn write(request: &CodeRequest) -> String { lines.push("Future main() async {".to_string()); lines.push(format!( " final request = http.{}({}, Uri.parse({}));", - if multipart { - "MultipartRequest" - } else { - "Request" - }, + if multipart { "MultipartRequest" } else { "Request" }, quoted(request.method.as_str()), quoted(&request.url) )); if !request.headers.is_empty() { - lines.push(format!( - " request.headers.addAll({});", - map(&request.headers) - )); + lines.push(format!(" request.headers.addAll({});", map(&request.headers))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -68,18 +61,12 @@ pub fn write(request: &CodeRequest) -> String { } } } - CodeBody::File(path) => lines.push(format!( - " request.bodyBytes = await File({}).readAsBytes();", - quoted(path) - )), + CodeBody::File(path) => { + lines.push(format!(" request.bodyBytes = await File({}).readAsBytes();", quoted(path))); + } } - lines.push(format!( - " request.followRedirects = {};", - request.follow_redirects - )); - lines.push( - " final response = await http.Response.fromStream(await request.send());".to_string(), - ); + lines.push(format!(" request.followRedirects = {};", request.follow_redirects)); + lines.push(" final response = await http.Response.fromStream(await request.send());".to_string()); lines.push(" print('${response.statusCode} ${response.body}');".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/fetch.rs b/crates/engine/src/http/codegen/fetch.rs index 9fb4e9f09..b3293e71d 100644 --- a/crates/engine/src/http/codegen/fetch.rs +++ b/crates/engine/src/http/codegen/fetch.rs @@ -23,11 +23,7 @@ pub fn write(request: &CodeRequest) -> String { if !request.follow_redirects { options.push(("redirect".to_string(), string("manual"))); } - lines.push(format!( - "const response = await fetch({}, {});", - string(&request.url), - object(&options, "") - )); + lines.push(format!("const response = await fetch({}, {});", string(&request.url), object(&options, ""))); lines.push("console.log(response.status, await response.text());".to_string()); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/go.rs b/crates/engine/src/http/codegen/go.rs index 806b818aa..87a5aaf92 100644 --- a/crates/engine/src/http/codegen/go.rs +++ b/crates/engine/src/http/codegen/go.rs @@ -46,9 +46,8 @@ pub fn write(request: &CodeRequest) -> String { } } body_lines.push("writer.Close()".to_string()); - after_request.push( - "request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string(), - ); + after_request + .push("request.Header.Set(\"Content-Type\", writer.FormDataContentType())".to_string()); "&form".to_string() } CodeBody::File(path) => { @@ -68,19 +67,11 @@ pub fn write(request: &CodeRequest) -> String { )); lines.push("if err != nil {\n\t\tpanic(err)\n\t}".to_string()); for (name, value) in &request.headers { - lines.push(format!( - "request.Header.Set({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!("request.Header.Set({}, {})", quoted(name), quoted(value))); } lines.extend(after_request); if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.SetBasicAuth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.SetBasicAuth({}, {})", quoted(user), quoted(password))); } if request.follow_redirects { lines.push("client := &http.Client{}".to_string()); @@ -96,16 +87,9 @@ pub fn write(request: &CodeRequest) -> String { lines.push("answer, _ := io.ReadAll(response.Body)".to_string()); lines.push("fmt.Println(response.StatusCode, string(answer))".to_string()); - let imports: Vec = imports - .into_iter() - .map(|import| format!("\t{}", quoted(import))) - .collect(); + let imports: Vec = imports.into_iter().map(|import| format!("\t{}", quoted(import))).collect(); let body: Vec = lines.into_iter().map(|line| format!("\t{line}")).collect(); - format!( - "package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", - imports.join("\n"), - body.join("\n") - ) + format!("package main\n\nimport (\n{}\n)\n\nfunc main() {{\n{}\n}}", imports.join("\n"), body.join("\n")) } #[cfg(test)] diff --git a/crates/engine/src/http/codegen/guzzle.rs b/crates/engine/src/http/codegen/guzzle.rs index 7c8cd1b7e..49b9d590e 100644 --- a/crates/engine/src/http/codegen/guzzle.rs +++ b/crates/engine/src/http/codegen/guzzle.rs @@ -25,19 +25,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(("headers".to_string(), array(&headers, " "))); } if let Some((user, password)) = &request.basic { - options.push(( - "auth".to_string(), - format!("[{}, {}]", quoted(user), quoted(password)), - )); + options.push(("auth".to_string(), format!("[{}, {}]", quoted(user), quoted(password)))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(("body".to_string(), quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(("form_params".to_string(), array(&fields, " "))); } CodeBody::Multipart(parts) => { @@ -49,25 +44,16 @@ pub fn write(request: &CodeRequest) -> String { } else { quoted(&part.value) }; - format!( - " ['name' => {}, 'contents' => {contents}],", - quoted(&part.name) - ) + format!(" ['name' => {}, 'contents' => {contents}],", quoted(&part.name)) }) .collect(); - options.push(( - "multipart".to_string(), - format!("[\n{}\n ]", lines.join("\n")), - )); + options.push(("multipart".to_string(), format!("[\n{}\n ]", lines.join("\n")))); } CodeBody::File(path) => { options.push(("body".to_string(), format!("fopen({}, 'r')", quoted(path)))); } } - options.push(( - "allow_redirects".to_string(), - request.follow_redirects.to_string(), - )); + options.push(("allow_redirects".to_string(), request.follow_redirects.to_string())); options.push(("http_errors".to_string(), "false".to_string())); format!( "request({}, {}, {});\necho $response->getStatusCode(), ' ', $response->getBody();", diff --git a/crates/engine/src/http/codegen/httpie.rs b/crates/engine/src/http/codegen/httpie.rs index ed1a49fa4..173d37c38 100644 --- a/crates/engine/src/http/codegen/httpie.rs +++ b/crates/engine/src/http/codegen/httpie.rs @@ -10,10 +10,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--follow".to_string()); } if let Some((user, password)) = &request.basic { - arguments.push(format!( - "--auth {}", - shell_quoted(&format!("{user}:{password}")) - )); + arguments.push(format!("--auth {}", shell_quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::Form(_) => arguments.push("--form".to_string()), @@ -33,20 +30,13 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { CodeBody::Multipart(parts) => { for part in parts { let separator = if part.file { "@" } else { "=" }; - arguments.push(shell_quoted(&format!( - "{}{separator}{}", - part.name, part.value - ))); + arguments.push(shell_quoted(&format!("{}{separator}{}", part.name, part.value))); } } CodeBody::File(path) => arguments.push(format!("< {}", shell_quoted(path))), CodeBody::None | CodeBody::Text(_) => {} } - let first = format!( - "http {} {}", - request.method.as_str(), - shell_quoted(&request.url) - ); + let first = format!("http {} {}", request.method.as_str(), shell_quoted(&request.url)); shell_lines(&first, &arguments, multiline) } diff --git a/crates/engine/src/http/codegen/java.rs b/crates/engine/src/http/codegen/java.rs index 371f69dc9..1c24edb91 100644 --- a/crates/engine/src/http/codegen/java.rs +++ b/crates/engine/src/http/codegen/java.rs @@ -14,20 +14,14 @@ pub fn write(request: &CodeRequest) -> String { "java.net.http.HttpResponse", ]; let publisher = match &request.body { - CodeBody::None | CodeBody::Multipart(_) => { - "HttpRequest.BodyPublishers.noBody()".to_string() - } + CodeBody::None | CodeBody::Multipart(_) => "HttpRequest.BodyPublishers.noBody()".to_string(), CodeBody::Text(text) => format!("HttpRequest.BodyPublishers.ofString({})", quoted(text)), - CodeBody::Form(fields) => format!( - "HttpRequest.BodyPublishers.ofString({})", - quoted(&form_encoded(fields)) - ), + CodeBody::Form(fields) => { + format!("HttpRequest.BodyPublishers.ofString({})", quoted(&form_encoded(fields))) + } CodeBody::File(path) => { imports.push("java.nio.file.Path"); - format!( - "HttpRequest.BodyPublishers.ofFile(Path.of({}))", - quoted(path) - ) + format!("HttpRequest.BodyPublishers.ofFile(Path.of({}))", quoted(path)) } }; if request.basic.is_some() { @@ -35,34 +29,20 @@ pub fn write(request: &CodeRequest) -> String { } imports.sort_unstable(); - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import};")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import};")).collect(); lines.push(String::new()); lines.push("public class Main {".to_string()); lines.push(" public static void main(String[] args) throws Exception {".to_string()); lines.push(" HttpClient client = HttpClient.newBuilder()".to_string()); lines.push(format!( " .followRedirects(HttpClient.Redirect.{})", - if request.follow_redirects { - "NORMAL" - } else { - "NEVER" - } + if request.follow_redirects { "NORMAL" } else { "NEVER" } )); lines.push(" .build();".to_string()); lines.push(" HttpRequest request = HttpRequest.newBuilder()".to_string()); - lines.push(format!( - " .uri(URI.create({}))", - quoted(&request.url) - )); + lines.push(format!(" .uri(URI.create({}))", quoted(&request.url))); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -70,18 +50,13 @@ pub fn write(request: &CodeRequest) -> String { quoted(&format!("{user}:{password}")) )); } - lines.push(format!( - " .method({}, {publisher})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {publisher})", quoted(request.method.as_str()))); lines.push(" .build();".to_string()); lines.push( " HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());" .to_string(), ); - lines.push( - " System.out.println(response.statusCode() + \" \" + response.body());".to_string(), - ); + lines.push(" System.out.println(response.statusCode() + \" \" + response.body());".to_string()); lines.push(" }".to_string()); lines.push("}".to_string()); lines.join("\n") diff --git a/crates/engine/src/http/codegen/javascript.rs b/crates/engine/src/http/codegen/javascript.rs index ad1f35633..218f39f2a 100644 --- a/crates/engine/src/http/codegen/javascript.rs +++ b/crates/engine/src/http/codegen/javascript.rs @@ -8,10 +8,7 @@ use super::{CodeBody, CodeRequest}; #[must_use] pub fn string(text: &str) -> String { if text.contains('\n') { - let escaped = text - .replace('\\', "\\\\") - .replace('`', "\\`") - .replace("${", "\\${"); + let escaped = text.replace('\\', "\\\\").replace('`', "\\`").replace("${", "\\${"); return format!("`{escaped}`"); } let escaped = text @@ -30,11 +27,7 @@ pub fn key(name: &str) -> String { .next() .is_some_and(|first| first.is_ascii_alphabetic() || first == '_' || first == '$') && chars.all(|next| next.is_ascii_alphanumeric() || next == '_' || next == '$'); - if identifier { - name.to_string() - } else { - string(name) - } + if identifier { name.to_string() } else { string(name) } } /// `{ a: 'b', 'c-d': e }` laid out a key a line at `indent`, the values already written. @@ -62,10 +55,7 @@ pub fn headers(request: &CodeRequest) -> Vec<(String, String)> { if let Some((user, password)) = &request.basic { headers.push(( "Authorization".to_string(), - format!( - "`Basic ${{btoa({})}}`", - string(&format!("{user}:{password}")) - ), + format!("`Basic ${{btoa({})}}`", string(&format!("{user}:{password}"))), )); } headers @@ -104,11 +94,7 @@ pub fn form_data(body: &CodeBody) -> Vec { string(&file_name(&part.value)) )); } else { - lines.push(format!( - "form.append({}, {});", - string(&part.name), - string(&part.value) - )); + lines.push(format!("form.append({}, {});", string(&part.name), string(&part.value))); } } lines @@ -121,10 +107,8 @@ pub fn body(body: &CodeBody, indent: &str) -> Option { CodeBody::None => None, CodeBody::Text(text) => Some(string(text)), CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), string(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), string(value))).collect(); Some(format!("new URLSearchParams({})", object(&entries, indent))) } CodeBody::Multipart(_) => Some("form".to_string()), @@ -140,10 +124,7 @@ mod tests { fn a_string_is_quoted_for_a_line_and_a_template_for_several() { assert_eq!(string("O'Brien"), r"'O\'Brien'"); assert_eq!(string("a\\b"), r"'a\\b'"); - assert_eq!( - string("{\n \"a\": `${x}`\n}"), - "`{\n \"a\": \\`\\${x}\\`\n}`" - ); + assert_eq!(string("{\n \"a\": `${x}`\n}"), "`{\n \"a\": \\`\\${x}\\`\n}`"); } #[test] diff --git a/crates/engine/src/http/codegen/okhttp.rs b/crates/engine/src/http/codegen/okhttp.rs index 15f9757ee..df862b772 100644 --- a/crates/engine/src/http/codegen/okhttp.rs +++ b/crates/engine/src/http/codegen/okhttp.rs @@ -8,16 +8,10 @@ use super::{CodeBody, CodeRequest}; use crate::http::model::HttpMethod; /// The body as `.method` takes it, what builds it written into `prelude`. -fn body_of( - request: &CodeRequest, - imports: &mut BTreeSet<&'static str>, - prelude: &mut Vec, -) -> String { +fn body_of(request: &CodeRequest, imports: &mut BTreeSet<&'static str>, prelude: &mut Vec) -> String { let content_type = request.content_type().unwrap_or("application/octet-stream"); match &request.body { - CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => { - "null".to_string() - } + CodeBody::None if matches!(request.method, HttpMethod::Get | HttpMethod::Head) => "null".to_string(), CodeBody::None => { imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); "ByteArray(0).toRequestBody()".to_string() @@ -25,11 +19,7 @@ fn body_of( CodeBody::Text(text) => { imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.toRequestBody"); - format!( - "{}.toRequestBody({}.toMediaType())", - quoted(text), - quoted(content_type) - ) + format!("{}.toRequestBody({}.toMediaType())", quoted(text), quoted(content_type)) } CodeBody::Form(fields) => { imports.insert("okhttp3.FormBody"); @@ -69,36 +59,24 @@ fn body_of( imports.insert("java.io.File"); imports.insert("okhttp3.MediaType.Companion.toMediaType"); imports.insert("okhttp3.RequestBody.Companion.asRequestBody"); - format!( - "File({}).asRequestBody({}.toMediaType())", - quoted(path), - quoted(content_type) - ) + format!("File({}).asRequestBody({}.toMediaType())", quoted(path), quoted(content_type)) } } } #[must_use] pub fn write(request: &CodeRequest) -> String { - let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"] - .into_iter() - .collect(); + let mut imports: BTreeSet<&str> = ["okhttp3.OkHttpClient", "okhttp3.Request"].into_iter().collect(); let mut prelude = Vec::new(); let body = body_of(request, &mut imports, &mut prelude); if request.basic.is_some() { imports.insert("okhttp3.Credentials"); } - let mut lines: Vec = imports - .iter() - .map(|import| format!("import {import}")) - .collect(); + let mut lines: Vec = imports.iter().map(|import| format!("import {import}")).collect(); lines.push(String::new()); lines.push("val client = OkHttpClient.Builder()".to_string()); - lines.push(format!( - " .followRedirects({})", - request.follow_redirects - )); + lines.push(format!(" .followRedirects({})", request.follow_redirects)); lines.push(" .build()".to_string()); lines.extend(prelude); lines.push("val request = Request.Builder()".to_string()); @@ -118,10 +96,7 @@ pub fn write(request: &CodeRequest) -> String { quoted(password) )); } - lines.push(format!( - " .method({}, {body})", - quoted(request.method.as_str()) - )); + lines.push(format!(" .method({}, {body})", quoted(request.method.as_str()))); lines.push(" .build()".to_string()); lines.push("client.newCall(request).execute().use { response ->".to_string()); lines.push(" println(\"${response.code} ${response.body?.string()}\")".to_string()); diff --git a/crates/engine/src/http/codegen/powershell.rs b/crates/engine/src/http/codegen/powershell.rs index 588d25f43..706680be0 100644 --- a/crates/engine/src/http/codegen/powershell.rs +++ b/crates/engine/src/http/codegen/powershell.rs @@ -72,10 +72,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { } let mut lines = Vec::new(); - let mut parameters = vec![ - format!("-Uri {}", quoted(&request.url)), - format!("-Method {}", method(request.method)), - ]; + let mut parameters = + vec![format!("-Uri {}", quoted(&request.url)), format!("-Method {}", method(request.method))]; if !headers.is_empty() { lines.push(format!("$headers = {}", hashtable(&headers, multiline))); parameters.push("-Headers $headers".to_string()); @@ -92,10 +90,8 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { parameters.push("-Body $body".to_string()); } CodeBody::Form(fields) => { - let entries: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let entries: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); lines.push(format!("$body = {}", hashtable(&entries, multiline))); parameters.push("-Body $body".to_string()); } @@ -126,13 +122,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { let last = call.len() - 1; call.iter() .enumerate() - .map(|(at, line)| { - if at == last { - line.clone() - } else { - format!("{line} `") - } - }) + .map(|(at, line)| if at == last { line.clone() } else { format!("{line} `") }) .collect::>() .join("\n") } else { diff --git a/crates/engine/src/http/codegen/python.rs b/crates/engine/src/http/codegen/python.rs index 34ff83da2..48bcd2a7d 100644 --- a/crates/engine/src/http/codegen/python.rs +++ b/crates/engine/src/http/codegen/python.rs @@ -44,10 +44,8 @@ fn write(request: &CodeRequest, library: Library) -> String { CodeBody::None => {} CodeBody::Text(text) => arguments.push(format!("{raw}={}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); arguments.push(format!("data={}", dict(&fields))); } CodeBody::Multipart(parts) => { @@ -59,12 +57,7 @@ fn write(request: &CodeRequest, library: Library) -> String { let files: Vec<(String, String)> = parts .iter() .filter(|part| part.file) - .map(|part| { - ( - part.name.clone(), - format!("open({}, \"rb\")", quoted(&part.value)), - ) - }) + .map(|part| (part.name.clone(), format!("open({}, \"rb\")", quoted(&part.value)))) .collect(); if !texts.is_empty() { arguments.push(format!("data={}", dict(&texts))); @@ -77,19 +70,12 @@ fn write(request: &CodeRequest, library: Library) -> String { arguments.push(format!("{raw}=open({}, \"rb\")", quoted(path))); } } - let follow = if request.follow_redirects { - "True" - } else { - "False" - }; + let follow = if request.follow_redirects { "True" } else { "False" }; arguments.push(match library { Library::Requests => format!("allow_redirects={follow}"), Library::Httpx => format!("follow_redirects={follow}"), }); - let arguments: Vec = arguments - .into_iter() - .map(|argument| format!(" {argument},")) - .collect(); + let arguments: Vec = arguments.into_iter().map(|argument| format!(" {argument},")).collect(); format!( "import {name}\n\nresponse = {name}.request(\n{}\n)\nprint(response.status_code, response.text)", arguments.join("\n") diff --git a/crates/engine/src/http/codegen/req.rs b/crates/engine/src/http/codegen/req.rs index 330ee944d..c263636b8 100644 --- a/crates/engine/src/http/codegen/req.rs +++ b/crates/engine/src/http/codegen/req.rs @@ -28,19 +28,14 @@ pub fn write(request: &CodeRequest) -> String { options.push(format!("headers: {}", pairs(&headers))); } if let Some((user, password)) = &request.basic { - options.push(format!( - "auth: {{:basic, {}}}", - quoted(&format!("{user}:{password}")) - )); + options.push(format!("auth: {{:basic, {}}}", quoted(&format!("{user}:{password}")))); } match &request.body { CodeBody::None => {} CodeBody::Text(text) => options.push(format!("body: {}", quoted(text))), CodeBody::Form(fields) => { - let fields: Vec<(String, String)> = fields - .iter() - .map(|(name, value)| (name.clone(), quoted(value))) - .collect(); + let fields: Vec<(String, String)> = + fields.iter().map(|(name, value)| (name.clone(), quoted(value))).collect(); options.push(format!("form: {}", pairs(&fields))); } CodeBody::Multipart(parts) => { @@ -61,10 +56,7 @@ pub fn write(request: &CodeRequest) -> String { } options.push(format!("redirect: {}", request.follow_redirects)); options.push("retry: false".to_string()); - let options: Vec = options - .into_iter() - .map(|option| format!(" {option}")) - .collect(); + let options: Vec = options.into_iter().map(|option| format!(" {option}")).collect(); format!( "response =\n Req.request!(\n{}\n )\n\nIO.puts(\"#{{response.status}} #{{inspect(response.body)}}\")", options.join(",\n") diff --git a/crates/engine/src/http/codegen/reqwest.rs b/crates/engine/src/http/codegen/reqwest.rs index cfd2e7fcb..32720010f 100644 --- a/crates/engine/src/http/codegen/reqwest.rs +++ b/crates/engine/src/http/codegen/reqwest.rs @@ -40,17 +40,9 @@ pub fn write(request: &CodeRequest) -> String { for (at, part) in parts.iter().enumerate() { let end = if at == last { ";" } else { "" }; if part.file { - lines.push(format!( - " .file({}, {})?{end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .file({}, {})?{end}", quoted(&part.name), quoted(&part.value))); } else { - lines.push(format!( - " .text({}, {}){end}", - quoted(&part.name), - quoted(&part.value) - )); + lines.push(format!(" .text({}, {}){end}", quoted(&part.name), quoted(&part.value))); } } } @@ -61,18 +53,10 @@ pub fn write(request: &CodeRequest) -> String { quoted(&request.url) )); for (name, value) in &request.headers { - lines.push(format!( - " .header({}, {})", - quoted(name), - quoted(value) - )); + lines.push(format!(" .header({}, {})", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - " .basic_auth({}, Some({}))", - quoted(user), - quoted(password) - )); + lines.push(format!(" .basic_auth({}, Some({}))", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -86,10 +70,7 @@ pub fn write(request: &CodeRequest) -> String { } CodeBody::Multipart(_) => lines.push(" .multipart(form)".to_string()), CodeBody::File(path) => { - lines.push(format!( - " .body(std::fs::File::open({})?)", - quoted(path) - )); + lines.push(format!(" .body(std::fs::File::open({})?)", quoted(path))); } } lines.push(" .send()?;".to_string()); diff --git a/crates/engine/src/http/codegen/ruby.rs b/crates/engine/src/http/codegen/ruby.rs index 0fa2cf3fb..7e6ad1ad0 100644 --- a/crates/engine/src/http/codegen/ruby.rs +++ b/crates/engine/src/http/codegen/ruby.rs @@ -30,11 +30,7 @@ pub fn write(request: &CodeRequest) -> String { lines.push(format!("request[{}] = {}", quoted(name), quoted(value))); } if let Some((user, password)) = &request.basic { - lines.push(format!( - "request.basic_auth({}, {})", - quoted(user), - quoted(password) - )); + lines.push(format!("request.basic_auth({}, {})", quoted(user), quoted(password))); } match &request.body { CodeBody::None => {} @@ -58,10 +54,7 @@ pub fn write(request: &CodeRequest) -> String { format!("[{}, {value}]", quoted(&part.name)) }) .collect(); - lines.push(format!( - "request.set_form([{}], 'multipart/form-data')", - pairs.join(", ") - )); + lines.push(format!("request.set_form([{}], 'multipart/form-data')", pairs.join(", "))); } CodeBody::File(path) => { lines.push(format!("request.body = File.binread({})", quoted(path))); diff --git a/crates/engine/src/http/codegen/source.rs b/crates/engine/src/http/codegen/source.rs index 8fbde7652..2e09913ca 100644 --- a/crates/engine/src/http/codegen/source.rs +++ b/crates/engine/src/http/codegen/source.rs @@ -43,13 +43,7 @@ pub fn single_quoted(text: &str) -> String { pub fn dart(text: &str) -> String { let inner = double_quoted(text); let inner = &inner[1..inner.len() - 1]; - format!( - "'{}'", - inner - .replace("\\\"", "\"") - .replace('\'', "\\'") - .replace('$', "\\$") - ) + format!("'{}'", inner.replace("\\\"", "\"").replace('\'', "\\'").replace('$', "\\$")) } /// The last part of a path: what a file part is sent as. diff --git a/crates/engine/src/http/codegen/swift.rs b/crates/engine/src/http/codegen/swift.rs index 897f45a36..4214a1168 100644 --- a/crates/engine/src/http/codegen/swift.rs +++ b/crates/engine/src/http/codegen/swift.rs @@ -10,18 +10,11 @@ pub fn write(request: &CodeRequest) -> String { let mut lines = vec![ "import Foundation".to_string(), String::new(), - format!( - "var request = URLRequest(url: URL(string: {})!)", - quoted(&request.url) - ), + format!("var request = URLRequest(url: URL(string: {})!)", quoted(&request.url)), format!("request.httpMethod = {}", quoted(request.method.as_str())), ]; for (name, value) in &request.headers { - lines.push(format!( - "request.setValue({}, forHTTPHeaderField: {})", - quoted(value), - quoted(name) - )); + lines.push(format!("request.setValue({}, forHTTPHeaderField: {})", quoted(value), quoted(name))); } if let Some((user, password)) = &request.basic { lines.push(format!( @@ -34,19 +27,15 @@ pub fn write(request: &CodeRequest) -> String { CodeBody::Text(text) => { lines.push(format!("request.httpBody = Data({}.utf8)", quoted(text))); } - CodeBody::Form(fields) => lines.push(format!( - "request.httpBody = Data({}.utf8)", - quoted(&form_encoded(fields)) - )), - CodeBody::File(path) => lines.push(format!( - "request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", - quoted(path) - )), + CodeBody::Form(fields) => { + lines.push(format!("request.httpBody = Data({}.utf8)", quoted(&form_encoded(fields)))); + } + CodeBody::File(path) => lines + .push(format!("request.httpBody = try Data(contentsOf: URL(fileURLWithPath: {}))", quoted(path))), } lines.push("let (data, response) = try await URLSession.shared.data(for: request)".to_string()); lines.push( - "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))" - .to_string(), + "print((response as! HTTPURLResponse).statusCode, String(decoding: data, as: UTF8.self))".to_string(), ); lines.join("\n") } diff --git a/crates/engine/src/http/codegen/wget.rs b/crates/engine/src/http/codegen/wget.rs index d924bae8c..50a0dec12 100644 --- a/crates/engine/src/http/codegen/wget.rs +++ b/crates/engine/src/http/codegen/wget.rs @@ -11,10 +11,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { arguments.push("--max-redirect 0".to_string()); } for (name, value) in &request.headers { - arguments.push(format!( - "--header {}", - shell_quoted(&format!("{name}: {value}")) - )); + arguments.push(format!("--header {}", shell_quoted(&format!("{name}: {value}")))); } if let Some((user, password)) = &request.basic { // Without it, wget sends its credentials only once a server has asked for them. @@ -25,10 +22,7 @@ pub fn write(request: &CodeRequest, multiline: bool) -> String { match &request.body { CodeBody::Text(text) => arguments.push(format!("--body-data {}", shell_quoted(text))), CodeBody::Form(fields) => { - arguments.push(format!( - "--body-data {}", - shell_quoted(&form_encoded(fields)) - )); + arguments.push(format!("--body-data {}", shell_quoted(&form_encoded(fields)))); } CodeBody::File(path) => arguments.push(format!("--body-file {}", shell_quoted(path))), CodeBody::None | CodeBody::Multipart(_) => {} diff --git a/crates/engine/src/http/collection_run.rs b/crates/engine/src/http/collection_run.rs index 37233a9ae..efa7ab81a 100644 --- a/crates/engine/src/http/collection_run.rs +++ b/crates/engine/src/http/collection_run.rs @@ -28,15 +28,7 @@ pub(super) async fn run_step( step: RunStep<'_>, overlay: &mut Vec, ) -> Option<(runner::RunResult, Option)> { - let RunStep { - run, - iteration, - iterations, - index, - steps, - placed, - row, - } = step; + let RunStep { run, iteration, iterations, index, steps, placed, row } = step; say_run( engine, &run.id, @@ -88,13 +80,7 @@ pub(super) async fn run_step( if matches!(&answer, Err(error) if error.code == crate::error::ErrorCode::HttpCancelled) { return None; } - let result = runner::result_of( - iteration, - &request, - placed.path.clone(), - answer, - run.keep_responses, - ); + let result = runner::result_of(iteration, &request, placed.path.clone(), answer, run.keep_responses); Some((result, next)) } @@ -112,8 +98,5 @@ pub(super) async fn wait(runs: &runner::Runs, id: &str, millis: u32) -> bool { } pub(super) fn say_run(engine: &Engine, id: &str, step: runner::RunStep) { - engine.emit(EngineEvent::Run(runner::RunEvent { - id: id.to_string(), - step, - })); + engine.emit(EngineEvent::Run(runner::RunEvent { id: id.to_string(), step })); } diff --git a/crates/engine/src/http/console.rs b/crates/engine/src/http/console.rs index 6f0cebeec..dca07a344 100644 --- a/crates/engine/src/http/console.rs +++ b/crates/engine/src/http/console.rs @@ -28,14 +28,8 @@ pub struct ConsoleOrigin { impl ConsoleOrigin { #[must_use] pub fn of(id: Option<&str>, scripts: &[Script]) -> Option { - let script = scripts - .iter() - .find(|script| Some(script.id.as_str()) == id)?; - Some(Self { - kind: script.kind, - level: script.level, - name: script.name.clone(), - }) + let script = scripts.iter().find(|script| Some(script.id.as_str()) == id)?; + Some(Self { kind: script.kind, level: script.level, name: script.name.clone() }) } } @@ -126,18 +120,9 @@ pub fn secret_segments(text: &str) -> Vec<(String, bool)> { /// A request as the console shows it: each secret in force written as its name, an auth or a /// cookie header masked as the history masks it. #[must_use] -pub fn out( - exchange: &Exchange, - secrets: &[(String, String)], - by: Option, -) -> ConsoleLine { +pub fn out(exchange: &Exchange, secrets: &[(String, String)], by: Option) -> ConsoleLine { let shown = history::shown(exchange, secrets); - ConsoleLine::Out { - method: shown.method.to_string(), - url: shown.url, - headers: shown.headers, - by, - } + ConsoleLine::Out { method: shown.method.to_string(), url: shown.url, headers: shown.headers, by } } #[must_use] @@ -153,11 +138,7 @@ pub fn answered(response: &SentResponse, by: Option) -> ConsoleLi #[must_use] pub fn failed(error: AppError, by: Option) -> ConsoleLine { - ConsoleLine::Failed { - code: error.code, - params: error.params, - by, - } + ConsoleLine::Failed { code: error.code, params: error.params, by } } /// What a phase leaves in the console, in the order it happened: its logs and its sends, then @@ -205,12 +186,7 @@ pub fn phase( .map(|test| (now, tested(test, scripts, secrets))), ); if let Some(failure) = &outcome.failure { - lines.push(( - now, - ConsoleLine::Stopped { - stop: ScriptStop::of(failure, scripts), - }, - )); + lines.push((now, ConsoleLine::Stopped { stop: ScriptStop::of(failure, scripts) })); } lines } @@ -234,124 +210,197 @@ mod tests { use crate::http::send::{SendError, SentBody}; fn script(id: &str, kind: ScriptKind, level: ScriptLevel, name: &str) -> Script { - Script { - id: id.to_string(), - kind, - level, - name: name.to_string(), - ..Script::default() + Script { id: id.to_string(), kind, level, name: name.to_string(), ..Script::default() } + } + + fn scripts() -> [Script; 2] { + [ + script("s1", ScriptKind::Before, ScriptLevel::Collection, "API"), + script("s2", ScriptKind::Tests, ScriptLevel::Request, "Pay"), + ] + } + + fn origin(script: &Script) -> ConsoleOrigin { + ConsoleOrigin { kind: script.kind, level: script.level, name: script.name.clone() } + } + + fn header(key: &str, value: &str) -> KeyValue { + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } + } + + fn exchange(url: &str, headers: Vec) -> Exchange { + Exchange { method: HttpMethod::Delete, url: url.to_string(), headers, body: SentBody::None } + } + + fn secrets() -> [(String, String); 1] { + [("token".to_string(), "s3cr3t".to_string())] + } + + /// Seconds after an instant. + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_760_000_000 + seconds, 0).unwrap() + } + + fn log(text: &str, script: &str, seconds: i64) -> LogEntry { + LogEntry { + level: LogLevel::Warn, + text: text.to_string(), + script: Some(script.to_string()), + at: Some(at(seconds)), } } - fn exchange(url: &str, headers: &[(&str, &str)]) -> Exchange { - Exchange { - method: HttpMethod::Get, - url: url.to_string(), - headers: headers - .iter() - .map(|(key, value)| KeyValue { - key: (*key).to_string(), - value: (*value).to_string(), - ..KeyValue::default() - }) - .collect(), - body: SentBody::None, + fn sent(answer: Result) -> ScriptSend { + ScriptSend { + script: Some("s1".to_string()), + exchange: exchange("https://auth/s3cr3t", Vec::new()), + started: at(1), + ended: at(3), + answer, } } + fn lines(logs: Vec, sends: Vec, outcome: &Outcome) -> Vec { + phase(logs, sends, outcome, &scripts(), &secrets()) + .into_iter() + .map(|(_, line)| line) + .collect() + } + #[test] fn a_request_leaves_with_its_secrets_written_as_their_names_and_its_auth_masked() { - let secrets = [("token".to_string(), "s3cr3t".to_string())]; - let ConsoleLine::Out { url, headers, .. } = out( - &exchange( - "https://api.exemple.fr/me?key=s3cr3t", - &[("Authorization", "Bearer s3cr3t"), ("X-Trace", "s3cr3t-1")], - ), - &secrets, - None, - ) else { - panic!("not a request"); + let headers = vec![header("Authorization", "Bearer s3cr3t"), header("X-Trace", "s3cr3t-1")]; + + let line = out(&exchange("https://shop.test/me?key=s3cr3t", headers), &secrets(), None); + + let expected = ConsoleLine::Out { + method: "DELETE".to_string(), + url: "https://shop.test/me?key={{token}}".to_string(), + headers: vec![header("Authorization", "Bearer ••••••••"), header("X-Trace", "{{token}}-1")], + by: None, }; - assert_eq!(url, "https://api.exemple.fr/me?key={{token}}"); - assert_eq!(headers[0].value, "Bearer ••••••••"); - assert_eq!(headers[1].value, "{{token}}-1"); + assert_eq!(line, expected); } #[test] - fn a_phase_says_its_logs_and_sends_in_order_then_its_failed_tests_and_its_stop() { - let scripts = [ - script("s1", ScriptKind::Before, ScriptLevel::Collection, "API"), - script("s2", ScriptKind::Tests, ScriptLevel::Request, "Payer"), + fn what_came_back_is_its_status_its_time_and_its_size() { + let response: SentResponse = serde_json::from_value(serde_json::json!({ + "status": 201, "reason": "Created", "millis": 12, "size": 34, "url": "", "headers": [], + "body": "", "binary": false, "cut": false, "incomplete": false, "redirects": [], + "language": "json", "pretty": null, "cookies": [], "graphql": null, + "exchange": { "method": "GET", "url": "", "headers": [], "body": { "kind": "none" } }, + })) + .unwrap(); + + let expected = ConsoleLine::In { + status: 201, + reason: "Created".to_string(), + millis: 12, + size: 34, + by: Some(origin(&scripts()[0])), + }; + assert_eq!(answered(&response, Some(origin(&scripts()[0]))), expected); + assert_eq!(lines(Vec::new(), vec![sent(Ok(response))], &Outcome::default())[1], expected); + } + + /// The order it happened in: a script's send around what it logged meanwhile. + #[test] + fn a_phase_says_its_logs_and_its_sends_in_the_order_they_came() { + let logs = vec![log("s3cr3t between", "s1", 2), log("last", "gone", 4)]; + + let said = lines(logs, vec![sent(Err(SendError::Refused("down".to_string())))], &Outcome::default()); + + let by = Some(origin(&scripts()[0])); + let expected = [ + ConsoleLine::Out { + method: "DELETE".to_string(), + url: "https://auth/{{token}}".to_string(), + headers: Vec::new(), + by: by.clone(), + }, + ConsoleLine::Log { level: LogLevel::Warn, text: "{{token}} between".to_string(), by: by.clone() }, + ConsoleLine::Failed { code: ErrorCode::HttpRefused, params: BTreeMap::new(), by }, + ConsoleLine::Log { level: LogLevel::Warn, text: "last".to_string(), by: None }, ]; - let at = |seconds: i64| DateTime::from_timestamp(1_760_000_000 + seconds, 0).unwrap(); - let logs = vec![LogEntry { - level: LogLevel::Log, - text: "token s3cr3t".to_string(), - script: Some("s1".to_string()), - at: Some(at(2)), - }]; - let sends = vec![ScriptSend { + assert_eq!(said, expected); + } + + #[test] + fn logs_of_one_instant_keep_their_order() { + let said = lines( + vec![log("a", "s1", 1), log("b", "s1", 1), log("c", "s1", 0)], + Vec::new(), + &Outcome::default(), + ); + + let texts: Vec<_> = said + .iter() + .map(|line| match line { + ConsoleLine::Log { text, .. } => text.as_str(), + _ => "", + }) + .collect(); + assert_eq!(texts, ["c", "a", "b"]); + } + + /// After what the phase logged: the tests that failed, then what stopped it. + #[test] + fn a_phase_ends_on_its_failed_tests_and_what_stopped_it() { + let test = |name: &str| TestResult { + name: name.to_string(), + script: Some("s2".to_string()), + ..TestResult::default() + }; + let failed = TestResult { + expected: Some("\"s3cr3t\"".to_string()), + actual: Some("\"usd\"".to_string()), + message: Some("not s3cr3t".to_string()), + ..test("currency s3cr3t") + }; + let failure = ScriptFailure { + kind: FailureKind::Error, script: Some("s1".to_string()), - exchange: exchange("https://auth/login", &[]), - started: at(1), - ended: at(3), - answer: Err(SendError::Refused("down".to_string())), - }]; + line: Some(4), + message: "boom".to_string(), + }; let outcome = Outcome { tests: vec![ - TestResult { - name: "passes".to_string(), - passed: true, - ..TestResult::default() - }, - TestResult { - name: "currency".to_string(), - expected: Some("\"eur\"".to_string()), - actual: Some("\"usd\"".to_string()), - script: Some("s2".to_string()), - ..TestResult::default() - }, + TestResult { passed: true, ..test("passes") }, + TestResult { skipped: true, ..test("later") }, + failed, ], - failure: Some(ScriptFailure { - kind: FailureKind::Error, - script: Some("s1".to_string()), - line: Some(4), - message: "boom".to_string(), - }), + failure: Some(failure.clone()), ..Outcome::default() }; - let secrets = [("token".to_string(), "s3cr3t".to_string())]; - let lines = phase(logs, sends, &outcome, &scripts, &secrets); + let said = lines(vec![log("first", "s1", 0)], Vec::new(), &outcome); - let kinds: Vec<&str> = lines - .iter() - .map(|(_, line)| match line { - ConsoleLine::Out { .. } => "out", - ConsoleLine::In { .. } => "in", - ConsoleLine::Failed { .. } => "failed", - ConsoleLine::Log { .. } => "log", - ConsoleLine::Test { .. } => "test", - ConsoleLine::Stopped { .. } => "stopped", - ConsoleLine::Missed { .. } => "missed", - }) - .collect(); - assert_eq!(kinds, ["out", "log", "failed", "test", "stopped"]); - let ConsoleLine::Log { text, by, .. } = &lines[1].1 else { - panic!("not a log"); - }; - assert_eq!(text, "token {{token}}"); - assert_eq!( - by.as_ref().map(|by| by.level), - Some(ScriptLevel::Collection) - ); - let ConsoleLine::Failed { code, .. } = &lines[2].1 else { - panic!("not a failure"); - }; - assert_eq!(*code, ErrorCode::HttpRefused); - let ConsoleLine::Test { by, .. } = &lines[3].1 else { - panic!("not a test"); + let expected = ConsoleLine::Test { + name: "currency {{token}}".to_string(), + expected: Some("\"{{token}}\"".to_string()), + actual: Some("\"usd\"".to_string()), + message: Some("not {{token}}".to_string()), + by: Some(origin(&scripts()[1])), }; - assert_eq!(by.as_ref().map(|by| by.kind), Some(ScriptKind::Tests)); + assert_eq!(said.len(), 3); + assert_eq!(said[1], expected); + assert_eq!(said[2], ConsoleLine::Stopped { stop: ScriptStop::of(&failure, &scripts()) }); + } + + #[test] + fn a_text_is_cut_where_a_secret_is_written_as_its_name() { + for (text, parts) in [ + ("", vec![]), + ("plain", vec![("plain", false)]), + ("{{token}}", vec![("{{token}}", true)]), + ("a {{b}} c {{d}}", vec![("a ", false), ("{{b}}", true), (" c ", false), ("{{d}}", true)]), + ("open {{b", vec![("open {{b", false)]), + ("{{}} x", vec![("{{", false), ("}} x", false)]), + ("{{a{{b}}", vec![("{{", false), ("a", false), ("{{b}}", true)]), + ] { + let cut = secret_segments(text); + let cut: Vec<(&str, bool)> = cut.iter().map(|(part, secret)| (part.as_str(), *secret)).collect(); + assert_eq!(cut, parts, "{text}"); + } } } diff --git a/crates/engine/src/http/cookies.rs b/crates/engine/src/http/cookies.rs index 10d7b8d6e..ff912c431 100644 --- a/crates/engine/src/http/cookies.rs +++ b/crates/engine/src/http/cookies.rs @@ -59,25 +59,18 @@ fn is_public_suffix(domain: &str) -> bool { /// between —, read token by token: the first time, day, month and year found, a two-digit year /// taken to 1970–2069. `None` for a date that does not read: the cookie lasts the session. fn cookie_date(text: &str) -> Option> { - const MONTHS: [&str; 12] = [ - "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec", - ]; + const MONTHS: [&str; 12] = + ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; let delimiter = |character: char| matches!(character, '\t' | ' '..='/' | ';'..='@' | '['..='`' | '{'..='~'); let leading_digits = |token: &str, at_most: usize| -> Option { let digits: String = token.chars().take_while(char::is_ascii_digit).collect(); - (1..=at_most) - .contains(&digits.len()) - .then(|| digits.parse().ok()) - .flatten() + (1..=at_most).contains(&digits.len()).then(|| digits.parse().ok()).flatten() }; let (mut time, mut day, mut month, mut year) = (None, None, None, None); for token in text.split(delimiter).filter(|token| !token.is_empty()) { if time.is_none() { - let parts: Vec> = token - .splitn(3, ':') - .map(|part| leading_digits(part, 2)) - .collect(); + let parts: Vec> = token.splitn(3, ':').map(|part| leading_digits(part, 2)).collect(); if let [Some(hour), Some(minute), Some(second)] = parts[..] { time = Some((hour, minute, second)); continue; @@ -122,16 +115,12 @@ fn cookie_date(text: &str) -> Option> { } fn domain_matches(host: &str, domain: &str) -> bool { - host == domain - || host - .strip_suffix(domain) - .is_some_and(|rest| rest.ends_with('.')) + host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.')) } fn path_matches(path: &str, cookie: &str) -> bool { path == cookie - || (path.starts_with(cookie) - && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) + || (path.starts_with(cookie) && (cookie.ends_with('/') || path[cookie.len()..].starts_with('/'))) } /// The directory of the request's path: `/api/users` → `/api`. @@ -168,9 +157,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" if !value.is_empty() => { let domain = value.trim_start_matches('.').to_ascii_lowercase(); @@ -205,11 +192,7 @@ fn parse(line: &str, url: &Url, now: DateTime) -> Option { if let Some(seconds) = max_age { cookie.expires = Some(now + TimeDelta::seconds(seconds.max(0))); } - Some(if cookie.expired(now) { - Change::Remove(cookie) - } else { - Change::Set(cookie) - }) + Some(if cookie.expired(now) { Change::Remove(cookie) } else { Change::Set(cookie) }) } fn is_secure(url: &Url) -> bool { @@ -238,16 +221,10 @@ pub fn received(headers: &[KeyValue], url: &Url, now: DateTime) -> Vec, changes: &[Change]) { for change in changes { let (Change::Set(cookie) | Change::Remove(cookie)) = change; - let replaced = jar - .iter() - .find(|known| known.same_as(cookie)) - .and_then(|known| known.created); + let replaced = jar.iter().find(|known| known.same_as(cookie)).and_then(|known| known.created); jar.retain(|known| !known.same_as(cookie)); if let Change::Set(cookie) = change { - jar.push(JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }); + jar.push(JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }); } } } @@ -259,19 +236,15 @@ pub fn matching<'a>(jar: &'a [JarCookie], url: &Url, now: DateTime) -> Vec< return Vec::new(); }; let secure = is_secure(url); - let mut sent: Vec<&JarCookie> = jar - .iter() - .filter(|cookie| !cookie.expired(now)) - .filter(|cookie| { - if cookie.host_only { - host == cookie.domain - } else { - domain_matches(&host, &cookie.domain) - } - }) - .filter(|cookie| path_matches(url.path(), &cookie.path)) - .filter(|cookie| secure || !cookie.secure) - .collect(); + let mut sent: Vec<&JarCookie> = + jar.iter() + .filter(|cookie| !cookie.expired(now)) + .filter(|cookie| { + if cookie.host_only { host == cookie.domain } else { domain_matches(&host, &cookie.domain) } + }) + .filter(|cookie| path_matches(url.path(), &cookie.path)) + .filter(|cookie| secure || !cookie.secure) + .collect(); sent.sort_by_key(|cookie| (std::cmp::Reverse(cookie.path.len()), cookie.created)); sent } @@ -292,264 +265,273 @@ mod tests { use super::*; fn now() -> DateTime { - "2026-10-07T12:00:00Z".parse().unwrap() + crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn url(text: &str) -> Url { + Url::parse(text).unwrap() } fn set_cookie(value: &str) -> KeyValue { - KeyValue { - key: "Set-Cookie".to_string(), - value: value.to_string(), - ..KeyValue::default() + KeyValue { key: "Set-Cookie".to_string(), value: value.to_string(), ..KeyValue::default() } + } + + /// The one change a `Set-Cookie` line makes, answered by `at`. + fn one(line: &str, at: &str) -> Option { + received(&[set_cookie(line)], &url(at), now()).pop() + } + + fn set(line: &str, at: &str) -> JarCookie { + match one(line, at) { + Some(Change::Set(cookie)) => cookie, + other => panic!("{line} at {at}: {other:?}"), } } - fn set(change: Change) -> JarCookie { - match change { - Change::Set(cookie) => cookie, - Change::Remove(cookie) => panic!("removed {cookie:?}"), + fn cookie(name: &str, domain: &str, path: &str) -> JarCookie { + JarCookie { + name: name.to_string(), + value: name.to_uppercase(), + domain: domain.to_string(), + host_only: false, + path: path.to_string(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: Some(now()), } } + fn sent(jar: &[JarCookie], at: &str) -> Vec { + matching(jar, &url(at), now()) + .iter() + .map(|cookie| cookie.name.clone()) + .collect() + } + + /// Without attributes: for the host that set it alone, lowercased, under the directory of + /// the request's path, lasting the session; a quoted value without its quotes. #[test] - fn a_cookie_takes_its_host_and_path_unless_it_names_a_domain_above() { - let url = Url::parse("https://api.exemple.fr/v1/users").unwrap(); - let changes = received( - &[ - set_cookie("session=abc; HttpOnly; Secure"), - set_cookie("theme=dark; Domain=.EXEMPLE.fr; Path=/; Max-Age=3600; SameSite=Lax"), - set_cookie("evil=1; Domain=other.fr"), - set_cookie("old=1; Expires=Wed, 01 Oct 2025 07:28:00 GMT"), - ], - &url, - now(), - ); + fn a_cookie_without_attributes_is_the_host_s_for_its_directory() { + let cookie = set("sid=\"abc=1\"", "https://API.Shop.test/v1/users?x=1"); + + assert_eq!((cookie.name.as_str(), cookie.value.as_str()), ("sid", "abc=1")); + assert_eq!((cookie.domain.as_str(), cookie.host_only), ("api.shop.test", true)); + assert_eq!((cookie.path.as_str(), cookie.expires), ("/v1", None)); + assert_eq!(set("a=1", "https://shop.test/users").path, "/"); + assert_eq!(set("a=1", "https://shop.test").path, "/"); + } - assert_eq!(changes.len(), 3); - let session = set(changes[0].clone()); - assert_eq!( - ( - session.domain.as_str(), - session.host_only, - session.path.as_str() - ), - ("api.exemple.fr", true, "/v1") - ); - assert!(session.secure && session.http_only && session.expires.is_none()); - let theme = set(changes[1].clone()); + /// Only `Set-Cookie`, case aside, in their order, a line naming no cookie left out; created + /// a microsecond apart, so two of one path length go back in the order they were set. + #[test] + fn an_answer_s_cookies_are_read_in_their_order() { + let headers = [ + set_cookie("first=1; HttpOnly; SameSite=Strict"), + KeyValue { key: "Content-Type".to_string(), value: "a=b".to_string(), ..KeyValue::default() }, + KeyValue { key: "set-cookie".to_string(), ..set_cookie("second=2; SameSite=") }, + set_cookie("no equals sign"), + set_cookie(" =nameless"), + ]; + + let changes = received(&headers, &url("https://shop.test/"), now()); + + let read: Vec = changes + .into_iter() + .map(|change| match change { + Change::Set(cookie) => cookie, + Change::Remove(cookie) => panic!("{cookie:?}"), + }) + .collect(); + let names: Vec<&str> = read.iter().map(|cookie| cookie.name.as_str()).collect(); + assert_eq!(names, ["first", "second"]); assert_eq!( - (theme.domain.as_str(), theme.host_only), - ("exemple.fr", false) + (read[0].created, read[1].created), + (Some(now()), Some(now() + TimeDelta::microseconds(1))) ); - assert_eq!(theme.expires, Some(now() + TimeDelta::hours(1))); - assert!(matches!(&changes[2], Change::Remove(cookie) if cookie.name == "old")); + assert!(read[0].http_only && !read[1].http_only); + assert_eq!((read[0].same_site.as_deref(), read[1].same_site.as_deref()), (Some("Strict"), None)); + } - let plain = Url::parse("http://api.exemple.fr/").unwrap(); - assert!(received(&[set_cookie("csrf=1; Secure")], &plain, now()).is_empty()); + /// A server sets a cookie for itself or a domain above it, never for another, an address, + /// or a suffix under which unrelated sites register; naming itself is host-only. + #[test] + fn a_domain_is_taken_only_at_or_above_the_host_and_below_a_public_suffix() { + let above = set("a=1; Domain=.Shop.TEST", "https://api.shop.test/"); + let itself = set("a=1; Domain=api.shop.test", "https://api.shop.test/"); + let empty = set("a=1; Domain=", "https://api.shop.test/"); + let registered = set("a=1; Domain=exemple.co.uk", "https://api.exemple.co.uk/"); + + assert_eq!((above.domain.as_str(), above.host_only), ("shop.test", false)); + assert_eq!((itself.domain.as_str(), itself.host_only), ("api.shop.test", true)); + assert!(empty.host_only); + assert_eq!((registered.domain.as_str(), registered.host_only), ("exemple.co.uk", false)); + for (line, at) in [ + ("a=1; Domain=other.test", "https://shop.test/"), + ("a=1; Domain=api.shop.test", "https://shop.test/"), + ("a=1; Domain=hop.test", "https://shop.test/"), + ("a=1; Domain=co.uk", "https://shop.co.uk/"), + ("a=1; Domain=github.io", "https://me.github.io/"), + ("a=1; Domain=test", "https://shop.test/"), + ("a=1; Domain=0.1", "http://127.0.0.1/"), + ] { + assert_eq!(one(line, at), None, "{line} at {at}"); + } + assert!(set("a=1; Domain=127.0.0.1", "http://127.0.0.1/").host_only); } - /// #705: `x.co.uk` set a cookie for `co.uk`, sent to every `.co.uk` site; `127.0.0.1` one - /// for `0.0.1`. + /// A path that does not start with `/` is ignored for the default one. #[test] - fn a_public_suffix_and_an_address_take_no_domain_above_them() { - let names = |url: &str, lines: &[&str]| -> Vec<(String, String, bool)> { - let url = Url::parse(url).unwrap(); - let headers: Vec = lines.iter().map(|line| set_cookie(line)).collect(); - received(&headers, &url, now()) - .into_iter() - .map(|change| { - let cookie = set(change); - (cookie.name, cookie.domain, cookie.host_only) - }) - .collect() - }; - let cookie = |name: &str, domain: &str, host_only: bool| { - (name.to_string(), domain.to_string(), host_only) - }; + fn a_path_is_taken_only_when_it_starts_with_a_slash() { + assert_eq!(set("a=1; Path=/api", "https://shop.test/v1/x").path, "/api"); + assert_eq!(set("a=1; Path=api", "https://shop.test/v1/x").path, "/v1"); + } + + /// As browsers do: a plain connection cannot set what only a secure one may read. + #[test] + fn a_secure_cookie_is_set_only_over_a_secure_connection() { + assert!(set("a=1; Secure", "https://shop.test/").secure); + assert!(set("a=1; Secure", "wss://shop.test/").secure); + assert_eq!(one("a=1; Secure", "http://shop.test/"), None); + assert_eq!(one("a=1; Secure", "ws://shop.test/"), None); + } + + /// `Max-Age` counts from now and wins over `Expires`, whichever comes first; zero or less, + /// or an expiry past, removes; a `Max-Age` that is no number, or a second `Expires` that + /// does not read, is ignored. + #[test] + fn an_expiry_counts_from_now_or_removes_the_cookie() { + let in_a_minute = Some(now() + TimeDelta::seconds(60)); assert_eq!( - names( - "https://x.co.uk/", - &["suffix=1; Domain=co.uk", "itself=1; Domain=x.co.uk"] - ), - [cookie("itself", "x.co.uk", true)] + set("a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", "https://shop.test/").expires, + in_a_minute ); assert_eq!( - names( - "https://api.exemple.co.uk/", - &[ - "registered=1; Domain=exemple.co.uk", - "pages=1; Domain=github.io" - ] - ), - [cookie("registered", "exemple.co.uk", false)] + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", "https://shop.test/").expires, + in_a_minute ); - assert!(names("https://ada.github.io/", &["all=1; Domain=github.io"]).is_empty()); + assert_eq!(set("a=1; Max-Age=soon", "https://shop.test/").expires, None); + let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); assert_eq!( - names( - "http://127.0.0.1:8080/", - &["above=1; Domain=0.0.1", "named=1; Domain=127.0.0.1"] - ), - [cookie("named", "127.0.0.1", true)] + set("a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Expires=garbage", "https://shop.test/").expires, + october ); + for line in ["a=1; Max-Age=0", "a=1; Max-Age=-5", "a=1; Expires=Thu, 01 Jan 2026 00:00:00 GMT"] { + assert!(matches!(one(line, "https://shop.test/"), Some(Change::Remove(_))), "{line}"); + } } - /// Headers are decoded lossily: a date may hold anything. + /// Dates as servers write them, read token by token, a two-digit year taken to 1970–2069; + /// one that does not read — accented letters included, which once broke the reading — lasts + /// the session. #[test] - fn an_expiry_in_accented_letters_is_no_date() { - assert_eq!(cookie_date("éé"), None); - assert_eq!(cookie_date("21 éé 2026"), None); + fn an_expiry_is_read_in_every_form_servers_write() { + let october = crate::db::iso8601::parse("2026-10-21T07:28:00.000Z").ok(); + for (date, expected) in [ + ("Wed, 21 Oct 2026 07:28:00 GMT", october), + ("Wednesday, 21-Oct-26 07:28:00 GMT", october), + ("Wed Oct 21 07:28:00 2026", october), + ("21 october 2026 7:28:0", october), + ("Sun, 01-Jan-69 00:00:01 GMT", crate::db::iso8601::parse("2069-01-01T00:00:01.000Z").ok()), + ("mér., 21 oct. 2026 07:28:00", october), + ("Wed, 21 Oct 2026 25:00:00 GMT", None), + ("Wed, 31 Feb 2026 07:28:00 GMT", None), + ("Wed, 21 Oct 1600 07:28:00 GMT", None), + ("Wed, 21 Oct 207 07:28:00 GMT", None), + ("éèà", None), + ("tomorrow", None), + ("21 Oct 2026", None), + ("21 éé 2026 07:28:00", None), + ] { + let read = set(&format!("a=1; Expires={date}"), "https://shop.test/"); + + assert_eq!(read.expires, expected, "{date}"); + } + assert!(matches!( + one("a=1; Expires=Thu, 01-Jan-70 00:00:01 GMT", "https://shop.test/"), + Some(Change::Remove(_)) + )); } - /// #705: RFC 850 and asctime were read as no date at all, and the cookie lived the session. + /// The same name, domain and path is the same cookie: replaced, keeping its first creation; + /// a removal takes it away; another path is another cookie. #[test] - fn an_expiry_is_read_in_every_format_servers_write() { - let at = |text: &str| cookie_date(text).map(|date| date.to_rfc3339()); - let expected = Some("2026-10-21T07:28:00+00:00".to_string()); - - assert_eq!(at("Wed, 21 Oct 2026 07:28:00 GMT"), expected); - assert_eq!(at("Wednesday, 21-Oct-26 07:28:00 GMT"), expected); - assert_eq!(at("Wed Oct 21 07:28:00 2026"), expected); - assert_eq!(at("21-Oct-2026 07:28:00 GMT"), expected); - assert_eq!( - at("Thu, 01-Jan-70 00:00:01 GMT"), - Some("1970-01-01T00:00:01+00:00".to_string()) - ); - assert_eq!( - at("Sun, 01-Jan-69 00:00:01 GMT"), - Some("2069-01-01T00:00:01+00:00".to_string()) - ); - for unreadable in [ - "", - "tomorrow", - "Wed, 32 Oct 2026 07:28:00 GMT", - "21 Oct 2026", - ] { - assert_eq!(at(unreadable), None, "{unreadable}"); - } + fn a_change_replaces_or_removes_the_same_cookie() { + let mut jar = vec![cookie("a", "shop.test", "/"), cookie("a", "shop.test", "/api")]; + let newer = JarCookie { + value: "new".to_string(), + created: Some(now() + TimeDelta::hours(1)), + ..cookie("a", "shop.test", "/") + }; - let url = Url::parse("https://exemple.fr/").unwrap(); - let change = received( - &[set_cookie("a=1; Expires=Wednesday, 21-Oct-26 07:28:00 GMT")], - &url, - now(), - ); - assert_eq!( - set(change[0].clone()).expires.map(|date| date.to_rfc3339()), - expected - ); + apply(&mut jar, &[Change::Set(newer), Change::Set(cookie("b", "shop.test", "/"))]); + assert_eq!(jar.len(), 3); + let replaced = jar.iter().find(|known| known.path == "/" && known.name == "a").unwrap(); + assert_eq!((replaced.value.as_str(), replaced.created), ("new", Some(now()))); + + apply(&mut jar, &[Change::Remove(cookie("a", "shop.test", "/api"))]); + let left: Vec<(&str, &str)> = + jar.iter().map(|known| (known.name.as_str(), known.path.as_str())).collect(); + assert_eq!(left, [("a", "/"), ("b", "/")]); } - /// #705: two paths of one length came out in the order the jar was read, a random id's. + /// A host-only cookie to its host alone; a domain cookie to the domain and below it, never + /// to a name that merely ends like it. #[test] - fn of_two_paths_of_one_length_the_older_cookie_goes_first_and_a_replacement_keeps_its_age() { - let url = Url::parse("https://exemple.fr/").unwrap(); - let mut jar = Vec::new(); - apply( - &mut jar, - &received(&[set_cookie("first=1; Path=/")], &url, now()), - ); - apply( - &mut jar, - &received( - &[ - set_cookie("second=1; Path=/"), - set_cookie("third=1; Path=/"), - ], - &url, - now() + TimeDelta::seconds(1), - ), - ); - // Read back in another order, as the store may. - jar.reverse(); - assert_eq!( - header_for(&jar, &url, now()).as_deref(), - Some("first=1; second=1; third=1") - ); + fn a_cookie_is_sent_to_its_host_or_below_its_domain() { + let jar = [ + JarCookie { host_only: true, ..cookie("host", "shop.test", "/") }, + cookie("domain", "shop.test", "/"), + ]; - apply( - &mut jar, - &received( - &[set_cookie("first=2; Path=/")], - &url, - now() + TimeDelta::seconds(2), - ), - ); - assert_eq!( - header_for(&jar, &url, now()).as_deref(), - Some("first=2; second=1; third=1") - ); + assert_eq!(sent(&jar, "https://shop.test/"), ["host", "domain"]); + assert_eq!(sent(&jar, "https://API.shop.test/"), ["domain"]); + assert!(sent(&jar, "https://evilshop.test/").is_empty()); + assert!(sent(&jar, "data:text/plain,x").is_empty()); } + /// A path and what lies under it, never a name that merely starts like it. #[test] - fn a_jar_in_memory_takes_a_cookie_replaces_it_and_lets_it_go() { - let url = Url::parse("http://api.exemple.fr/login").unwrap(); - let mut jar = Vec::new(); - let line = |jar: &[JarCookie]| header_for(jar, &url, now()); - - apply( - &mut jar, - &received(&[set_cookie("session=abc; Path=/")], &url, now()), - ); - assert_eq!(line(&jar).as_deref(), Some("session=abc")); - - apply( - &mut jar, - &received( - &[ - set_cookie("session=def; Path=/"), - set_cookie("theme=dark; Path=/"), - ], - &url, - now(), - ), - ); - assert_eq!(line(&jar).as_deref(), Some("session=def; theme=dark")); + fn a_cookie_is_sent_under_its_path() { + let jar = [cookie("api", "shop.test", "/api"), cookie("slash", "shop.test", "/v1/")]; + + assert_eq!(sent(&jar, "https://shop.test/api"), ["api"]); + assert_eq!(sent(&jar, "https://shop.test/api/users"), ["api"]); + assert!(sent(&jar, "https://shop.test/apix").is_empty()); + assert_eq!(sent(&jar, "https://shop.test/v1/x"), ["slash"]); + assert!(sent(&jar, "https://shop.test/v1").is_empty()); + } - apply( - &mut jar, - &received(&[set_cookie("session=; Path=/; Max-Age=0")], &url, now()), - ); - assert_eq!(line(&jar).as_deref(), Some("theme=dark")); + /// Neither an expired cookie nor, over a plain connection, a secure one. + #[test] + fn an_expired_or_secure_cookie_is_held_back() { + let jar = [ + JarCookie { expires: Some(now()), ..cookie("expired", "shop.test", "/") }, + JarCookie { expires: Some(now() + TimeDelta::seconds(1)), ..cookie("later", "shop.test", "/") }, + JarCookie { secure: true, ..cookie("secure", "shop.test", "/") }, + ]; + + assert_eq!(sent(&jar, "http://shop.test/"), ["later"]); + assert_eq!(sent(&jar, "https://shop.test/"), ["later", "secure"]); + assert_eq!(sent(&jar, "wss://shop.test/"), ["later", "secure"]); } + /// The longest paths first and, of two paths of one length, the older first; one header, + /// or none. #[test] - fn a_request_carries_what_matches_its_host_path_and_scheme_the_longest_paths_first() { - let cookie = - |name: &str, domain: &str, host_only: bool, path: &str, secure: bool| JarCookie { - name: name.to_string(), - value: "v".to_string(), - domain: domain.to_string(), - host_only, - path: path.to_string(), - expires: None, - secure, - http_only: false, - same_site: None, - created: None, - }; - let jar = vec![ - cookie("root", "exemple.fr", false, "/", false), - cookie("api", "api.exemple.fr", true, "/v1", false), - cookie("secure", "exemple.fr", false, "/", true), - cookie("elsewhere", "other.fr", false, "/", false), - cookie("sibling", "exemple.fr", true, "/", false), - JarCookie { - expires: Some(now() - TimeDelta::seconds(1)), - ..cookie("gone", "exemple.fr", false, "/", false) - }, + fn the_cookie_header_sends_the_longest_paths_first_then_the_oldest() { + let jar = [ + JarCookie { created: Some(now() + TimeDelta::seconds(2)), ..cookie("young", "shop.test", "/") }, + cookie("old", "shop.test", "/"), + cookie("deep", "shop.test", "/api"), ]; - let plain = Url::parse("http://api.exemple.fr/v1/users").unwrap(); - assert_eq!( - header_for(&jar, &plain, now()).as_deref(), - Some("api=v; root=v") - ); - let secure = Url::parse("https://api.exemple.fr/v10").unwrap(); assert_eq!( - header_for(&jar, &secure, now()).as_deref(), - Some("root=v; secure=v") + header_for(&jar, &url("https://shop.test/api/x"), now()).as_deref(), + Some("deep=DEEP; old=OLD; young=YOUNG") ); - let other = Url::parse("https://nowhere.fr/").unwrap(); - assert_eq!(header_for(&jar, &other, now()), None); + assert_eq!(header_for(&jar, &url("https://other.test/"), now()), None); } } diff --git a/crates/engine/src/http/cookies/store.rs b/crates/engine/src/http/cookies/store.rs index de5407a8b..3092c38e2 100644 --- a/crates/engine/src/http/cookies/store.rs +++ b/crates/engine/src/http/cookies/store.rs @@ -24,18 +24,12 @@ pub struct CookieDomain { } fn open(vault: &Vault, id: String, sealed: &str) -> Result { - let cookie = - serde_json::from_str(&vault.open(sealed)?).map_err(|_| StorageError::CorruptRow { - id: id.clone(), - field: "cookie", - })?; + let cookie = serde_json::from_str(&vault.open(sealed)?) + .map_err(|_| StorageError::CorruptRow { id: id.clone(), field: "cookie" })?; Ok(StoredCookie { id, cookie }) } -fn read( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn read(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { http_cookies::table .select((http_cookies::id, http_cookies::cookie)) .load::<(String, String)>(connection)? @@ -56,11 +50,7 @@ pub fn jar(connection: &mut Library, now: DateTime) -> Result, -) -> Result<(), StorageError> { +pub fn apply(connection: &mut Library, changes: &[Change], now: DateTime) -> Result<(), StorageError> { if changes.is_empty() { return Ok(()); } @@ -76,10 +66,7 @@ pub fn apply( known.retain(|stored| !stored.cookie.same_as(cookie)); if let Change::Set(cookie) = change { // As the jar held in memory does: a replaced cookie keeps its place. - let cookie = &JarCookie { - created: replaced.or(cookie.created), - ..cookie.clone() - }; + let cookie = &JarCookie { created: replaced.or(cookie.created), ..cookie.clone() }; let id = Uuid::new_v4().to_string(); let json = serde_json::to_string(cookie) .map_err(|error| StorageError::Vault(format!("unwritable cookie: {error}")))?; @@ -90,16 +77,11 @@ pub fn apply( http_cookies::cookie.eq(vault.seal(&json)?), )) .execute(connection)?; - known.push(StoredCookie { - id, - cookie: cookie.clone(), - }); + known.push(StoredCookie { id, cookie: cookie.clone() }); } } - diesel::delete( - http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now))), - ) - .execute(connection)?; + diesel::delete(http_cookies::table.filter(http_cookies::expires_at.le(iso8601::format(now)))) + .execute(connection)?; Ok(()) }) } @@ -119,10 +101,7 @@ pub fn by_domain(connection: &mut Library) -> Result, StorageE for stored in cookies { match domains.last_mut() { Some(last) if last.domain == stored.cookie.domain => last.cookies.push(stored), - _ => domains.push(CookieDomain { - domain: stored.cookie.domain.clone(), - cookies: vec![stored], - }), + _ => domains.push(CookieDomain { domain: stored.cookie.domain.clone(), cookies: vec![stored] }), } } Ok(domains) @@ -134,9 +113,7 @@ fn removed(count: usize) -> u32 { pub fn delete(connection: &mut Library, id: &str) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table.find(id)).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table.find(id)).execute(connection)?)) } /// A domain's cookies, answering how many went. @@ -147,10 +124,7 @@ pub fn delete_domain(connection: &mut Library, domain: &str) -> Result Result { @@ -161,9 +135,7 @@ pub fn count(connection: &mut Library) -> Result { pub fn clear(connection: &mut Library) -> Result { let (connection, _) = connection.split(); - Ok(removed( - diesel::delete(http_cookies::table).execute(connection)?, - )) + Ok(removed(diesel::delete(http_cookies::table).execute(connection)?)) } #[cfg(test)] @@ -171,83 +143,161 @@ mod tests { use super::*; use chrono::TimeDelta; - fn cookie(name: &str, domain: &str, value: &str) -> JarCookie { + fn now() -> DateTime { + iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn cookie(name: &str, domain: &str, path: &str) -> JarCookie { JarCookie { name: name.to_string(), - value: value.to_string(), + value: format!("{name}-value"), domain: domain.to_string(), - host_only: false, - path: "/".to_string(), + host_only: true, + path: path.to_string(), expires: None, secure: false, http_only: false, same_site: None, - created: None, + created: Some(now()), } } - #[test] - fn a_cookie_set_again_replaces_itself_and_one_expired_goes() { + fn lasting(name: &str, seconds: i64) -> JarCookie { + JarCookie { expires: Some(now() + TimeDelta::seconds(seconds)), ..cookie(name, "shop.test", "/") } + } + + fn names(jar: &[JarCookie]) -> Vec<&str> { + let mut names: Vec<&str> = jar.iter().map(|cookie| cookie.name.as_str()).collect(); + names.sort_unstable(); + names + } + + /// Written an hour ago: what expires by now is still in the table. + fn library_with(cookies: &[JarCookie]) -> Library { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - apply( - &mut library, - &[ - Change::Set(cookie("session", "a.fr", "1")), - Change::Set(cookie("theme", "a.fr", "dark")), - Change::Set(JarCookie { - expires: Some(now + TimeDelta::seconds(10)), - ..cookie("brief", "b.fr", "x") - }), - ], - now, - ) - .unwrap(); - apply( - &mut library, - &[ - Change::Set(cookie("session", "a.fr", "2")), - Change::Remove(cookie("theme", "a.fr", "")), - ], - now + TimeDelta::seconds(20), - ) - .unwrap(); - - let domains = by_domain(&mut library).unwrap(); - assert_eq!(domains.len(), 1); - assert_eq!(domains[0].cookies.len(), 1); - assert_eq!(domains[0].cookies[0].cookie.value, "2"); - assert_eq!(jar(&mut library, now).unwrap().len(), 1); - - apply(&mut library, &[Change::Set(cookie("x", "b.fr", "1"))], now).unwrap(); - assert_eq!(delete_domain(&mut library, "a.fr").unwrap(), 1); - let id = by_domain(&mut library).unwrap()[0].cookies[0].id.clone(); - assert_eq!(delete(&mut library, &id).unwrap(), 1); - assert_eq!(count(&mut library).unwrap(), 0); + let changes: Vec = cookies.iter().cloned().map(Change::Set).collect(); + apply(&mut library, &changes, now() - TimeDelta::hours(1)).unwrap(); + library } - /// As the jar held in memory does: a cookie set again keeps its place among those sent. + /// The same cookie is replaced, keeping its place among those of its path; a removal takes + /// it away; what has expired by now goes as the changes are written. #[test] - fn a_cookie_set_again_keeps_when_it_was_first_made() { - let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - let at = |seconds| Some(now + TimeDelta::seconds(seconds)); - let first = JarCookie { - created: at(0), - ..cookie("session", "a.fr", "1") - }; - let again = JarCookie { - created: at(5), - ..cookie("session", "a.fr", "2") + fn an_answer_s_changes_replace_remove_and_sweep_the_jar() { + let mut library = library_with(&[ + cookie("a", "shop.test", "/"), + lasting("short", 10), + cookie("b", "shop.test", "/"), + ]); + let newer = JarCookie { + value: "new".to_string(), + created: Some(now() + TimeDelta::hours(1)), + ..cookie("a", "shop.test", "/") }; - apply(&mut library, &[Change::Set(first.clone())], now).unwrap(); - apply(&mut library, &[Change::Set(again.clone())], now).unwrap(); - let mut held = vec![first]; - crate::http::cookies::apply(&mut held, &[Change::Set(again)]); - let stored = jar(&mut library, now).unwrap(); + let later = now() + TimeDelta::seconds(10); + apply(&mut library, &[Change::Set(newer), Change::Remove(cookie("b", "shop.test", "/"))], later) + .unwrap(); + + let jar = jar(&mut library, now()).unwrap(); + assert_eq!(names(&jar), ["a"]); + assert_eq!((jar[0].value.as_str(), jar[0].created), ("new", Some(now()))); + assert_eq!(count(&mut library).unwrap(), 1); + } + + /// What has expired is never sent, even before a write sweeps it. + #[test] + fn the_jar_read_leaves_out_what_has_expired() { + let mut library = + library_with(&[lasting("expired", 0), lasting("later", 1), cookie("session", "shop.test", "/")]); + + let jar = jar(&mut library, now()).unwrap(); + + assert_eq!(names(&jar), ["later", "session"]); + } + + /// No change writes nothing, and sweeps nothing either. + #[test] + fn no_change_writes_nothing() { + let mut library = library_with(&[lasting("expired", 0)]); + + apply(&mut library, &[], now() + TimeDelta::hours(1)).unwrap(); - assert_eq!(stored[0].created, held[0].created); - assert_eq!(stored[0].created, at(0)); + assert_eq!(count(&mut library).unwrap(), 1); + } + + /// What the manager lists: by domain, then name, then path. + #[test] + fn the_jar_is_listed_by_domain_then_name() { + let mut library = library_with(&[ + cookie("a", "b.test", "/"), + cookie("b", "a.test", "/x"), + cookie("b", "a.test", "/"), + cookie("a", "a.test", "/"), + ]); + + let listed = by_domain(&mut library).unwrap(); + + let shown: Vec<(&str, Vec<(&str, &str)>)> = listed + .iter() + .map(|domain| { + let cookies = domain + .cookies + .iter() + .map(|stored| (stored.cookie.name.as_str(), stored.cookie.path.as_str())) + .collect(); + (domain.domain.as_str(), cookies) + }) + .collect(); + assert_eq!( + shown, + [("a.test", vec![("a", "/"), ("b", "/"), ("b", "/x")]), ("b.test", vec![("a", "/")]),] + ); + } + + /// One cookie, a domain's, or all of them, each answering how many went. + #[test] + fn cookies_are_deleted_one_a_domain_or_all_at_once() { + let mut library = library_with(&[ + cookie("a", "a.test", "/"), + cookie("b", "a.test", "/"), + cookie("c", "b.test", "/"), + cookie("d", "c.test", "/"), + ]); + let one = by_domain(&mut library).unwrap()[2].cookies[0].id.clone(); + + assert_eq!(delete(&mut library, &one).unwrap(), 1); + assert_eq!(delete(&mut library, &one).unwrap(), 0); + assert_eq!(delete_domain(&mut library, "a.test").unwrap(), 2); + assert_eq!(count(&mut library).unwrap(), 1); + assert_eq!(clear(&mut library).unwrap(), 1); + assert_eq!(count(&mut library).unwrap(), 0); + } + + /// A cookie that does not read fails the jar rather than vanishing from it. + #[test] + fn a_cookie_that_does_not_read_is_named_as_such() { + let mut library = library_with(&[cookie("a", "shop.test", "/")]); + let garbage = library.vault().seal("not json").unwrap(); + diesel::update(http_cookies::table) + .set(http_cookies::cookie.eq(garbage)) + .execute(library.db()) + .unwrap(); + + assert!(matches!(jar(&mut library, now()), Err(StorageError::CorruptRow { field: "cookie", .. }))); + } + + /// Sealed whole: neither a name nor a value, nor its domain, is in the database in the clear. + #[test] + fn a_cookie_is_sealed_whole() { + let mut library = library_with(&[cookie("session_id", "bank.test", "/")]); + + let stored: Vec = + http_cookies::table.select(http_cookies::cookie).load(library.db()).unwrap(); + + assert_eq!(stored.len(), 1); + for clear in ["session_id", "bank.test"] { + assert!(!stored[0].contains(clear), "{clear} in the clear"); + } } } diff --git a/crates/engine/src/http/environments.rs b/crates/engine/src/http/environments.rs index 3db32c859..a3137932c 100644 --- a/crates/engine/src/http/environments.rs +++ b/crates/engine/src/http/environments.rs @@ -190,56 +190,64 @@ pub fn variable_faults(variables: &[Variable]) -> Vec> { mod tests { use super::*; - fn variable(name: &str, value: &str, kind: VariableKind) -> Variable { - Variable { - name: name.to_string(), - value: value.to_string(), - kind, - ..Variable::default() - } + fn variable(name: &str, value: &str) -> Variable { + Variable { name: name.to_string(), value: value.to_string(), ..Variable::default() } } - #[test] - fn every_kind_survives_its_stored_spelling() { - for kind in VariableKind::ALL { - assert_eq!(kind.as_str().parse::(), Ok(kind)); - } + fn number(name: &str, value: &str) -> Variable { + Variable { kind: VariableKind::Number, ..variable(name, value) } } + fn secret(name: &str) -> Variable { + Variable { kind: VariableKind::Secret, ..variable(name, "s") } + } + + /// What a `{{…}}` can hold: letters, digits, `_` and `-`, as a snippet's field. #[test] - fn a_name_holds_what_a_placeholder_holds() { - for name in ["baseUrl", "access_token", "api-key", "v2"] { - assert!(is_variable_name(name), "{name}"); - } - for name in ["", "base url", "user.name", "clé", "{{x}}"] { - assert!(!is_variable_name(name), "{name}"); + fn a_variable_name_holds_letters_digits_underscores_and_dashes() { + for (name, valid) in [ + ("base_url", true), + ("api-v2", true), + ("ID9", true), + ("", false), + ("a.b", false), + ("a b", false), + ("clé", false), + ("$guid", false), + ] { + assert_eq!(is_variable_name(name), valid, "{name:?}"); } } + /// Kept as typed and marked: a name no `{{…}}` can hold, a number that does not read as + /// one, a name already set above it — the first one being used. A row switched off or + /// still without a name is not judged. #[test] - fn a_table_marks_a_bad_name_a_second_one_and_a_number_that_is_not() { - let mut off = variable("token", "x", VariableKind::Text); - off.enabled = false; + fn a_row_is_marked_by_what_keeps_it_from_resolving() { + let rows = [ + variable("host", "x"), + variable("bad name", "x"), + number("count", "12.5"), + number("empty", ""), + number("many", "many"), + number("endless", "inf"), + variable(" host ", "again"), + Variable { enabled: false, ..variable("bad name", "x") }, + variable(" ", "unnamed"), + ]; + + let faults = variable_faults(&rows); + assert_eq!( - variable_faults(&[ - variable("baseUrl", "https://exemple.fr", VariableKind::Text), - variable("base url", "", VariableKind::Text), - variable("baseUrl", "other", VariableKind::Text), - variable("pageSize", "50", VariableKind::Number), - variable("ratio", "-1.5e3", VariableKind::Number), - variable("limit", "fifty", VariableKind::Number), - variable("unset", " ", VariableKind::Number), - variable(" ", "orphan", VariableKind::Text), - off, - ]), - vec![ + faults, + [ None, Some(VariableFault::Name), - Some(VariableFault::Duplicate), None, None, Some(VariableFault::Number), - None, + Some(VariableFault::Number), + Some(VariableFault::Duplicate), None, None, ] @@ -247,29 +255,71 @@ mod tests { } #[test] - fn a_patch_changes_what_it_names_and_nothing_else() { - let before = EnvironmentDocument { + fn a_set_counts_its_named_variables_and_its_secrets() { + let counts = variable_counts(&[variable("a", "1"), secret("b"), secret(" "), variable("", "x")]); + + assert_eq!(counts, VariableCounts { count: 2, secrets: 1 }); + } + + /// What reads without changing anything goes unasked; a socket asks before it opens, + /// whatever it then says. + #[test] + fn a_protected_environment_asks_before_anything_that_could_change_something() { + for method in HttpMethod::ALL { + assert_eq!( + asks_before_sending(RequestKind::Http, method), + !method.changes_nothing(), + "{method:?}" + ); + assert_eq!( + asks_before_sending(RequestKind::Graphql, method), + !method.changes_nothing(), + "{method:?}" + ); + assert!(asks_before_sending(RequestKind::Websocket, method), "{method:?}"); + } + } + + /// A field left out is untouched; the name comes validated, apart from the patch. + #[test] + fn a_patch_changes_only_the_fields_it_sets() { + let document = EnvironmentDocument { name: "Staging".to_string(), colour: FolderColour::Amber, protected: false, - variables: vec![variable("a", "1", VariableKind::Text)], + variables: vec![variable("host", "staging")], }; - let after = before.clone().patched( - &EnvironmentPatch { - protected: Some(true), - ..EnvironmentPatch::default() - }, - None, - ); + let patch = EnvironmentPatch { protected: Some(true), ..EnvironmentPatch::default() }; + let full = EnvironmentPatch { + name: Some("ignored".to_string()), + colour: Some(FolderColour::Red), + protected: Some(true), + variables: Some(vec![variable("host", "prod")]), + }; + + let protected = document.clone().patched(&patch, None); + let renamed = document.clone().patched(&full, Some("Production")); + + assert_eq!(protected, EnvironmentDocument { protected: true, ..document }); assert_eq!( - after, + renamed, EnvironmentDocument { + name: "Production".to_string(), + colour: FolderColour::Red, protected: true, - ..before + variables: vec![variable("host", "prod")], } ); } + #[test] + fn an_environment_is_named_readably() { + assert_eq!(validated_name(" Prod ").unwrap(), "Prod"); + assert!(validated_name("").is_err()); + } + + /// Every field defaults: a set written by an older version still opens, and a row without + /// its switch is on. #[test] fn a_document_written_before_a_field_existed_still_opens() { let document: EnvironmentDocument = serde_json::from_str(r#"{"name":"Local"}"#).unwrap(); @@ -280,4 +330,12 @@ mod tests { assert!(row.enabled); assert_eq!(row.kind, VariableKind::Text); } + + /// Stored as written: a kind reads back from its spelling. + #[test] + fn every_variable_kind_reads_back_from_its_spelling() { + for kind in VariableKind::ALL { + assert_eq!(kind.as_str().parse::(), Ok(kind)); + } + } } diff --git a/crates/engine/src/http/environments/store.rs b/crates/engine/src/http/environments/store.rs index cb23f82ea..84cdcc63b 100644 --- a/crates/engine/src/http/environments/store.rs +++ b/crates/engine/src/http/environments/store.rs @@ -26,10 +26,8 @@ struct EnvironmentRow { impl EnvironmentRow { fn document(&self, vault: &Vault) -> Result { - serde_json::from_str(&vault.open(&self.document)?).map_err(|_| StorageError::CorruptRow { - id: self.id.clone(), - field: "document", - }) + serde_json::from_str(&vault.open(&self.document)?) + .map_err(|_| StorageError::CorruptRow { id: self.id.clone(), field: "document" }) } fn open(self, vault: &Vault) -> Result { @@ -58,10 +56,7 @@ fn rows(connection: &mut SqliteConnection) -> Result, Storag .load(connection)?) } -fn environments( - connection: &mut SqliteConnection, - vault: &Vault, -) -> Result, StorageError> { +fn environments(connection: &mut SqliteConnection, vault: &Vault) -> Result, StorageError> { rows(connection)? .into_iter() .filter(|row| row.kind == ENVIRONMENT) @@ -80,11 +75,7 @@ fn find(connection: &mut SqliteConnection, id: &str) -> Result, -) -> Result<(), StorageError> { +fn refuse_taken(held: &[Environment], name: &str, except_id: Option<&str>) -> Result<(), StorageError> { let pairs = held .iter() .map(|environment| (environment.id.as_str(), environment.name.as_str())); @@ -105,10 +96,7 @@ pub fn list(connection: &mut Library) -> Result environments.push(row.open(vault)?); } } - Ok(HttpEnvironments { - globals, - environments, - }) + Ok(HttpEnvironments { globals, environments }) } /// One environment, for the send that resolves from it. @@ -138,11 +126,7 @@ fn insert( } /// Last, in the next of the five colours: two made one after the other differ. -pub fn create( - connection: &mut Library, - name: &str, - now: DateTime, -) -> Result { +pub fn create(connection: &mut Library, name: &str, now: DateTime) -> Result { connection.transaction(|connection, vault| { let held = environments(connection, vault)?; refuse_taken(&held, name, None)?; @@ -189,15 +173,11 @@ pub fn save_globals( connection.transaction(|connection, vault| { let document = seal( vault, - &EnvironmentDocument { - variables: variables.to_vec(), - ..EnvironmentDocument::default() - }, + &EnvironmentDocument { variables: variables.to_vec(), ..EnvironmentDocument::default() }, )?; - let changed = - diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) - .set(http_environments::document.eq(&document)) - .execute(connection)?; + let changed = diesel::update(http_environments::table.filter(http_environments::kind.eq(GLOBALS))) + .set(http_environments::document.eq(&document)) + .execute(connection)?; if changed == 0 { diesel::insert_into(http_environments::table) .values(( @@ -224,10 +204,7 @@ pub fn duplicate( connection.transaction(|connection, vault| { let original = find(connection, id)?; refuse_taken(&environments(connection, vault)?, name, None)?; - let document = EnvironmentDocument { - name: name.to_string(), - ..original.document(vault)? - }; + let document = EnvironmentDocument { name: name.to_string(), ..original.document(vault)? }; diesel::update( http_environments::table .filter(http_environments::kind.eq(ENVIRONMENT)) diff --git a/crates/engine/src/http/error.rs b/crates/engine/src/http/error.rs index 0386ec8a4..a1565f128 100644 --- a/crates/engine/src/http/error.rs +++ b/crates/engine/src/http/error.rs @@ -42,31 +42,22 @@ impl From for AppError { .and("unit", unit) .set_by(&limit.set_by) } - SendError::TooManyRedirects(limit) => { - Self::new(ErrorCode::HttpTooManyRedirects, detail) - .and("count", &limit.value.to_string()) - .set_by(&limit.set_by) - } + SendError::TooManyRedirects(limit) => Self::new(ErrorCode::HttpTooManyRedirects, detail) + .and("count", &limit.value.to_string()) + .set_by(&limit.set_by), SendError::FileUnreadable(path) => { Self::with(ErrorCode::HttpFileUnreadable, detail, "path", &path) } - SendError::FileTooLarge(path) => { - Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) - .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()) - } + SendError::FileTooLarge(path) => Self::with(ErrorCode::HttpFileTooLarge, detail, "path", &path) + .and("limit", &crate::http::send::SENT_FILE_MEGABYTES.to_string()), SendError::Cancelled => Self::new(ErrorCode::HttpCancelled, detail), SendError::Fell => Self::new(ErrorCode::HttpFell, detail), SendError::GraphqlVariables(_) => Self::new(ErrorCode::HttpGraphqlVariables, detail), - SendError::Handshake(status) => Self::with( - ErrorCode::HttpWebsocketRefused, - detail, - "status", - &status.to_string(), - ), - // The cause's own words: « Erreur réseau » alone tells nothing. - SendError::Network(cause) => { - Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause) + SendError::Handshake(status) => { + Self::with(ErrorCode::HttpWebsocketRefused, detail, "status", &status.to_string()) } + // The cause's own words: « Erreur réseau » alone tells nothing. + SendError::Network(cause) => Self::with(ErrorCode::HttpNetwork, detail, "cause", &cause), SendError::SocketScheme { twin } => { let refused = Self::new(ErrorCode::HttpWebsocketScheme, detail); match twin { @@ -74,11 +65,7 @@ impl From for AppError { None => refused, } } - SendError::Header { - name, - fault, - set_by, - } => { + SendError::Header { name, fault, set_by } => { let code = match fault { HeaderFault::Name => ErrorCode::HttpHeaderName, HeaderFault::Value => ErrorCode::HttpHeaderValue, @@ -107,12 +94,8 @@ impl From for AppError { match error { ScriptError::Stopped(stop) => { - let mut refused = Self::with( - ErrorCode::HttpScript, - detail, - "failure", - &stop.kind.to_string(), - ); + let mut refused = + Self::with(ErrorCode::HttpScript, detail, "failure", &stop.kind.to_string()); for (key, value) in [ ("level", stop.level.map(|level| level.to_string())), ("name", stop.name), @@ -131,19 +114,11 @@ impl From for AppError { } ScriptError::Skipped => Self::new(ErrorCode::HttpScriptSkipped, detail), ScriptError::File(path) => Self::with(ErrorCode::HttpScriptFile, detail, "path", &path), - ScriptError::Method(method) => { - Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method) + ScriptError::Method(method) => Self::with(ErrorCode::HttpScriptMethod, detail, "method", &method), + ScriptError::Protected { method, environment } => { + Self::with(ErrorCode::HttpScriptProtected, detail, "method", &method.to_string()) + .and("environment", &environment) } - ScriptError::Protected { - method, - environment, - } => Self::with( - ErrorCode::HttpScriptProtected, - detail, - "method", - &method.to_string(), - ) - .and("environment", &environment), } } } diff --git a/crates/engine/src/http/extract.rs b/crates/engine/src/http/extract.rs index a802e2e01..2031d7f6c 100644 --- a/crates/engine/src/http/extract.rs +++ b/crates/engine/src/http/extract.rs @@ -105,11 +105,7 @@ pub fn variable_name_of(path: &str) -> String { name.push(c); } } - if name.starts_with(|c: char| c.is_ascii_alphabetic()) { - name - } else { - format!("value{name}") - } + if name.starts_with(|c: char| c.is_ascii_alphabetic()) { name } else { format!("value{name}") } } /// What a key reads as when it holds something to keep out of sight. @@ -147,72 +143,96 @@ pub fn looks_secret(path: &str) -> bool { mod tests { use super::*; + const ANSWER: &str = r#"{"access_token":"t0k3n","items":[{"id":7},{"id":8}],"a key":"spaced","it's":"quoted","back\\slash":"b","nested":{"ok":true}}"#; + + /// A text as it is, anything else as JSON; a key with a space or a quote reached between + /// quotes. #[test] - fn a_name_is_proposed_from_the_last_key_in_camel_case() { - assert_eq!(variable_name_of("body.access_token"), "accessToken"); - assert_eq!(variable_name_of("body.data['user-id']"), "userId"); - assert_eq!(variable_name_of("body.items[0]"), "value"); - assert_eq!(variable_name_of("body.Id"), "id"); - assert_eq!(variable_name_of("body['2fa']"), "value2fa"); + fn a_value_is_read_at_its_path() { + for (path, value) in [ + ("body.access_token", "t0k3n"), + (" body.items[1].id ", "8"), + ("body['a key']", "spaced"), + ("body['it\\'s']", "quoted"), + ("body['back\\\\slash']", "b"), + ("body.nested", "{\"ok\":true}"), + ("body.nested.ok", "true"), + ] { + assert_eq!(extract(ANSWER, path).as_deref(), Some(value), "{path}"); + } + assert_eq!(extract("[1,2]", "body").as_deref(), Some("[1,2]")); } + /// The variable is then left as it was. #[test] - fn a_key_that_reads_as_a_secret_is_proposed_as_one() { + fn a_path_leading_nowhere_or_an_answer_not_json_reads_nothing() { for path in [ - "body.access_token", - "body.password", - "body.apiKey", - "body.api_key", - "body['x-key']", - "body.key", + "body.missing", + "body.items[5].id", + "body.items.id", + "access_token", + "body.", + "body..x", + "body[one]", + "body[0", + "body['open", + "body['a key'", ] { - assert!(looks_secret(path), "{path}"); - } - for path in ["body.keyboard", "body.monkey", "body.id", "body.items[0]"] { - assert!(!looks_secret(path), "{path}"); + assert_eq!(extract(ANSWER, path), None, "{path}"); } + assert_eq!(extract("not json", "body"), None); + assert_eq!(extract(r#"{"":{"x":1}}"#, "body..x"), None); } + /// What the response's explorer writes, as a rule reads it. #[test] - fn the_explorer_s_path_becomes_a_rule_s() { + fn the_explorer_s_path_reads_from_the_body() { assert_eq!(body_path("$.data.token"), "body.data.token"); assert_eq!(body_path("$['a key']"), "body['a key']"); - assert_eq!(body_path("body.id"), "body.id"); + assert_eq!(body_path("body.x"), "body.x"); } - const LOGIN: &str = r#"{"access_token":"eyJ.a.b","expires_in":3600,"scope":null, - "user":{"roles":["admin","billing"],"a key":{"it's":true}}}"#; - + /// Its key in camelCase; a name that would not start with a letter is prefixed; an index or + /// a bare body proposes `value`. #[test] - fn reads_a_value_down_its_path_a_text_as_it_is_the_rest_as_json() { - assert_eq!( - extract(LOGIN, "body.access_token").as_deref(), - Some("eyJ.a.b") - ); - assert_eq!(extract(LOGIN, "body.expires_in").as_deref(), Some("3600")); - assert_eq!(extract(LOGIN, "body.scope").as_deref(), Some("null")); - assert_eq!( - extract(LOGIN, "body.user.roles[1]").as_deref(), - Some("billing") - ); - assert_eq!( - extract(LOGIN, "body.user.roles").as_deref(), - Some(r#"["admin","billing"]"#) - ); - assert_eq!( - extract(LOGIN, r"body.user['a key']['it\'s']").as_deref(), - Some("true") - ); - assert_eq!(extract("[1,2]", "body[0]").as_deref(), Some("1")); + fn a_value_is_proposed_a_name_from_its_key() { + for (path, name) in [ + ("body.access_token", "accessToken"), + ("body['x-request-id']", "xRequestId"), + ("body['a key']", "aKey"), + ("body.Token", "token"), + ("body.userID", "userID"), + ("body['2fa']", "value2fa"), + ("body['__']", "value"), + ("body.items[0]", "value"), + ("body", "value"), + ] { + assert_eq!(variable_name_of(path), name, "{path}"); + } } + /// A key that reads as a token, a password or a key; `key` as a word, not inside one. #[test] - fn a_path_that_no_longer_reads_gives_nothing() { - assert_eq!(extract(LOGIN, "body.refresh_token"), None); - assert_eq!(extract(LOGIN, "body.user.roles[7]"), None); - assert_eq!(extract(LOGIN, "body..x"), None); - assert_eq!(extract(LOGIN, "headers.x"), None); - assert_eq!(extract(LOGIN, "body['open"), None); - assert_eq!(extract("", "body.x"), None); + fn a_key_reading_as_a_secret_is_proposed_as_one() { + for (path, secret) in [ + ("body.access_token", true), + ("body.Password", true), + ("body.pwd", true), + ("body.client_secret", true), + ("body.sessionId", true), + ("body['Set-Cookie']", true), + ("body.key", true), + ("body.api_key", true), + ("body['api-key']", true), + ("body.apiKey", true), + ("body.monkey", false), + ("body.keyboard", false), + ("body.APIKey", false), + ("body.id", false), + ("body.items[0]", false), + ("not a path", false), + ] { + assert_eq!(looks_secret(path), secret, "{path}"); + } } } diff --git a/crates/engine/src/http/flight.rs b/crates/engine/src/http/flight.rs index 30e1ef108..0736b22d3 100644 --- a/crates/engine/src/http/flight.rs +++ b/crates/engine/src/http/flight.rs @@ -8,16 +8,15 @@ use chrono::Utc; use super::scripts::around::{self, Around}; use super::scripts::model::{ - Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, - ScriptError, ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, - WriteScope, + Extracted, FailureKind, Job, LayerScope, LogEntry, Outcome, Phase, RequestFault, Script, ScriptError, + ScriptFailure, ScriptInfo, ScriptLayer, ScriptRequest, ScriptStop, VariableWrite, WriteScope, }; use super::scripts::network::{self, Network}; use super::scripts::process::ScriptProcess; use super::scripts::session::Session; use super::{ - console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, - send, settings, store, transport, variables, + console, cookies, environments, extract, history, inherited_of, layers_for, model, runner, send, + settings, store, transport, variables, }; use crate::db::{self, lock, lock_library}; use crate::error::AppError; @@ -93,10 +92,7 @@ impl Flight { confirmed: false, files: Vec::new(), collection_id: None, - info: ScriptInfo { - iteration_count: 1, - ..ScriptInfo::default() - }, + info: ScriptInfo { iteration_count: 1, ..ScriptInfo::default() }, by: environments::FilledBy::default(), heard: (Vec::new(), Vec::new()), record: true, @@ -110,10 +106,7 @@ impl Flight { } } - pub(super) async fn send( - &mut self, - request: send::SendRequest, - ) -> Result { + pub(super) async fn send(&mut self, request: send::SendRequest) -> Result { let send::SendRequest { id, kind, @@ -127,20 +120,8 @@ impl Flight { confirmed, files, } = request; - let Prepared { - inherited, - mut layers, - environment, - jar, - library, - } = prepare( - &self.engine, - &document, - collection_id.clone(), - folder_id, - environment_id, - ) - .await?; + let Prepared { inherited, mut layers, environment, jar, library } = + prepare(&self.engine, &document, collection_id.clone(), folder_id, environment_id).await?; let around = Around::of(&document.scripts, &name, &inherited); self.jar = jar; self.library = library; @@ -153,12 +134,7 @@ impl Flight { self.layered(&mut layers); // What the request reads as the user wrote it: a file the scripts add waits for a yes. let own = (!around.before.is_empty()).then(|| files_read(&document, &inherited, &layers)); - let mut going = Going { - kind, - method, - document, - layers, - }; + let mut going = Going { kind, method, document, layers }; if !around.before.is_empty() { self.before(&around.before, &mut going).await?; } @@ -215,10 +191,8 @@ impl Flight { fn named(&mut self, name: &str, request_id: Option<&str>) { self.info.request_name = name.to_string(); self.info.request_id = request_id.map(str::to_string); - self.by = environments::FilledBy { - request_id: request_id.map(str::to_string), - name: name.to_string(), - }; + self.by = + environments::FilledBy { request_id: request_id.map(str::to_string), name: name.to_string() }; } /// What a run lays over the levels read: what its scripts wrote, kept for it alone, and @@ -231,12 +205,10 @@ impl Flight { } fn sent_environment(&self) -> Option { - self.environment - .as_ref() - .map(|environment| history::SentEnvironment { - name: environment.name.clone(), - colour: environment.colour, - }) + self.environment.as_ref().map(|environment| history::SentEnvironment { + name: environment.name.clone(), + colour: environment.colour, + }) } /// The request sent, the lock free; `Err` alone when « Annuler » stopped it, a failure to @@ -246,11 +218,7 @@ impl Flight { id: &str, outgoing: send::Outgoing, ) -> Result, AppError> { - let (answer, cookies_set) = self - .engine - .sending - .run(&self.engine.runtime, id, outgoing) - .await; + let (answer, cookies_set) = self.engine.sending.run(&self.engine.runtime, id, outgoing).await; if matches!(answer, Err(send::SendError::Cancelled)) { return Err(send::SendError::Cancelled.into()); } @@ -260,11 +228,9 @@ impl Flight { Utc::now(), match &answer { Ok(response) => console::answered(response, None), - Err(error) => console::ConsoleLine::Failed { - code: error.code, - params: error.params.clone(), - by: None, - }, + Err(error) => { + console::ConsoleLine::Failed { code: error.code, params: error.params.clone(), by: None } + } }, ); Ok(answer) @@ -287,18 +253,11 @@ impl Flight { let finished = outcome.is_some(); if let Some(outcome) = outcome { let extractions = std::mem::take(&mut going.document.extractions); - response.scripts.extracted = self - .extract(&extractions, response, &mut going.layers) - .await; + response.scripts.extracted = self.extract(&extractions, response, &mut going.layers).await; // Said once the extractions ran: a value one makes a secret is hidden in the logs. self.report(&answered, &outcome, &going.layers); self.follow(&outcome); - for missed in response - .scripts - .extracted - .iter() - .filter(|extracted| !extracted.found) - { + for missed in response.scripts.extracted.iter().filter(|extracted| !extracted.found) { self.say( Utc::now(), console::ConsoleLine::Missed { @@ -323,10 +282,7 @@ impl Flight { request: ScriptRequest::of(going.kind, going.method, &going.document), response: None, layers: self.script_layers(going), - environment: self - .environment - .as_ref() - .map(|environment| environment.name.clone()), + environment: self.environment.as_ref().map(|environment| environment.name.clone()), cookies: network::cookies_for(self.jar().as_deref(), url), info: self.info.clone(), } @@ -337,11 +293,7 @@ impl Flight { if !self.data.is_empty() { layers.insert( 0, - ScriptLayer { - scope: LayerScope::Data, - from: String::new(), - values: self.data.clone(), - }, + ScriptLayer { scope: LayerScope::Data, from: String::new(), values: self.data.clone() }, ); } layers @@ -355,10 +307,7 @@ impl Flight { self.write(&outcome.writes, &mut going.layers).await; self.report(scripts, &outcome, &going.layers); self.follow(&outcome); - let refused = self - .session - .as_mut() - .and_then(|session| session.network.refused_file.take()); + let refused = self.session.as_mut().and_then(|session| session.network.refused_file.take()); if let Some(path) = refused { return Err(ScriptError::File(path).into()); } @@ -386,9 +335,7 @@ impl Flight { .into()); } if !outcome.locals.is_empty() { - going - .layers - .insert(0, around::locals_layer(&outcome.locals)); + going.layers.insert(0, around::locals_layer(&outcome.locals)); } Ok(()) } @@ -408,10 +355,7 @@ impl Flight { let outcome = self.run(job).await.ok()?; self.write(&outcome.writes, &mut going.layers).await; response.scripts.tests.clone_from(&outcome.tests); - response.scripts.failure = outcome - .failure - .as_ref() - .map(|failure| ScriptStop::of(failure, scripts)); + response.scripts.failure = outcome.failure.as_ref().map(|failure| ScriptStop::of(failure, scripts)); Some(outcome) } @@ -426,10 +370,7 @@ impl Flight { self.transport, self.jar.take(), self.confirmed - || !self - .environment - .as_ref() - .is_some_and(|environment| environment.protected), + || !self.environment.as_ref().is_some_and(|environment| environment.protected), ); network.files.clone_from(&self.files); Session::new(host, network) @@ -451,10 +392,7 @@ impl Flight { let outcome = match ran { Ok((mut session, outcome)) => { self.changes.append(&mut session.network.changes); - self.heard = ( - std::mem::take(&mut session.logs), - std::mem::take(&mut session.network.sent), - ); + self.heard = (std::mem::take(&mut session.logs), std::mem::take(&mut session.network.sent)); self.session = Some(session); outcome } @@ -475,11 +413,7 @@ impl Flight { response: &send::SentResponse, layers: &mut [variables::VariableLayer], ) -> Vec { - let scope = if self.environment.is_some() { - WriteScope::Environment - } else { - WriteScope::Globals - }; + let scope = if self.environment.is_some() { WriteScope::Environment } else { WriteScope::Globals }; let mut writes = Vec::new(); let extracted = extractions .iter() @@ -516,11 +450,7 @@ impl Flight { /// What the send did to the jar, for the scripts after it to read. fn received(&mut self, changes: Vec) { - if let Some(jar) = self - .session - .as_mut() - .and_then(|session| session.network.jar.as_mut()) - { + if let Some(jar) = self.session.as_mut().and_then(|session| session.network.jar.as_mut()) { cookies::apply(jar, &changes); } self.changes.extend(changes); @@ -550,12 +480,7 @@ impl Flight { /// What the last phase logged and sent, the tests that failed and what stopped it, each /// secret in force — those the phase wrote included — written as its name. - fn report( - &mut self, - scripts: &[Script], - outcome: &Outcome, - layers: &[variables::VariableLayer], - ) { + fn report(&mut self, scripts: &[Script], outcome: &Outcome, layers: &[variables::VariableLayer]) { let (logs, sends) = std::mem::take(&mut self.heard); let secrets = variables::Resolver::new(layers).secrets(); for (at, line) in console::phase(logs, sends, outcome, scripts, &secrets) { @@ -574,10 +499,7 @@ impl Flight { return; } let writes = writes.to_vec(); - let environment_id = self - .environment - .as_ref() - .map(|environment| environment.id.clone()); + let environment_id = self.environment.as_ref().map(|environment| environment.id.clone()); let collection_id = self.collection_id.clone(); let by = self.by.clone(); let library = self.library; @@ -607,13 +529,7 @@ impl Flight { /// The history and the jar, written under the lock again, and never at the answer's expense. pub(super) async fn keep(self) { - let Self { - engine, - library, - sent, - changes, - .. - } = self; + let Self { engine, library, sent, changes, .. } = self; if sent.is_none() && changes.is_empty() { return; } @@ -626,23 +542,14 @@ impl Flight { }; if let Some(sent) = &sent { let (summary, record) = history::record_of(sent); - history::store::record( - &mut connection, - sent.request_id.as_deref(), - &summary, - &record, - now, - )?; + history::store::record(&mut connection, sent.request_id.as_deref(), &summary, &record, now)?; } cookies::store::apply(&mut connection, &changes, now)?; Ok(()) }) .await; if let Err(error) = kept { - log::warn!( - "A send's history or cookies were not kept: {}", - error.for_log() - ); + log::warn!("A send's history or cookies were not kept: {}", error.for_log()); engine.emit(EngineEvent::SendNotKept); } } @@ -678,11 +585,7 @@ async fn prepare( db::run(Arc::clone(engine), move |engine| { let db = &engine.db; let mut connection = lock(db)?; - let inherited = inherited_of( - &mut connection, - collection_id.as_deref(), - folder_id.as_deref(), - )?; + let inherited = inherited_of(&mut connection, collection_id.as_deref(), folder_id.as_deref())?; let layers = layers_for(&mut connection, &own, &inherited, environment_id.as_deref())?; let environment = environment_id .as_deref() @@ -695,13 +598,7 @@ async fn prepare( } else { None }; - Ok(Prepared { - inherited, - layers, - environment, - jar, - library: connection.number(), - }) + Ok(Prepared { inherited, layers, environment, jar, library: connection.number() }) }) .await } @@ -734,27 +631,17 @@ fn keep_writes( } if wrote_to(WriteScope::Globals) { let globals = environments::store::list(connection)?.globals; - let globals = around::written( - &globals, - around::writes_to(writes, WriteScope::Globals), - Some(by), - ); + let globals = around::written(&globals, around::writes_to(writes, WriteScope::Globals), Some(by)); environments::store::save_globals(connection, &globals, Utc::now())?; wrote = true; } if let Some(id) = collection_id && wrote_to(WriteScope::Collection) { - let item = model::HttpItem { - kind: model::HttpItemKind::Collection, - id: id.to_string(), - }; + let item = model::HttpItem { kind: model::HttpItemKind::Collection, id: id.to_string() }; let mut held = store::settings(connection, &item)?; - held.variables = around::written( - &held.variables, - around::writes_to(writes, WriteScope::Collection), - Some(by), - ); + held.variables = + around::written(&held.variables, around::writes_to(writes, WriteScope::Collection), Some(by)); store::save_settings(connection, &item, &held)?; wrote = true; } diff --git a/crates/engine/src/http/graphql.rs b/crates/engine/src/http/graphql.rs index ada327de8..153a8415d 100644 --- a/crates/engine/src/http/graphql.rs +++ b/crates/engine/src/http/graphql.rs @@ -117,8 +117,7 @@ impl Reader<'_> { } fn word(&mut self) -> String { - std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')) - .collect() + std::iter::from_fn(|| self.next_if(|next| next.is_ascii_alphanumeric() || next == '_')).collect() } fn skip_spaces(&mut self) { @@ -164,11 +163,7 @@ impl Reader<'_> { /// One pass over a query, past its strings and comments: its operations with what each /// declares, and the first brace, parenthesis or string that does not pair. fn scan(query: &str) -> Scanned { - let mut reader = Reader { - chars: query.chars().peekable(), - line: 1, - column: 1, - }; + let mut reader = Reader { chars: query.chars().peekable(), line: 1, column: 1 }; let mut scanned = Scanned::default(); // What is open, and where it was opened. let mut open: Vec<(char, u32, u32)> = Vec::new(); @@ -177,11 +172,7 @@ fn scan(query: &str) -> Scanned { // The depth at which the operation being read declares its variables. let mut declaring: Option = None; let fault = |scanned: &mut Scanned, fault, line, column| { - scanned.problem.get_or_insert(QueryProblem { - fault, - line, - column, - }); + scanned.problem.get_or_insert(QueryProblem { fault, line, column }); }; while let Some((read, line, column)) = reader.next() { @@ -209,11 +200,8 @@ fn scan(query: &str) -> Scanned { if open.last().is_some_and(|(opened, ..)| *opened == pair) { open.pop(); } else { - let stray = if read == '}' { - QueryFault::StrayBrace - } else { - QueryFault::StrayParenthesis - }; + let stray = + if read == '}' { QueryFault::StrayBrace } else { QueryFault::StrayParenthesis }; fault(&mut scanned, stray, line, column); } if declaring.is_some_and(|depth| open.len() < depth) { @@ -223,10 +211,7 @@ fn scan(query: &str) -> Scanned { '$' if declaring == Some(open.len()) => { let name = reader.word(); if let (Some(operation), false) = (scanned.operations.last_mut(), name.is_empty()) { - operation.variables.push(Variable { - name, - has_default: false, - }); + operation.variables.push(Variable { name, has_default: false }); } } '=' if declaring == Some(open.len()) => { @@ -259,36 +244,20 @@ fn scan(query: &str) -> Scanned { } // Left open at the end: the innermost, the one nearest to where the typing stopped. if let Some((opened, line, column)) = open.last().copied() { - let unclosed = if opened == '{' { - QueryFault::UnclosedBrace - } else { - QueryFault::UnclosedParenthesis - }; + let unclosed = + if opened == '{' { QueryFault::UnclosedBrace } else { QueryFault::UnclosedParenthesis }; fault(&mut scanned, unclosed, line, column); } scanned } -/// The names of the document's operations, read past strings, comments and selections. -pub fn operations(query: &str) -> Vec { - scan(query) - .operations - .into_iter() - .filter_map(|operation| operation.name) - .collect() -} - /// The operation a send runs: the one named, or the first as the server takes it. fn sent<'a>(operations: &'a [Operation], document: &GraphqlDocument) -> Option<&'a Operation> { document .operation_name .as_deref() .filter(|name| !name.is_empty()) - .and_then(|name| { - operations - .iter() - .find(|operation| operation.name.as_deref() == Some(name)) - }) + .and_then(|name| operations.iter().find(|operation| operation.name.as_deref() == Some(name))) .or_else(|| operations.first()) } @@ -306,10 +275,8 @@ fn given(variables: &str) -> Option> { pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { let scanned = scan(&document.query); let (mut missing, mut unknown) = (Vec::new(), Vec::new()); - if let (Some(operation), Some(given)) = ( - sent(&scanned.operations, document), - given(&document.variables), - ) { + if let (Some(operation), Some(given)) = (sent(&scanned.operations, document), given(&document.variables)) + { missing = operation .variables .iter() @@ -318,20 +285,11 @@ pub fn describe(document: &GraphqlDocument) -> GraphqlAnswer { .collect(); unknown = given .into_iter() - .filter(|key| { - !operation - .variables - .iter() - .any(|variable| &variable.name == key) - }) + .filter(|key| !operation.variables.iter().any(|variable| &variable.name == key)) .collect(); } GraphqlAnswer { - operations: scanned - .operations - .into_iter() - .filter_map(|operation| operation.name) - .collect(), + operations: scanned.operations.into_iter().filter_map(|operation| operation.name).collect(), variables_problem: if document.variables.trim().is_empty() { None } else { @@ -388,11 +346,7 @@ pub(crate) fn body(document: &GraphqlDocument, variables: Option<&str>) -> Strin body.push_str(",\"variables\":"); body.push_str(variables); } - if let Some(name) = document - .operation_name - .as_deref() - .filter(|name| !name.is_empty()) - { + if let Some(name) = document.operation_name.as_deref().filter(|name| !name.is_empty()) { body.push_str(",\"operationName\":"); body.push_str("ed(name)); } @@ -475,204 +429,174 @@ pub fn result(body: &str) -> Option { mod tests { use super::*; + fn document(query: &str, variables: &str, operation: Option<&str>) -> GraphqlDocument { + GraphqlDocument { + query: query.to_string(), + variables: variables.to_string(), + operation_name: operation.map(ToString::to_string), + as_get: false, + } + } + + fn problem(query: &str) -> Option<(QueryFault, u32, u32)> { + describe(&document(query, "", None)) + .query_problem + .map(|problem| (problem.fault, problem.line, problem.column)) + } + + /// Named ones, in the order written, read past strings, comments and selections; an + /// anonymous one or the shorthand has no name to list. #[test] - fn the_named_operations_are_read_past_strings_comments_and_selections() { + fn the_operations_of_a_document_are_read_in_order() { let query = r#" # query Commented { x } - query Invoices($first: Int) { invoices(first: $first, note: "mutation Fake") { id } } - mutation Pay { pay { id } } - { anonymous } - subscription - Ticks { tick } + query Orders($first: Int) { orders(note: "mutation Fake { }") { id } } + fragment Fields on Order { id } + mutation Pay { pay } + subscription Ticks { tick } + query { anonymous } + { shorthand } "#; - assert_eq!(operations(query), ["Invoices", "Pay", "Ticks"]); - assert!(operations("{ me { id } }").is_empty()); - assert_eq!(scan(query).problem, None); - // A block string runs over lines, quotes and braces included. - let described = r#" - """ - Says "hello" { and more - """ - query Greeting { hello(note: "a \" b") } - "#; - assert_eq!(operations(described), ["Greeting"]); - assert_eq!(scan(described).problem, None); + let named = scan(query).operations.into_iter().filter_map(|operation| operation.name); + assert_eq!(named.collect::>(), ["Orders", "Pay", "Ticks"]); } - fn document(query: &str, variables: &str) -> GraphqlDocument { - GraphqlDocument { - query: query.to_string(), - variables: variables.to_string(), - ..GraphqlDocument::default() + /// Said where it is typed — the sign at fault, by line and column from 1 — and the first + /// one only; what is left open at the end is the innermost. + #[test] + fn a_sign_the_query_leaves_unpaired_is_said_where_it_stands() { + for (query, expected) in [ + ("{ a { b }", Some((QueryFault::UnclosedBrace, 1, 1))), + ("query Q {\n a(x: 1 {\n}", Some((QueryFault::UnclosedParenthesis, 2, 4))), + ("{ a(x: \"open) }", Some((QueryFault::UnclosedString, 1, 8))), + ("{ a }\n}", Some((QueryFault::StrayBrace, 2, 1))), + ("{ a(x: 1}) }", Some((QueryFault::StrayBrace, 1, 9))), + ("{ a ) }", Some((QueryFault::StrayParenthesis, 1, 5))), + ("{ a(x: \"\"\"one\ntwo \\\"\"\" three\"\"\") }", None), + ("{ a(x: \"\"\"never closed) }", Some((QueryFault::UnclosedString, 1, 8))), + ("{ a(x: \"quote \\\" inside\") } # } stray in a comment", None), + ("{ a(x: \"\") }", None), + ] { + assert_eq!(problem(query), expected, "{query:?}"); } } - /// A query missing a brace was sent without a word, and answered by a 400. + /// What the operation sent declares without a default and the variables give no value; the + /// keys given that it does not declare. #[test] - fn a_brace_a_parenthesis_or_a_string_left_open_is_said_with_its_place() { - let problem = |query: &str| { - scan(query) - .problem - .map(|found| (found.fault, found.line, found.column)) - }; + fn the_variables_say_what_the_operation_lacks_and_what_it_does_not_take() { + let query = "query Orders($first: Int = 10, $after: String, $status: Status!) { orders { id } }"; - assert_eq!( - problem("query {\n viewer {\n login\n }\n"), - Some((QueryFault::UnclosedBrace, 1, 7)) - ); - // The innermost one, nearest to where the typing stopped. - assert_eq!( - problem("{ viewer {\n repos(first: 3 {"), - Some((QueryFault::UnclosedBrace, 2, 18)) - ); - assert_eq!( - problem("{ user(id: 1 }"), - Some((QueryFault::StrayBrace, 1, 14)) - ); - assert_eq!( - problem("{ user(id: 1) ) }"), - Some((QueryFault::StrayParenthesis, 1, 15)) - ); - assert_eq!(problem("{ user }\n}"), Some((QueryFault::StrayBrace, 2, 1))); - assert_eq!( - problem("{ search(text: \"open) { id }\n}"), - Some((QueryFault::UnclosedString, 1, 16)) - ); - assert_eq!( - problem("{ a }\n\"\"\"never closed"), - Some((QueryFault::UnclosedString, 2, 1)) - ); - assert_eq!( - problem("{ user(id: 1"), - Some((QueryFault::UnclosedParenthesis, 1, 7)) - ); - // A sign in a comment or in a string pairs with nothing. - assert_eq!(problem("{ a(note: \"}\") } # }"), None); - assert_eq!(problem(""), None); + let answer = describe(&document(query, r#"{"status": "PAID", "extra": 1}"#, None)); + + assert_eq!(answer.operations, ["Orders"]); + assert_eq!(answer.missing, ["after"]); + assert_eq!(answer.unknown, ["extra"]); + assert_eq!((answer.variables_problem, answer.query_problem), (None, None)); } - /// The variables were typed after the query, in its box: nothing said what goes where. + /// The operation named, or the first as the server takes it; a variable used in a selection + /// or an argument is no declaration. #[test] - fn the_variables_an_operation_declares_are_compared_with_those_given() { - let query = r" - query Country($code: ID!, $first: Int = 10, $after: String) { - country(code: $code) { cities(first: $first, after: $after) { name } } - } - mutation Rename($id: ID!, $name: String!) { rename(id: $id, name: $name) { id } } - "; - let said = |variables: &str, operation: Option<&str>| { - let answer = describe(&GraphqlDocument { - operation_name: operation.map(str::to_string), - ..document(query, variables) - }); - (answer.missing, answer.unknown) - }; - let names = |names: &[&str]| names.iter().map(ToString::to_string).collect::>(); - - // Without a default and without a value; the first operation when none is named. - assert_eq!(said("", None), (names(&["code", "after"]), names(&[]))); - assert_eq!( - said(r#"{ "code": "FR", "page": 2 }"#, None), - (names(&["after"]), names(&["page"])) - ); - assert_eq!( - said(r#"{"id": 1}"#, Some("Rename")), - (names(&["name"]), names(&[])) - ); - assert_eq!( - said(r#"{"id": 1}"#, Some("Gone")), - (names(&["code", "after"]), names(&["id"])) - ); - // Not an object as typed: said as that, not as a list of what is missing. - assert_eq!(said("{\"code\":", None), (names(&[]), names(&[]))); - assert_eq!(said("[1]", None), (names(&[]), names(&[]))); - - // The shorthand and a fragment declare nothing; no operation, nothing is compared. - let shorthand = describe(&document( - "fragment F on User { id } { me { ...F } }", - r#"{"a": 1}"#, - )); - assert_eq!( - (shorthand.missing, shorthand.unknown), - (names(&[]), names(&["a"])) - ); - let empty = describe(&document("", r#"{"a": 1}"#)); - assert_eq!((empty.missing, empty.unknown), (names(&[]), names(&[]))); - // A `$variable` used in a selection is not one declared. - let used = describe(&document("query ($a: Int) { x(a: $a, b: $b) }", "")); - assert_eq!(used.missing, names(&["a"])); + fn the_variables_are_judged_against_the_operation_sent() { + let query = "query A($a: Int) { x(v: $inside) }\nquery B($b: Int) { y }"; + + let named = describe(&document(query, "{}", Some("B"))); + let first = describe(&document(query, "{}", None)); + let unknown_name = describe(&document(query, "{}", Some("Nope"))); + let blank_name = describe(&document(query, "{}", Some(""))); + + assert_eq!(named.missing, ["b"]); + for answer in [first, unknown_name, blank_name] { + assert_eq!(answer.missing, ["a"]); + } } + /// Variables that are no object as typed are said for what they are, not as values lacking; + /// none typed is none given. #[test] - fn what_is_missing_is_added_as_null_at_the_end_of_the_object_as_typed() { - let query = "query Country($code: ID!, $after: String) { country(code: $code) { name } }"; - let added = |variables: &str| with_missing(&document(query, variables)); + fn variables_that_do_not_read_are_said_as_such() { + let query = "query Q($id: ID!) { node(id: $id) { id } }"; - assert_eq!(added(""), "{\n \"code\": null,\n \"after\": null\n}"); - assert_eq!(added("{ }"), "{\n \"code\": null,\n \"after\": null\n}"); - assert_eq!( - added("{\n \"n\": 12345678901234567890,\n \"code\": \"FR\"\n}\n"), - "{\n \"n\": 12345678901234567890,\n \"code\": \"FR\",\n \"after\": null\n}" - ); - // Nothing missing, or nothing that reads: left as it is. - let whole = r#"{"code": "FR", "after": null}"#; - assert_eq!(added(whole), whole); - assert_eq!(added("{\"code\":"), "{\"code\":"); + let broken = describe(&document(query, "{\"id\": ", None)); + let array = describe(&document(query, "[1]", None)); + let empty = describe(&document(query, " ", None)); + + assert!(broken.variables_problem.is_some()); + assert!(broken.missing.is_empty() && array.missing.is_empty()); + assert_eq!(array.variables_problem, None); + assert_eq!((empty.variables_problem, empty.missing), (None, vec!["id".to_string()])); } + /// A `null` for each value lacking, written at the end of the object as typed — nothing + /// else of it touched, its numbers least of all — or a new object. #[test] - fn the_body_carries_the_variables_as_typed_and_the_operation_chosen() { - let document = GraphqlDocument { - query: "query A { a }".to_string(), - variables: " {\"id\": 12345678901234567890} ".to_string(), - operation_name: Some("A".to_string()), - as_get: false, - }; + fn the_values_lacking_are_added_as_null_at_the_end_of_the_object() { + let query = "query Q($a: Int, $b: String, $c: Int = 1) { x }"; + + let typed = with_missing(&document(query, "{\n \"big\": 12345678901234567890\n}", None)); + let blank = with_missing(&document(query, "", None)); + let empty = with_missing(&document(query, " { } ", None)); + let whole = with_missing(&document(query, "{\"a\": 1, \"b\": \"x\"}", None)); + + assert_eq!(typed, "{\n \"big\": 12345678901234567890,\n \"a\": null,\n \"b\": null\n}"); + assert_eq!(blank, "{\n \"a\": null,\n \"b\": null\n}"); + assert_eq!(empty, blank); + assert_eq!(whole, "{\"a\": 1, \"b\": \"x\"}"); + } - let variables = variables(&document).unwrap(); - assert_eq!( - body(&document, variables), - r#"{"query":"query A { a }","variables":{"id": 12345678901234567890},"operationName":"A"}"# - ); - assert!( - super::variables(&GraphqlDocument { - variables: "[1]".to_string(), - ..GraphqlDocument::default() - }) - .is_err() - ); - assert!( - describe(&GraphqlDocument { - variables: "{\"a\":".to_string(), - ..GraphqlDocument::default() - }) - .variables_problem - .is_some() - ); + /// Copied as typed, not re-serialised; none typed sends none; anything but an object is + /// refused. + #[test] + fn the_variables_sent_are_the_object_as_typed() { + assert_eq!(variables(&document("", " {\"n\": 1.10} ", None)), Ok(Some("{\"n\": 1.10}"))); + assert_eq!(variables(&document("", " ", None)), Ok(None)); + assert!(variables(&document("", "[1]", None)).is_err()); + assert!(variables(&document("", "{\"a\":", None)).is_err()); } + /// The query quoted, the variables as typed, the operation when one is named. #[test] - fn an_answer_is_read_as_data_and_errors_apart() { - let read = result( - r#"{"data":{"invoice":null,"n":1.10},"errors":[{"message":"Not found","path":["invoices",0,"amount"],"locations":[{"line":3,"column":5}]}]}"#, - ) - .unwrap(); + fn a_post_s_body_carries_the_query_its_variables_and_its_operation() { + let named = document("query Q { \"x\" }", "", Some("Q")); + let unnamed = document("{ x }", "", Some("")); assert_eq!( - read.data.as_deref(), - Some("{\n \"invoice\": null,\n \"n\": 1.10\n}") + body(&named, Some("{\"n\": 1.10}")), + r#"{"query":"query Q { \"x\" }","variables":{"n": 1.10},"operationName":"Q"}"# ); + assert_eq!(body(&unnamed, None), r#"{"query":"{ x }"}"#); + } + + /// `errors` read beside `data`: each message, its path joined and its first location; data + /// laid out, a `null` one being none. + #[test] + fn an_answer_is_read_as_its_data_and_its_errors() { + let answered = result(r#"{"data":{"n":1.10},"errors":[{"message":"denied","path":["orders",0,"total"],"locations":[{"line":3,"column":5},{"line":9,"column":1}]},{"message":"bare","path":[0,true]},{}]}"#).unwrap(); + let null_data = result(r#"{"data":null,"errors":[{"message":"x"}]}"#).unwrap(); + + assert_eq!(answered.data.as_deref(), Some("{\n \"n\": 1.10\n}")); assert_eq!( - read.errors, - [GraphqlError { - message: "Not found".to_string(), - path: Some("invoices[0].amount".to_string()), - location: Some("3:5".to_string()), - }] + answered.errors, + [ + GraphqlError { + message: "denied".to_string(), + path: Some("orders[0].total".to_string()), + location: Some("3:5".to_string()), + }, + GraphqlError { message: "bare".to_string(), path: Some("[0]".to_string()), location: None }, + GraphqlError { message: String::new(), path: None, location: None }, + ] ); - assert_eq!(result(r#"{"data":null,"errors":[]}"#), None); - assert_eq!(result(r#"{"id":7}"#), None); - assert_eq!(result("not json"), None); + assert_eq!(null_data.data, None); + } + + /// No `data` and no `errors`, or no JSON: not a GraphQL answer. + #[test] + fn a_body_with_neither_data_nor_errors_is_no_graphql_answer() { + assert_eq!(result(r#"{"message":"not found"}"#), None); + assert_eq!(result(r#"{"errors":[]}"#), None); + assert_eq!(result(""), None); } } diff --git a/crates/engine/src/http/history.rs b/crates/engine/src/http/history.rs index 2d6973a3c..962ec7240 100644 --- a/crates/engine/src/http/history.rs +++ b/crates/engine/src/http/history.rs @@ -91,9 +91,7 @@ pub fn url_parts(url: &str) -> (String, String) { let end = rest.find(['/', '?', '#']).unwrap_or(rest.len()); let (authority, tail) = rest.split_at(end); // Its credentials are nothing a list has to show. - let host = authority - .rsplit_once('@') - .map_or(authority, |(_, host)| host); + let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host); (host.to_string(), tail.to_string()) } @@ -129,10 +127,7 @@ pub struct Sent { fn is_secret(name: &str, secrets: &[String]) -> bool { let name = name.trim().to_ascii_lowercase(); - matches!( - name.as_str(), - "authorization" | "proxy-authorization" | "cookie" - ) || secrets.contains(&name) + matches!(name.as_str(), "authorization" | "proxy-authorization" | "cookie") || secrets.contains(&name) } /// `Bearer abc` keeps its scheme: what kind of auth left is worth knowing, the token is not. @@ -210,9 +205,7 @@ pub fn mask(exchange: &Exchange, secrets: &[String]) -> Exchange { /// `session=abc; Path=/; HttpOnly` keeps its name and what it is set for. fn masked_set_cookie(value: &str) -> String { - let (pair, attributes) = value - .split_once(';') - .map_or((value, None), |(pair, rest)| (pair, Some(rest))); + let (pair, attributes) = value.split_once(';').map_or((value, None), |(pair, rest)| (pair, Some(rest))); let name = pair.split_once('=').map_or(pair, |(name, _)| name); match attributes { Some(rest) => format!("{name}={MASK};{rest}"), @@ -249,22 +242,14 @@ fn masked_answer(response: &SentResponse, secrets: &[String]) -> SentResponse { ..header.clone() }) .collect(), - cookies: response - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: response.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), redirects: response .redirects .iter() .map(|hop| Redirect { url: masked_url(&hop.url, secrets), from: masked_url(&hop.from, secrets), - cookies: hop - .cookies - .iter() - .map(|cookie| masked_cookie(cookie, secrets)) - .collect(), + cookies: hop.cookies.iter().map(|cookie| masked_cookie(cookie, secrets)).collect(), ..hop.clone() }) .collect(), @@ -294,10 +279,12 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { } let name = header.key.trim().to_ascii_lowercase(); if name == "cookie" { - found.extend(header.value.split(';').filter_map(|pair| { - pair.split_once('=') - .map(|(_, value)| value.trim().to_string()) - })); + found.extend( + header + .value + .split(';') + .filter_map(|pair| pair.split_once('=').map(|(_, value)| value.trim().to_string())), + ); } else { if let Some((_, token)) = header.value.split_once(' ') { found.push(token.trim().to_string()); @@ -309,9 +296,7 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { let query = query.split_once('#').map_or(query, |(query, _)| query); found.extend(query.split('&').filter_map(|pair| { let (key, value) = pair.split_once('=')?; - secrets - .contains(&key.to_ascii_lowercase()) - .then(|| value.to_string()) + secrets.contains(&key.to_ascii_lowercase()).then(|| value.to_string()) })); } // A secret variable is already written as its `{{name}}`, which stays readable. @@ -324,9 +309,8 @@ pub fn sent_secrets(exchange: &Exchange, secrets: &[String]) -> Vec { /// Each value the request sent as a secret, masked wherever the text says it back. #[must_use] pub fn masked_echo(text: &str, sent: &[String]) -> String { - sent.iter().fold(text.to_string(), |text, value| { - text.replace(value.as_str(), MASK) - }) + sent.iter() + .fold(text.to_string(), |text, value| text.replace(value.as_str(), MASK)) } /// A secret variable's value, wherever the answer repeats it — a server echoing a token in its @@ -353,31 +337,21 @@ fn rewritten(response: &SentResponse, hide: impl Fn(&str) -> String) -> SentResp headers: response .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: hide(&response.body), pretty: response.pretty.as_deref().map(&hide), redirects: response .redirects .iter() - .map(|hop| Redirect { - url: hide(&hop.url), - from: hide(&hop.from), - ..hop.clone() - }) + .map(|hop| Redirect { url: hide(&hop.url), from: hide(&hop.from), ..hop.clone() }) .collect(), graphql: response.graphql.as_ref().map(|graphql| GraphqlResult { data: graphql.data.as_deref().map(&hide), errors: graphql .errors .iter() - .map(|error| GraphqlError { - message: hide(&error.message), - ..error.clone() - }) + .map(|error| GraphqlError { message: hide(&error.message), ..error.clone() }) .collect(), }), ..response.clone() @@ -393,10 +367,7 @@ fn hidden_exchange(exchange: &Exchange, secrets: &[(String, String)]) -> Exchang headers: exchange .headers .iter() - .map(|header| KeyValue { - value: hide(&header.value), - ..header.clone() - }) + .map(|header| KeyValue { value: hide(&header.value), ..header.clone() }) .collect(), body: match &exchange.body { SentBody::Text { text } => SentBody::Text { text: hide(text) }, @@ -415,10 +386,7 @@ pub fn shown(exchange: &Exchange, secrets: &[(String, String)]) -> Exchange { /// What is sealed: the request masked, its body and the answer's cut to `BODY_KEPT`. pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { - let mut exchange = mask( - &hidden_exchange(&sent.exchange, &sent.secret_values), - &sent.secrets, - ); + let mut exchange = mask(&hidden_exchange(&sent.exchange, &sent.secret_values), &sent.secrets); if let SentBody::Text { text } = &exchange.body { exchange.body = SentBody::Text { text: cut(text).0 }; } @@ -427,11 +395,7 @@ pub fn record_of(sent: &Sent) -> (HistorySummary, HistoryRecord) { let response = &echo_masked(&hidden_answer(response, &sent.secret_values), &echoed); let (body, shortened) = cut(&response.body); SentResponse { - pretty: if shortened { - None - } else { - response.pretty.clone() - }, + pretty: if shortened { None } else { response.pretty.clone() }, cut: response.cut || shortened, body, exchange: exchange.clone(), @@ -476,17 +440,9 @@ fn draft_url(url: &str) -> String { Some((head, query)) => { let kept: Vec<&str> = query .split('&') - .filter(|pair| { - !pair - .split_once('=') - .is_some_and(|(_, value)| value.starts_with(MASK)) - }) + .filter(|pair| !pair.split_once('=').is_some_and(|(_, value)| value.starts_with(MASK))) .collect(); - if kept.is_empty() { - head.to_string() - } else { - format!("{head}?{}", kept.join("&")) - } + if kept.is_empty() { head.to_string() } else { format!("{head}?{}", kept.join("&")) } } None => url, } @@ -511,10 +467,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { && !header.key.eq_ignore_ascii_case("content-type") && !send::is_default(&header.key, &header.value) }) - .map(|header| KeyValue { - enabled: true, - ..header.clone() - }) + .map(|header| KeyValue { enabled: true, ..header.clone() }) .collect(); let body = match &exchange.body { SentBody::Text { text } if typed.as_deref().is_some_and(|kind| kind.contains("json")) => { @@ -528,13 +481,7 @@ pub fn draft_of(entry: &HistoryEntry) -> HistoryDraft { name: entry.item.summary.name.clone(), kind: RequestKind::Http, method: exchange.method, - document: RequestDocument { - url, - params, - headers, - body, - ..RequestDocument::default() - }, + document: RequestDocument { url, params, headers, body, ..RequestDocument::default() }, }; // A GraphQL send back in its two boxes, when it still reads as one. if entry.item.summary.kind == RequestKind::Graphql @@ -579,10 +526,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { )); } let mut url = Url::parse(&exchange.url).ok()?; - let mut document = GraphqlDocument { - as_get: true, - ..GraphqlDocument::default() - }; + let mut document = GraphqlDocument { as_get: true, ..GraphqlDocument::default() }; let mut kept: Vec<(String, String)> = Vec::new(); for (key, value) in url.query_pairs() { match key.as_ref() { @@ -611,11 +555,7 @@ fn graphql_of(exchange: &Exchange) -> Option<(GraphqlDocument, String)> { /// it has one: never the dots as a value. Set by the auth or handed down, it has no row here, /// and what set it is still there. A header its folder or collection hands down today, with /// the value that was sent, is no change of the request's either. -pub fn onto( - entry: &HistoryEntry, - current: &HttpRequest, - above: &[InheritedHeader], -) -> HistoryDraft { +pub fn onto(entry: &HistoryEntry, current: &HttpRequest, above: &[InheritedHeader]) -> HistoryDraft { let sent = draft_of(entry); let exchange = &entry.record.exchange; let mut document = current.document.clone(); @@ -628,8 +568,7 @@ pub fn onto( }; let handed_down = |header: &KeyValue| { above.iter().any(|known| { - known.header.key.trim().eq_ignore_ascii_case(&header.key) - && known.header.value == header.value + known.header.key.trim().eq_ignore_ascii_case(&header.key) && known.header.value == header.value }) }; document.headers = exchange @@ -645,9 +584,7 @@ pub fn onto( .find(|kept| kept.key == header.key && !handed_down(kept)) // Its description is the request's, which the record never held. .map(|kept| KeyValue { - description: own(&kept.key) - .map(|row| row.description.clone()) - .unwrap_or_default(), + description: own(&kept.key).map(|row| row.description.clone()).unwrap_or_default(), ..kept.clone() }) }) @@ -672,18 +609,13 @@ pub fn onto( } } } - HistoryDraft { - name: current.name.clone(), - kind: current.kind, - method, - document, - } + HistoryDraft { name: current.name.clone(), kind: current.kind, method, document } } /// Retention holds even when the history is never opened. Never fatal. pub fn sweep_at_startup(db: &crate::db::Db) { - let purged = crate::db::lock(db) - .and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); + let purged = + crate::db::lock(db).and_then(|mut connection| store::purge_expired(&mut connection, Utc::now())); if let Err(error) = purged { log::warn!("Expired HTTP history not purged: {error}"); } @@ -694,17 +626,10 @@ pub fn by_day(items: Vec, tz_offset_minutes: i32) -> Vec = Vec::new(); for item in items { - let day = item - .sent_at - .with_timezone(&offset) - .format("%Y-%m-%d") - .to_string(); + let day = item.sent_at.with_timezone(&offset).format("%Y-%m-%d").to_string(); match days.last_mut() { Some(last) if last.day == day => last.items.push(item), - _ => days.push(HistoryDay { - day, - items: vec![item], - }), + _ => days.push(HistoryDay { day, items: vec![item] }), } } days @@ -713,316 +638,333 @@ pub fn by_day(items: Vec, tz_offset_minutes: i32) -> Vec KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } - fn exchange(url: &str, headers: Vec, body: SentBody) -> Exchange { - Exchange { - method: HttpMethod::Post, - url: url.to_string(), - headers, - body, - } + fn text(body: &str) -> SentBody { + SentBody::Text { text: body.to_string() } } - #[test] - fn the_secrets_are_masked_wherever_they_left_and_the_rest_is_kept() { - let masked = mask( - &exchange( - "https://api.exemple.fr/x?page=1&Key=s3cret#top", - vec![ - header("Authorization", "Bearer abc.def"), - header("Cookie", "session=1"), - header("X-Api-Key", "k"), - header("Accept", "application/json"), - ], - SentBody::None, - ), - &["key".to_string(), "x-api-key".to_string()], - ); - - assert_eq!( - masked.url, - "https://api.exemple.fr/x?page=1&Key=••••••••#top" - ); - assert_eq!( - masked - .headers - .iter() - .map(|header| header.value.as_str()) - .collect::>(), - [ - "Bearer ••••••••", - "••••••••", - "••••••••", - "application/json" - ] - ); - } - - fn answered(exchange: Exchange, secrets: &[&str], response: SentResponse) -> Sent { - Sent { - kind: RequestKind::Http, - name: "Login".to_string(), - request_id: None, - exchange, - secrets: secrets.iter().map(ToString::to_string).collect(), - secret_values: Vec::new(), - environment: None, - outcome: Ok(response), - } + fn exchange(url: &str, headers: Vec, body: SentBody) -> Exchange { + Exchange { method: HttpMethod::Post, url: url.to_string(), headers, body } } - fn answer() -> SentResponse { + fn response(body: &str) -> SentResponse { SentResponse { status: 200, reason: "OK".to_string(), millis: 12, - size: 2, - url: String::new(), + size: 34, + url: "https://shop.test/".to_string(), headers: Vec::new(), - body: "{}".to_string(), + body: body.to_string(), binary: false, cut: false, incomplete: false, redirects: Vec::new(), - language: crate::notes::language::Language::Json, + language: Language::Txt, pretty: None, cookies: Vec::new(), - exchange: exchange("https://api.exemple.fr", Vec::new(), SentBody::None), + exchange: exchange("https://shop.test/", Vec::new(), SentBody::None), graphql: None, - scripts: crate::http::scripts::model::ScriptsAnswer::default(), + scripts: ScriptsAnswer::default(), + } + } + + fn sent( + exchange: Exchange, + outcome: Result)>, + ) -> Sent { + Sent { + kind: RequestKind::Http, + name: "Login".to_string(), + request_id: None, + exchange, + secrets: Vec::new(), + secret_values: Vec::new(), + environment: None, + outcome, } } + fn entry(kind: RequestKind, exchange: Exchange) -> HistoryEntry { + let summary = HistorySummary { + name: "Login".to_string(), + url: exchange.url.clone(), + millis: None, + size: None, + failure: None, + failure_params: BTreeMap::new(), + kind, + method: exchange.method, + status: None, + environment: None, + }; + HistoryEntry { + item: HistoryItem { + id: "h-1".to_string(), + sent_at: crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(), + method: exchange.method, + status: None, + request_id: None, + summary, + url_head: String::new(), + url_tail: String::new(), + }, + record: HistoryRecord { exchange, response: None }, + } + } + + fn value_of<'a>(headers: &'a [KeyValue], key: &str) -> &'a str { + &headers.iter().find(|header| header.key == key).unwrap().value + } + + /// What repeats is the host, what tells sends apart follows it; its credentials are not + /// shown, and a text that is no URL is all tail. #[test] - fn what_the_request_sent_as_a_secret_is_found_as_it_was_written() { - let found = sent_secrets( - &exchange( - "https://api.exemple.fr/x?page=1&key=cl3-api#top", - vec![ - header("Authorization", "Bearer jeton-collection"), - header("Cookie", "session=s3ss10n; theme=dark"), - header("Accept", "application/json"), - ], - SentBody::None, - ), - &["key".to_string()], + fn a_url_is_listed_as_its_host_and_what_follows() { + for (url, parts) in [ + ("https://shop.test/orders?page=2", ("shop.test", "/orders?page=2")), + ("https://ada:pw@shop.test:8443#top", ("shop.test:8443", "#top")), + ("https://shop.test", ("shop.test", "")), + ("{{base}}/orders", ("", "{{base}}/orders")), + ] { + let (head, tail) = url_parts(url); + + assert_eq!((head.as_str(), tail.as_str()), parts, "{url}"); + } + } + + /// An auth keeps its scheme, a cookie and the proxy's auth go whole, an API key's header too; + /// the URL keeps its user but not the password, and a key in its query is masked as written. + #[test] + fn a_request_is_kept_without_its_credentials() { + let leaving = exchange( + "https://ada:s3cret@shop.test/a?api_key=k3y&page=2#top", + vec![ + header("Authorization", "Bearer t0k3n"), + header("authorization", "opaque"), + header("Proxy-Authorization", "Basic abc"), + header("Cookie", "sid=abc"), + header("X-Api-Key", "k3y"), + header("Accept", "application/json"), + ], + text("{}"), ); + let kept = mask(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); + + assert_eq!(kept.url, format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2#top")); + let values: Vec<&str> = kept.headers.iter().map(|header| header.value.as_str()).collect(); + assert_eq!(values, [format!("Bearer {MASK}").as_str(), MASK, MASK, MASK, MASK, "application/json"]); + assert_eq!(kept.body, text("{}")); assert_eq!( - found, - [ - "Bearer jeton-collection", - "jeton-collection", - "s3ss10n", - "cl3-api", - "dark" - ] + mask(&exchange("https://shop.test/a", Vec::new(), SentBody::None), &[]).url, + "https://shop.test/a" ); } - /// HRS-11: an echo service sends the request back; the history keeps it masked. + /// What the console shows: each secret in force as its name, an auth or a cookie masked, + /// an API key's header left, the console knowing no key list. #[test] - fn an_answer_that_says_back_the_auth_sent_is_kept_masked() { - let echoed = "{\"headers\":{\"Authorization\":\"Bearer jeton-collection\"}}"; - let sent = answered( - exchange( - "https://echo.exemple.fr/anything", - vec![header("Authorization", "Bearer jeton-collection")], - SentBody::None, - ), - &[], - SentResponse { - body: echoed.to_string(), - pretty: Some(echoed.to_string()), - ..answer() - }, + fn a_request_is_shown_with_its_secrets_as_their_names() { + let leaving = exchange( + "https://shop.test/?t=t0k3n", + vec![header("X-Token", "t0k3n"), header("Authorization", "Bearer t0k3n")], + text("{\"token\":\"t0k3n\"}"), ); - let (_, record) = record_of(&sent); - let kept = record.response.unwrap(); + let shown = shown(&leaving, &[("token".to_string(), "t0k3n".to_string())]); - assert_eq!(kept.body, "{\"headers\":{\"Authorization\":\"••••••••\"}}"); - assert_eq!(kept.pretty, Some(kept.body.clone())); + assert_eq!(shown.url, "https://shop.test/?t={{token}}"); + assert_eq!(value_of(&shown.headers, "X-Token"), "{{token}}"); + assert_eq!(value_of(&shown.headers, "Authorization"), format!("Bearer {MASK}")); + assert_eq!(shown.body, text("{\"token\":\"{{token}}\"}")); } - /// #487: a secret variable is kept as its name — in the request, the answer that echoes - /// it, the URL it went to —, never in clear; and the entry says which environment it left with. + /// What the request sent as a secret, as written, the longest first and once: an auth's + /// token and its whole value, each cookie's value, an API key in a header or the query; a + /// value too short, or already written as its name, is no secret to look for. #[test] - fn a_secret_variable_is_kept_as_its_name_wherever_it_shows() { - let mut sent = answered( - exchange( - "https://api.exemple.fr/v1?key=t0k3n-value", - vec![header("X-Token", "t0k3n-value")], - SentBody::Text { - text: "{\"token\":\"t0k3n-value\"}".to_string(), - }, - ), - &[], - SentResponse { - url: "https://api.exemple.fr/v1?key=t0k3n-value".to_string(), - body: "{\"echo\":\"t0k3n-value\"}".to_string(), - pretty: Some("{\n \"echo\": \"t0k3n-value\"\n}".to_string()), - headers: vec![header("X-Echo", "t0k3n-value")], - ..answer() - }, + fn the_secrets_a_request_sent_are_gathered_to_be_masked_in_the_answer() { + let leaving = exchange( + "https://shop.test/?api_key=k3y-in-url&x=1#api_key=frag", + vec![ + header("Authorization", "Bearer t0k3n"), + header("Cookie", "sid=s1d-value; tiny=ab"), + header("X-Api-Key", "k3y-in-header"), + header("X-Other", "not secret"), + header("Proxy-Authorization", "{{proxy}}"), + ], + SentBody::None, ); - sent.secret_values = vec![("token".to_string(), "t0k3n-value".to_string())]; - sent.environment = Some(SentEnvironment { - name: "Staging".to_string(), - colour: crate::folders::model::FolderColour::Amber, - }); - let (summary, record) = record_of(&sent); + let found = sent_secrets(&leaving, &["x-api-key".to_string(), "api_key".to_string()]); - let kept = serde_json::to_string(&(&summary, &record)).unwrap(); - assert!(!kept.contains("t0k3n-value"), "{kept}"); - assert_eq!(record.exchange.headers[0].value, "{{token}}"); - assert_eq!(summary.url, "https://api.exemple.fr/v1?key={{token}}"); - assert_eq!( - record - .response - .as_ref() - .map(|response| response.body.as_str()), - Some("{\"echo\":\"{{token}}\"}") - ); - assert_eq!( - summary.environment.map(|sent| sent.name), - Some("Staging".to_string()) - ); + assert_eq!(found, ["k3y-in-header", "Bearer t0k3n", "k3y-in-url", "s1d-value", "t0k3n"]); + assert_eq!(masked_echo("echo t0k3n and s1d-value", &found), format!("echo {MASK} and {MASK}")); } - /// One auth a line: whatever kind left, its secret is not in what is kept. + /// ⚠️ What an answer sets is what the next request sends: a `Set-Cookie` keeps its name and + /// what it is set for, a cookie read from it its name; every URL the answer names is the + /// request's own again, a key in its query masked. #[test] - fn every_kind_of_auth_is_masked_in_the_request_that_is_kept() { - let kept = |name: &str, value: &str, secrets: &[&str]| { - let secrets: Vec = secrets.iter().map(ToString::to_string).collect(); - mask( - &exchange("https://x", vec![header(name, value)], SentBody::None), - &secrets, - ) - .headers[0] - .value - .clone() + fn an_answer_is_kept_without_the_cookies_it_sets_or_the_keys_its_urls_carry() { + let mut answer = response("ok"); + answer.url = "https://shop.test/done?api_key=k3y".to_string(); + answer.headers = vec![ + header("Set-Cookie", "sid=abc; Path=/; HttpOnly"), + header("set-cookie", "bare=1"), + header("Location", "https://shop.test/next?api_key=k3y"), + header("Server", "test"), + ]; + let set = Cookie { + name: "sid".to_string(), + value: "abc".to_string(), + from: Some("https://shop.test/login?api_key=k3y".to_string()), + ..Cookie::default() }; + answer.cookies = vec![set.clone()]; + answer.redirects = vec![Redirect { + status: 302, + url: "https://shop.test/done?api_key=k3y".to_string(), + from: "https://shop.test/login?api_key=k3y".to_string(), + cookies: vec![set], + }]; + let mut leaving = sent(exchange("https://shop.test/login", Vec::new(), SentBody::None), Ok(answer)); + leaving.secrets = vec!["api_key".to_string()]; - // Basic and Bearer keep their scheme: what kind of auth left is worth knowing. - assert_eq!( - kept("Authorization", "Basic dXNlcjpodW50ZXIy", &[]), - "Basic ••••••••" - ); - assert_eq!( - kept("authorization", "Bearer eyJhbGciOi", &[]), - "Bearer ••••••••" - ); - // A key in a header goes by the name the request gave it, whatever its case. - assert_eq!(kept("X-Api-Key", "k-123", &["x-api-key"]), "••••••••"); - assert_eq!(kept("X-Api-Key", "k-123", &[]), "k-123"); - assert_eq!( - kept("Proxy-Authorization", "Basic cHJveHk6cHc=", &[]), - "••••••••" - ); - assert_eq!(kept("Cookie", "session=abc; theme=dark", &[]), "••••••••"); + let (_, record) = record_of(&leaving); + + let kept = record.response.unwrap(); + let masked = format!("api_key={MASK}"); + assert!(kept.url.ends_with(&masked)); + assert_eq!(value_of(&kept.headers, "Set-Cookie"), format!("sid={MASK}; Path=/; HttpOnly")); + assert_eq!(value_of(&kept.headers, "set-cookie"), format!("bare={MASK}")); + assert!(value_of(&kept.headers, "Location").ends_with(&masked)); + assert_eq!(value_of(&kept.headers, "Server"), "test"); + assert_eq!((kept.cookies[0].name.as_str(), kept.cookies[0].value.as_str()), ("sid", MASK)); + assert!(kept.cookies[0].from.as_deref().unwrap().ends_with(&masked)); + let hop = &kept.redirects[0]; + assert!(hop.url.ends_with(&masked) && hop.from.ends_with(&masked)); + assert_eq!(hop.cookies[0].value, MASK); } - /// A password typed in the URL itself is as much a secret as one typed under « Auth ». + /// A secret variable's value as its name, wherever the answer repeats it; what the request + /// sent as a secret masked wherever the answer says it back — an echo service does. #[test] - fn a_password_in_the_url_is_masked_and_its_user_kept() { - let masked = |url: &str| mask(&exchange(url, Vec::new(), SentBody::None), &[]).url; - - assert_eq!( - masked("https://ada:hunter2@api.exemple.fr/v1?page=2"), - "https://ada:••••••••@api.exemple.fr/v1?page=2" - ); - // A user alone, an address with a port, a bracketed one: nothing to mask. - assert_eq!( - masked("https://ada@api.exemple.fr/v1"), - "https://ada@api.exemple.fr/v1" - ); - assert_eq!(masked("http://[::1]:8080/x"), "http://[::1]:8080/x"); - assert_eq!( - masked("http://127.0.0.1:8080/a@b"), - "http://127.0.0.1:8080/a@b" + fn an_answer_repeating_a_secret_is_kept_without_it() { + let mut answer = response("{\"token\":\"t0k3n\",\"auth\":\"Bearer abc-123\"}"); + answer.pretty = Some("t0k3n abc-123".to_string()); + answer.headers = vec![header("X-Echo", "abc-123")]; + answer.url = "https://shop.test/?t=t0k3n".to_string(); + answer.redirects = vec![Redirect { + status: 301, + url: "https://shop.test/abc-123".to_string(), + from: "https://shop.test/t0k3n".to_string(), + cookies: Vec::new(), + }]; + answer.graphql = Some(GraphqlResult { + data: Some("{\"me\":\"abc-123\"}".to_string()), + errors: vec![GraphqlError { message: "bad token t0k3n".to_string(), path: None, location: None }], + }); + let mut leaving = sent( + exchange("https://shop.test/", vec![header("Authorization", "Bearer abc-123")], SentBody::None), + Ok(answer), ); - // Reopened as a draft, the dots do not come back as a password. + leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; + + let (_, record) = record_of(&leaving); + + let kept = record.response.unwrap(); + assert_eq!(kept.body, format!("{{\"token\":\"{{{{token}}}}\",\"auth\":\"{MASK}\"}}")); + assert_eq!(kept.pretty.as_deref(), Some(format!("{{{{token}}}} {MASK}").as_str())); + assert_eq!(value_of(&kept.headers, "X-Echo"), MASK); + assert_eq!(kept.url, "https://shop.test/?t={{token}}"); assert_eq!( - draft_url("https://ada:••••••••@api.exemple.fr/v1?page=2"), - "https://ada@api.exemple.fr/v1?page=2" + (kept.redirects[0].url.as_str(), kept.redirects[0].from.as_str()), + (format!("https://shop.test/{MASK}").as_str(), "https://shop.test/{{token}}") ); + let graphql = kept.graphql.unwrap(); + assert_eq!(graphql.data.as_deref(), Some(format!("{{\"me\":\"{MASK}\"}}").as_str())); + assert_eq!(graphql.errors[0].message, "bad token {{token}}"); } - /// The answer names the request's URL again — where it came from, each hop — and sets the - /// cookie the next request sends: each was kept whole beside a request that was masked. + /// What is sealed: the request masked, a secret variable as its name, both bodies cut at + /// `BODY_KEPT` on a character's edge, a body cut no longer laid out; the answer's timeline + /// is the masked request. #[test] - fn what_the_answer_repeats_of_the_secrets_is_masked_too() { - let cookie = |from: Option<&str>| Cookie { - name: "session".to_string(), - value: "abc123".to_string(), - from: from.map(str::to_string), - ..Cookie::default() - }; - let response = SentResponse { - url: "https://api.exemple.fr/home?key=s3cret".to_string(), - headers: vec![ - header("Set-Cookie", "session=abc123; Path=/; HttpOnly"), - header("set-cookie", "bare=zzz"), - header("Location", "/next?key=s3cret&page=1"), - header("Content-Type", "application/json"), - ], - cookies: vec![cookie(None)], - redirects: vec![Redirect { - status: 302, - url: "https://api.exemple.fr/home?key=s3cret".to_string(), - from: "https://ada:hunter2@api.exemple.fr/login?key=s3cret".to_string(), - cookies: vec![cookie(Some("https://api.exemple.fr/login?key=s3cret"))], - }], - ..answer() - }; - let (summary, record) = record_of(&answered( + fn a_send_is_recorded_masked_and_cut() { + let long = format!("{}é", "a".repeat(BODY_KEPT - 1)); + let mut answer = response(&long); + answer.pretty = Some("laid out".to_string()); + let mut leaving = sent( exchange( - "https://ada:hunter2@api.exemple.fr/login?key=s3cret", - Vec::new(), - SentBody::None, + "https://shop.test/?q=t0k3n", + vec![header("Authorization", "Bearer t0k3n")], + text(&long), ), - &["key"], - response, - )); + Ok(answer), + ); + leaving.secret_values = vec![("token".to_string(), "t0k3n".to_string())]; - let written = serde_json::to_string(&(&summary, &record)).unwrap(); - for secret in ["s3cret", "abc123", "hunter2", "zzz"] { - assert!(!written.contains(secret), "{secret} is kept in the history"); - } + let (summary, record) = record_of(&leaving); + + assert_eq!(record.exchange.url, "https://shop.test/?q={{token}}"); + assert_eq!(value_of(&record.exchange.headers, "Authorization"), format!("Bearer {MASK}")); + assert_eq!(record.exchange.body, text(&"a".repeat(BODY_KEPT - 1))); let kept = record.response.unwrap(); - assert_eq!(kept.url, "https://api.exemple.fr/home?key=••••••••"); - assert_eq!( - kept.headers - .iter() - .map(|header| header.value.as_str()) - .collect::>(), - [ - "session=••••••••; Path=/; HttpOnly", - "bare=••••••••", - "/next?key=••••••••&page=1", - "application/json" - ] + assert_eq!(kept.body.len(), BODY_KEPT - 1); + assert!(kept.cut); + assert_eq!(kept.pretty, None); + assert_eq!(kept.exchange, record.exchange); + assert_eq!(summary.url, "https://shop.test/?q={{token}}"); + } + + /// What a list shows: what was sent, how it went, with what environment; a failure as its + /// code and what its sentence states, and no answer. + #[test] + fn a_send_s_summary_says_how_it_went() { + let environment = + SentEnvironment { name: "Prod".to_string(), colour: crate::folders::model::FolderColour::Red }; + let mut answered = + sent(exchange("https://shop.test/", Vec::new(), SentBody::None), Ok(response("ok"))); + answered.kind = RequestKind::Graphql; + answered.environment = Some(environment.clone()); + let params = BTreeMap::from([("delay".to_string(), "30 s".to_string())]); + let failed = sent( + exchange("https://shop.test/", Vec::new(), SentBody::None), + Err((ErrorCode::HttpTimeout, params.clone())), ); - // What it was called and where it applies is not the secret. - assert_eq!(kept.cookies[0].name, "session"); + + let (summary, _) = record_of(&answered); + let (failure, record) = record_of(&failed); + assert_eq!( - kept.redirects[0].from, - "https://ada:••••••••@api.exemple.fr/login?key=••••••••" + summary, + HistorySummary { + name: "Login".to_string(), + url: "https://shop.test/".to_string(), + millis: Some(12), + size: Some(34), + failure: None, + failure_params: BTreeMap::new(), + kind: RequestKind::Graphql, + method: HttpMethod::Post, + status: Some(200), + environment: Some(environment), + } ); assert_eq!( - kept.redirects[0].cookies[0].from.as_deref(), - Some("https://api.exemple.fr/login?key=••••••••") + (failure.failure, failure.failure_params, failure.status), + (Some(ErrorCode::HttpTimeout), params, None) ); + assert_eq!(record.response, None); } /// Its method and its status were columns the migration dropped, and nothing moved them @@ -1040,424 +982,241 @@ mod tests { } /// The limit, asserted rather than left to be discovered: the mask knows the secrets a - /// request declares — its auth, its cookies — not one typed by hand in a parameter or a - /// body. Those are kept, sealed like the rest of the record. + /// request declares — its auth, its cookies, its key — not one typed by hand in a parameter + /// or a body. Those are kept, sealed like the rest of the record. #[test] fn a_secret_typed_by_hand_in_a_parameter_or_a_body_is_kept_as_it_was_sent() { - let (summary, record) = record_of(&answered( - exchange( - "https://api.exemple.fr/x?token=typed-by-hand", - Vec::new(), - SentBody::Text { - text: r#"{"password":"in-the-body"}"#.to_string(), - }, - ), - &[], - answer(), - )); + let by_hand = exchange( + "https://api.exemple.fr/x?token=typed-by-hand", + Vec::new(), + text(r#"{"pin":"in-the-body"}"#), + ); + + let (summary, record) = record_of(&sent(by_hand, Ok(response("")))); assert_eq!(summary.url, "https://api.exemple.fr/x?token=typed-by-hand"); - assert_eq!( - record.exchange.body, - SentBody::Text { - text: r#"{"password":"in-the-body"}"#.to_string() - } - ); + assert_eq!(record.exchange.body, text(r#"{"pin":"in-the-body"}"#)); } + /// A secret is typed again, never replayed as dots: a masked header or query pair goes, the + /// URL's user stays without its password; what is written again by itself goes too — the + /// `Content-Type` the body implies, the application's own headers. #[test] - fn a_record_cuts_long_bodies_and_says_how_it_ended() { - let long = "é".repeat(BODY_KEPT); - let sent = Sent { - kind: RequestKind::Http, - name: "Login".to_string(), - request_id: None, - exchange: exchange( - "https://api.exemple.fr", - Vec::new(), - SentBody::Text { text: long.clone() }, - ), - secrets: Vec::new(), - secret_values: Vec::new(), - environment: None, - outcome: Err(( - ErrorCode::HttpTimeout, - BTreeMap::from([("amount".to_string(), "2".to_string())]), - )), - }; + fn a_send_reopened_is_a_draft_without_what_was_masked() { + let recorded = exchange( + &format!("https://ada:{MASK}@shop.test/a?api_key={MASK}&page=2"), + vec![ + header("Authorization", &format!("Bearer {MASK}")), + header("Content-Type", "application/json; charset=utf-8"), + header("User-Agent", "DevNotes/1.3.0"), + header("Accept", "*/*"), + header("X-Trace", "1"), + ], + text("{\"a\":1}"), + ); + + let draft = draft_of(&entry(RequestKind::Http, recorded)); - let (summary, record) = record_of(&sent); - assert_eq!(summary.failure, Some(ErrorCode::HttpTimeout)); assert_eq!( - summary.failure_params.get("amount").map(String::as_str), - Some("2") + (draft.name.as_str(), draft.kind, draft.method), + ("Login", RequestKind::Http, HttpMethod::Post) ); - assert_eq!((summary.millis, record.response), (None, None)); - let SentBody::Text { text } = record.exchange.body else { - panic!("a text body"); - }; - assert!(text.len() <= BODY_KEPT && long.starts_with(&text)); + assert_eq!(draft.document.url, "https://ada@shop.test/a?page=2"); + let params: Vec<(&str, &str)> = draft + .document + .params + .iter() + .map(|row| (row.key.as_str(), row.value.as_str())) + .collect(); + assert_eq!(params, [("page", "2")]); + assert_eq!(draft.document.headers, [header("X-Trace", "1")]); + assert_eq!(draft.document.body, RequestBody::Json { text: "{\"a\":1}".to_string() }); } + /// A text without a JSON type is text; a file or a multipart was not kept; a query of + /// masked pairs alone leaves no `?`. #[test] - fn an_entry_sent_again_leaves_its_secrets_and_implied_type_behind() { - let entry = HistoryEntry { - item: HistoryItem { - id: "h".to_string(), - sent_at: "2026-10-07T10:00:00Z".parse().unwrap(), - method: HttpMethod::Post, - status: Some(201), - request_id: None, - summary: HistorySummary { - kind: RequestKind::Http, - name: "Payer".to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Post, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), - }, - record: HistoryRecord { - exchange: mask( - &exchange( - "https://api.exemple.fr/pay?page=2&key=s3cret", - vec![ - header("Authorization", "Bearer t"), - header("Accept", "application/json"), - header("Content-Type", "application/json"), - header("User-Agent", "DevNotes/0.10.1"), - header("X-Agent", "DevNotes/0.10.1"), - ], - SentBody::Text { - text: "{\"a\":1}".to_string(), - }, - ), - &["key".to_string()], - ), - response: None, - }, + fn a_draft_s_body_is_what_could_be_kept() { + let body = |sent: SentBody, headers: Vec| { + draft_of(&entry( + RequestKind::Http, + exchange(&format!("https://shop.test/?k={MASK}"), headers, sent), + )) + .document }; - let draft = draft_of(&entry); - assert_eq!( - (draft.name.as_str(), draft.method), - ("Payer", HttpMethod::Post) - ); - assert_eq!(draft.document.url, "https://api.exemple.fr/pay?page=2"); - assert_eq!(draft.document.params.len(), 1); - assert_eq!( - draft - .document - .headers - .iter() - .map(|header| header.key.as_str()) - .collect::>(), - ["Accept", "X-Agent"] - ); + let plain = body(text("hello"), vec![header("Content-Type", "text/plain")]); + + assert_eq!(plain.body, RequestBody::Text { text: "hello".to_string() }); + assert_eq!(plain.url, "https://shop.test/"); + assert_eq!(body(text("{}"), Vec::new()).body, RequestBody::Text { text: "{}".to_string() }); + assert_eq!(body(SentBody::Bytes { size: 3 }, Vec::new()).body, RequestBody::None); assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } + body(SentBody::Multipart { fields: vec!["a".to_string()] }, Vec::new()).body, + RequestBody::None ); } - /// Cut at its end, every URL of a host read `https://httpbin.org/hea…`. + /// Back in its two boxes: a `POST`'s JSON body, its variables laid out; a `GET`'s query + /// pairs, leaving the URL the others. One that no longer reads as GraphQL stays HTTP. #[test] - fn a_url_is_read_in_two_parts_the_host_and_what_tells_two_sends_apart() { - let parts = |url: &str| { - let (head, tail) = url_parts(url); - format!("{head}|{tail}") + fn a_graphql_send_reopens_as_graphql() { + let posted = exchange( + "https://shop.test/graphql", + Vec::new(), + text(r#"{"query":"{ me { id } }","variables":{"id":7},"operationName":"Me"}"#), + ); + let got = Exchange { + method: HttpMethod::Get, + ..exchange( + "https://shop.test/graphql?query=%7B+me+%7D&variables=%7B%22a%22%3A1%7D&v=2", + Vec::new(), + SentBody::None, + ) }; + let unreadable = exchange("https://shop.test/graphql", Vec::new(), text("not json")); + let from_post = draft_of(&entry(RequestKind::Graphql, posted)); + let from_get = draft_of(&entry(RequestKind::Graphql, got)); + let not_graphql = draft_of(&entry(RequestKind::Graphql, unreadable)); + + assert_eq!(from_post.kind, RequestKind::Graphql); + assert_eq!(from_post.document.graphql.query, "{ me { id } }"); + assert_eq!(from_post.document.graphql.variables, "{\n \"id\": 7\n}"); + assert_eq!(from_post.document.graphql.operation_name.as_deref(), Some("Me")); + assert!(!from_post.document.graphql.as_get && from_post.document.body == RequestBody::None); assert_eq!( - parts("https://httpbin.org/redirect/3"), - "httpbin.org|/redirect/3" - ); - assert_eq!( - parts("http://127.0.0.1:8080/users?page=2&key=••••••••#top"), - "127.0.0.1:8080|/users?page=2&key=••••••••#top" + (from_get.document.graphql.query.as_str(), from_get.document.graphql.as_get), + ("{ me }", true) ); - assert_eq!(parts("https://ada:pw@api.exemple.fr"), "api.exemple.fr|"); - assert_eq!(parts("https://api.exemple.fr?x=1"), "api.exemple.fr|?x=1"); - assert_eq!(parts("pas une URL"), "|pas une URL"); + assert_eq!(from_get.document.graphql.variables, "{\n \"a\": 1\n}"); + assert_eq!(from_get.document.url, "https://shop.test/graphql?v=2"); + assert_eq!(not_graphql.kind, RequestKind::Http); } - fn sent(url: &str, headers: Vec, body: SentBody, secrets: &[&str]) -> HistoryEntry { - let secrets: Vec = secrets.iter().map(ToString::to_string).collect(); - HistoryEntry { - item: HistoryItem { - id: "h".to_string(), - sent_at: "2026-10-07T10:00:00Z".parse().unwrap(), - method: HttpMethod::Post, - status: Some(200), - request_id: Some("r".to_string()), - summary: HistorySummary { - kind: RequestKind::Http, - name: "Payer".to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Post, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), - }, - record: HistoryRecord { - exchange: mask(&exchange(url, headers, body), &secrets), - response: None, - }, - } - } - - fn held(kind: RequestKind, document: RequestDocument) -> HttpRequest { + fn current(kind: RequestKind, document: RequestDocument) -> HttpRequest { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); HttpRequest { - id: "r".to_string(), - collection_id: "c".to_string(), + id: "r-1".to_string(), + collection_id: "c-1".to_string(), folder_id: None, - name: "ma req".to_string(), + name: "Saved name".to_string(), kind, method: HttpMethod::Get, document, - created_at: "2026-10-01T00:00:00Z".parse().unwrap(), - updated_at: "2026-10-01T00:00:00Z".parse().unwrap(), + created_at: at, + updated_at: at, } } - /// « Rouvrir » made a stranger of the send; and a mask must never come back as a value. + /// ⚠️ A header kept masked takes the request's own row of that name back — never the dots — + /// or none; one handed down today with the value sent is no change of the request's; a row + /// keeps the request's description. What was sent goes over the request, which keeps its + /// name, its auth and the body a file or a multipart was not kept for. #[test] - fn a_send_goes_back_onto_its_request_with_the_request_s_own_secrets() { - use crate::http::model::{HttpItemKind, KeyPlace, RequestAuth}; - use crate::http::settings::HttpOrigin; - - let entry = sent( - "https://api.exemple.fr/pay?page=2&key=s3cret", - vec![ - header("Authorization", "Bearer old"), - header("X-Token", "s3cret"), - header("X-Client", "web"), - header("X-Trace", "7"), - header("Content-Type", "application/json"), - header("User-Agent", "DevNotes/0.10.1"), - ], - SentBody::Text { - text: "{\"a\":1}".to_string(), - }, - &["key", "x-token"], - ); - let current = held( - RequestKind::Http, - RequestDocument { - url: "https://api.exemple.fr/pay".to_string(), - headers: vec![ - KeyValue { - description: "le jeton du moment".to_string(), - ..header("x-token", "n3w") - }, - KeyValue { - description: "à garder".to_string(), - ..header("X-Trace", "1") - }, - header("X-Gone", "1"), + fn a_send_put_back_onto_its_request_keeps_the_request_s_secrets() { + let recorded = Exchange { + method: HttpMethod::Put, + ..exchange( + "https://shop.test/b?page=3", + vec![ + header("X-Api-Key", MASK), + header("Authorization", &format!("Bearer {MASK}")), + header("X-Tenant", "acme"), + header("X-Trace", "2"), ], - auth: RequestAuth::ApiKey { - name: "key".to_string(), - value: "n3w".to_string(), - place: KeyPlace::Query, - }, - description: "Paie une facture".to_string(), - ..RequestDocument::default() - }, - ); - let above = vec![InheritedHeader { - header: header("x-client", "web"), - from: HttpOrigin { - kind: HttpItemKind::Collection, - id: "c".to_string(), - name: "API".to_string(), + SentBody::Bytes { size: 4 }, + ) + }; + let mine = RequestDocument { + url: "https://shop.test/a".to_string(), + headers: vec![ + KeyValue { description: "the key".to_string(), ..header("x-api-key", "{{key}}") }, + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "1") }, + ], + body: RequestBody::Binary { path: "/dump.bin".to_string() }, + auth: RequestAuth::Bearer { token: "{{token}}".to_string() }, + ..RequestDocument::default() + }; + let above = [InheritedHeader { + header: header("X-Tenant", "acme"), + from: crate::http::settings::HttpOrigin { + kind: crate::http::model::HttpItemKind::Collection, + id: "c-1".to_string(), + name: "Shop".to_string(), }, }]; - let draft = onto(&entry, ¤t, &above); + let put_back = + onto(&entry(RequestKind::Http, recorded), ¤t(RequestKind::Http, mine.clone()), &above); assert_eq!( - (draft.name.as_str(), draft.method), - ("ma req", HttpMethod::Post) + (put_back.name.as_str(), put_back.kind, put_back.method), + ("Saved name", RequestKind::Http, HttpMethod::Put) ); - // The key the auth writes is the auth's still, and no dot is in the URL. - assert_eq!(draft.document.url, "https://api.exemple.fr/pay?page=2"); - assert_eq!(draft.document.params.len(), 1); - assert_eq!(draft.document.auth, current.document.auth); - assert_eq!(draft.document.description, "Paie une facture"); + assert_eq!(put_back.document.url, "https://shop.test/b?page=3"); + assert_eq!(put_back.document.params.len(), 1); assert_eq!( - draft.document.body, - RequestBody::Json { - text: "{\"a\":1}".to_string() - } - ); - // Masked: the request's own row, as it is now. Sent: its value, the row's description. - // Handed down, implied or written by the auth: no row of the request's. - assert_eq!( - draft - .document - .headers - .iter() - .map(|row| ( - row.key.as_str(), - row.value.as_str(), - row.description.as_str() - )) - .collect::>(), - vec![ - ("x-token", "n3w", "le jeton du moment"), - ("X-Trace", "7", "à garder"), + put_back.document.headers, + [ + mine.headers[0].clone(), + KeyValue { description: "which trace".to_string(), ..header("X-Trace", "2") }, ] ); - assert!(!format!("{draft:?}").contains(MASK)); + assert_eq!((&put_back.document.body, &put_back.document.auth), (&mine.body, &mine.auth)); } - /// Reopened as a draft, a GraphQL send was an HTTP `POST` with a JSON body. + /// A text body or none goes over the request's; a GraphQL request takes its query back and + /// keeps its method. #[test] - fn a_send_reopened_as_a_draft_is_of_the_kind_that_was_sent() { - let mut posted = sent( - "https://api.exemple.fr/graphql", - vec![header("X-Trace", "1")], - SentBody::Text { - text: r#"{"query":"{ me }"}"#.to_string(), - }, - &[], - ); - assert_eq!(draft_of(&posted).kind, RequestKind::Http); - - posted.item.summary.kind = RequestKind::Graphql; - let draft = draft_of(&posted); - assert_eq!(draft.kind, RequestKind::Graphql); - assert_eq!(draft.document.graphql.query, "{ me }"); - assert_eq!(draft.document.body, RequestBody::None); - assert_eq!(draft.document.headers.len(), 1); - - // Said to be GraphQL and not reading as one: sent again as what it was on the wire. - let odd = HistoryEntry { - item: posted.item.clone(), - record: HistoryRecord { - exchange: exchange("https://api.exemple.fr/graphql", Vec::new(), SentBody::None), - response: None, - }, + fn a_send_put_back_takes_its_body_or_its_graphql() { + let mine = RequestDocument { + body: RequestBody::Json { text: "{\"old\":1}".to_string() }, + ..RequestDocument::default() }; - assert_eq!(draft_of(&odd).kind, RequestKind::Http); - } - - #[test] - fn a_graphql_send_goes_back_into_its_query_and_variables_and_a_file_is_left_alone() { - let posted = sent( - "https://api.exemple.fr/graphql", - Vec::new(), - SentBody::Text { - text: r#"{"query":"query Me { me }","variables":{"n":12345678901234567890},"operationName":"Me"}"#.to_string(), - }, - &[], - ); - let current = held(RequestKind::Graphql, RequestDocument::default()); - let draft = onto(&posted, ¤t, &[]); - assert_eq!(draft.method, HttpMethod::Get); - assert_eq!(draft.document.url, "https://api.exemple.fr/graphql"); - assert_eq!( - draft.document.graphql, - GraphqlDocument { - query: "query Me { me }".to_string(), - variables: "{\n \"n\": 12345678901234567890\n}".to_string(), - operation_name: Some("Me".to_string()), - as_get: false, - } - ); + let texted = exchange("https://shop.test/", Vec::new(), text("new")); + let posted = exchange("https://shop.test/graphql?x=1", Vec::new(), text(r#"{"query":"{ me }"}"#)); - let got = sent( - "https://api.exemple.fr/graphql?query=%7B%20me%20%7D&variables=%7B%22a%22%3A1%7D&trace=1", - Vec::new(), - SentBody::None, - &[], - ); - let draft = onto(&got, ¤t, &[]); - assert_eq!(draft.document.url, "https://api.exemple.fr/graphql?trace=1"); - assert_eq!(draft.document.graphql.query, "{ me }"); - assert_eq!(draft.document.graphql.variables, "{\n \"a\": 1\n}"); - assert!(draft.document.graphql.as_get); - // What does not read as GraphQL changes nothing of the request's. - let odd = sent( - "https://api.exemple.fr/graphql", - Vec::new(), - SentBody::None, - &[], - ); - assert_eq!( - onto(&odd, ¤t, &[]).document.graphql, - current.document.graphql - ); + let http = onto(&entry(RequestKind::Http, texted), ¤t(RequestKind::Http, mine.clone()), &[]); + let graphql = + onto(&entry(RequestKind::Graphql, posted), ¤t(RequestKind::Graphql, mine.clone()), &[]); - // A file was not kept: the request's own body stays. - let mut uploading = held(RequestKind::Http, RequestDocument::default()); - uploading.document.body = RequestBody::Binary { - path: "C:/tmp/a.bin".to_string(), - }; - let upload = sent( - "https://api.exemple.fr/upload", - Vec::new(), - SentBody::Bytes { size: 12 }, - &[], - ); - assert_eq!( - onto(&upload, &uploading, &[]).document.body, - uploading.document.body - ); + assert_eq!(http.document.body, RequestBody::Text { text: "new".to_string() }); + assert_eq!((graphql.method, graphql.document.graphql.query.as_str()), (HttpMethod::Get, "{ me }")); + assert_eq!(graphql.document.url, "https://shop.test/graphql?x=1"); + assert_eq!(graphql.document.body, mine.body); } + /// Newest first as read, a group a local day: a send at 23:30 in UTC is the next day two + /// hours east — −120 as the interface counts it. #[test] - fn entries_are_grouped_by_the_local_day() { + fn the_history_is_grouped_by_local_day() { let item = |id: &str, at: &str| HistoryItem { id: id.to_string(), - sent_at: at.parse().unwrap(), - method: HttpMethod::Get, - status: Some(200), - request_id: None, - summary: HistorySummary { - kind: RequestKind::Http, - name: id.to_string(), - url: String::new(), - millis: None, - size: None, - failure: None, - failure_params: BTreeMap::new(), - method: HttpMethod::Get, - status: None, - environment: None, - }, - url_head: String::new(), - url_tail: String::new(), + sent_at: crate::db::iso8601::parse(at).unwrap(), + ..entry(RequestKind::Http, exchange("https://shop.test/", Vec::new(), SentBody::None)).item }; - let days = by_day( - vec![ - item("c", "2026-10-07T00:30:00Z"), - item("b", "2026-10-06T23:30:00Z"), - item("a", "2026-10-06T10:00:00Z"), - ], - -120, - ); + let items = vec![ + item("late", "2026-07-25T23:30:00.000Z"), + item("evening", "2026-07-25T20:00:00.000Z"), + item("before", "2026-07-24T09:00:00.000Z"), + ]; - assert_eq!( + let utc = by_day(items.clone(), 0); + let east = by_day(items, -120); + + let grouped = |days: &[HistoryDay]| -> Vec<(String, Vec)> { days.iter() - .map(|day| (day.day.as_str(), day.items.len())) - .collect::>(), - [("2026-10-07", 2), ("2026-10-06", 1)] + .map(|day| (day.day.clone(), day.items.iter().map(|item| item.id.clone()).collect())) + .collect() + }; + assert_eq!( + grouped(&utc), + [ + ("2026-07-25".to_string(), vec!["late".to_string(), "evening".to_string()]), + ("2026-07-24".to_string(), vec!["before".to_string()]) + ] ); + assert_eq!(grouped(&east)[0], ("2026-07-26".to_string(), vec!["late".to_string()])); } } diff --git a/crates/engine/src/http/history/store.rs b/crates/engine/src/http/history/store.rs index b2301e9ee..f1d0873e6 100644 --- a/crates/engine/src/http/history/store.rs +++ b/crates/engine/src/http/history/store.rs @@ -5,8 +5,7 @@ use diesel::prelude::*; use uuid::Uuid; use super::{ - HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, - url_parts, + HistoryEntry, HistoryItem, HistoryRecord, HistorySummary, KEPT_AT_MOST, RETENTION_DAYS, url_parts, }; use crate::db::schema::http_history; use crate::db::{Library, iso8601}; @@ -23,10 +22,7 @@ struct Row { } fn corrupt(id: &str, field: &'static str) -> StorageError { - StorageError::CorruptRow { - id: id.to_string(), - field, - } + StorageError::CorruptRow { id: id.to_string(), field } } fn open_json( @@ -62,10 +58,7 @@ impl Row { } /// A request deleted since it was sent is history without its link. -fn still_there<'a>( - connection: &mut SqliteConnection, - request_id: Option<&'a str>, -) -> Option<&'a str> { +fn still_there<'a>(connection: &mut SqliteConnection, request_id: Option<&'a str>) -> Option<&'a str> { request_id.filter(|id| { crate::db::schema::http_requests::table .find(*id) @@ -130,15 +123,15 @@ pub fn restore(connection: &mut Library, entry: &HistoryEntry) -> Result<(), Sto /// Older than the retention, or past the count from the newest. fn purge(connection: &mut SqliteConnection, now: DateTime) -> Result { let horizon = iso8601::format(now - TimeDelta::days(RETENTION_DAYS)); - let aged = diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))) - .execute(connection)?; + let aged = + diesel::delete(http_history::table.filter(http_history::sent_at.lt(horizon))).execute(connection)?; let kept: Vec = http_history::table .select(http_history::id) .order((http_history::sent_at.desc(), http_history::id.desc())) .limit(KEPT_AT_MOST) .load(connection)?; - let counted = diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))) - .execute(connection)?; + let counted = + diesel::delete(http_history::table.filter(http_history::id.ne_all(kept))).execute(connection)?; Ok(aged + counted) } @@ -168,10 +161,7 @@ pub fn entry(connection: &mut Library, id: &str) -> Result Result { @@ -190,19 +180,22 @@ pub fn clear(connection: &mut Library) -> Result { #[cfg(test)] mod tests { use super::*; - use crate::http::history::{HistoryRecord, HistorySummary}; - use crate::http::model::HttpMethod; + use crate::http::model::{HttpMethod, HttpRequestDraft, RequestKind}; use crate::http::send::{Exchange, SentBody}; - fn summary() -> HistorySummary { + fn now() -> DateTime { + iso8601::parse("2026-07-25T09:00:00.000Z").unwrap() + } + + fn summary(name: &str) -> HistorySummary { HistorySummary { - kind: crate::http::model::RequestKind::Http, - name: "Ping".to_string(), - url: "https://api.exemple.fr".to_string(), - millis: Some(1), - size: Some(0), + name: name.to_string(), + url: "https://api.shop.test/orders/42".to_string(), + millis: Some(12), + size: Some(34), failure: None, failure_params: std::collections::BTreeMap::new(), + kind: RequestKind::Http, method: HttpMethod::Delete, status: Some(401), environment: None, @@ -212,8 +205,8 @@ mod tests { fn record() -> HistoryRecord { HistoryRecord { exchange: Exchange { - method: HttpMethod::Get, - url: "https://api.exemple.fr".to_string(), + method: HttpMethod::Delete, + url: "https://api.shop.test/orders/42".to_string(), headers: Vec::new(), body: SentBody::None, }, @@ -221,87 +214,193 @@ mod tests { } } + fn write(library: &mut Library, name: &str, request_id: Option<&str>, at: DateTime) -> String { + super::record(library, request_id, &summary(name), &record(), at).unwrap() + } + + fn names(library: &mut Library) -> Vec { + list(library).unwrap().into_iter().map(|item| item.summary.name).collect() + } + + fn a_request(library: &mut Library) -> String { + let collection = crate::http::store::create_collection(library, "Shop", now()).unwrap(); + let draft = HttpRequestDraft { + collection_id: collection.id, + folder_id: None, + name: "Orders".to_string(), + kind: RequestKind::Http, + method: HttpMethod::Get, + document: crate::http::model::RequestDocument::default(), + }; + crate::http::store::create_request(library, &draft, "Orders", now()).unwrap().id + } + + /// Newest first; of one instant, the one written last; read back with what a list shows, + /// its URL in two parts. #[test] - fn what_is_past_the_retention_or_the_count_goes_as_the_next_is_written() { + fn a_send_is_listed_newest_first_as_it_was_recorded() { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - let long_ago = now - TimeDelta::days(RETENTION_DAYS + 1); - record_at(&mut library, long_ago); - assert_eq!(count(&mut library).unwrap(), 1); + write(&mut library, "first", None, now()); + write(&mut library, "second", None, now()); + write(&mut library, "earlier", None, now() - TimeDelta::hours(1)); - for second in 0..=KEPT_AT_MOST { - record_at(&mut library, now + TimeDelta::seconds(second)); - } + let items = list(&mut library).unwrap(); - assert_eq!(i64::from(count(&mut library).unwrap()), KEPT_AT_MOST); - let newest = list(&mut library).unwrap(); - assert_eq!(newest[0].sent_at, now + TimeDelta::seconds(KEPT_AT_MOST)); - assert_eq!( - purge_expired(&mut library, now + TimeDelta::days(RETENTION_DAYS + 1)).unwrap(), - usize::try_from(KEPT_AT_MOST).unwrap() + let shown: Vec<&str> = items.iter().map(|item| item.summary.name.as_str()).collect(); + assert_eq!(shown, ["second", "first", "earlier"]); + let item = &items[0]; + assert_eq!((item.sent_at, item.method, item.status), (now(), HttpMethod::Delete, Some(401))); + assert_eq!((item.url_head.as_str(), item.url_tail.as_str()), ("api.shop.test", "/orders/42")); + } + + /// A request deleted since it was sent is history without its link. + #[test] + fn a_send_keeps_its_request_only_while_it_exists() { + let mut library = crate::db::open_in_memory().unwrap(); + let request = a_request(&mut library); + write(&mut library, "linked", Some(&request), now()); + write(&mut library, "gone", Some("deleted-since"), now()); + + let links: Vec> = + list(&mut library).unwrap().into_iter().map(|item| item.request_id).collect(); + + assert_eq!(links, [None, Some(request)]); + } + + /// Kept thirty days from each write: what is older goes as the next one is written. + #[test] + fn a_write_lets_go_of_what_is_past_the_retention() { + let mut library = crate::db::open_in_memory().unwrap(); + write( + &mut library, + "a month ago", + None, + now() - TimeDelta::days(RETENTION_DAYS) - TimeDelta::seconds(1), ); + write(&mut library, "at the edge", None, now() - TimeDelta::days(RETENTION_DAYS)); + + write(&mut library, "today", None, now()); + + assert_eq!(names(&mut library), ["today", "at the edge"]); } - /// « Vider l'historique » was the only way out for the one send made with the wrong token. + /// Five hundred entries at most: past them, the oldest goes as the next one is written. #[test] - fn one_entry_is_deleted_and_put_back_where_it_was() { + fn a_write_lets_go_of_what_is_past_the_count() { let mut library = crate::db::open_in_memory().unwrap(); - let now: DateTime = "2026-10-07T12:00:00Z".parse().unwrap(); - for second in 0..3 { - record_at(&mut library, now + TimeDelta::seconds(second)); + write(&mut library, "oldest", None, now() - TimeDelta::days(1)); + + for _ in 0..KEPT_AT_MOST { + write(&mut library, "recent", None, now()); } - let before = list(&mut library).unwrap(); - let middle = before[1].id.clone(); - - let removed = delete(&mut library, &middle).unwrap(); - assert_eq!(removed.item, before[1]); - assert_eq!( - list(&mut library) - .unwrap() - .iter() - .map(|item| item.id.as_str()) - .collect::>(), - [before[0].id.as_str(), before[2].id.as_str()] - ); - assert!(matches!( - delete(&mut library, &middle), - Err(StorageError::HttpItemNotFound(_)) - )); + assert_eq!(i64::from(count(&mut library).unwrap()), KEPT_AT_MOST); + assert!(!names(&mut library).contains(&"oldest".to_string())); + } + + /// Retention holds even when nothing is written: at launch, and never fatal. + #[test] + fn the_retention_is_swept_at_launch_without_a_write() { + let mut library = crate::db::open_in_memory().unwrap(); + write(&mut library, "old", None, Utc::now() - TimeDelta::days(RETENTION_DAYS + 1)); + write(&mut library, "kept", None, Utc::now()); + let db: crate::db::Db = std::sync::Mutex::new(Some(library)); + + crate::http::history::sweep_at_startup(&db); + crate::http::history::sweep_at_startup(&std::sync::Mutex::new(None)); + + assert_eq!(names(db.lock().unwrap().as_mut().unwrap()), ["kept"]); + } + + /// Deleted, an entry is answered whole; put back, it takes its place again under its id and + /// at its instant, once. + #[test] + fn an_entry_deleted_comes_back_where_it_was() { + let mut library = crate::db::open_in_memory().unwrap(); + write(&mut library, "older", None, now() - TimeDelta::hours(1)); + let id = write(&mut library, "middle", None, now()); + write(&mut library, "newer", None, now() + TimeDelta::hours(1)); + + let removed = delete(&mut library, &id).unwrap(); + assert_eq!(names(&mut library), ["newer", "older"]); restore(&mut library, &removed).unwrap(); - // Put back twice is put back once. restore(&mut library, &removed).unwrap(); - assert_eq!(list(&mut library).unwrap(), before); - assert_eq!(entry(&mut library, &middle).unwrap(), removed); + + assert_eq!(names(&mut library), ["newer", "middle", "older"]); + assert_eq!(entry(&mut library, &id).unwrap(), removed); + assert_eq!(removed.record, record()); } + /// Put back after its request went, an entry comes back without the link. #[test] - fn a_list_reads_each_url_in_its_two_parts() { + fn an_entry_put_back_after_its_request_went_has_no_link() { let mut library = crate::db::open_in_memory().unwrap(); - record_at(&mut library, "2026-10-07T12:00:00Z".parse().unwrap()); + let request = a_request(&mut library); + let id = write(&mut library, "linked", Some(&request), now()); + let removed = delete(&mut library, &id).unwrap(); + let gone = + crate::http::model::HttpItem { kind: crate::http::model::HttpItemKind::Request, id: request }; + crate::http::store::delete(&mut library, &gone).unwrap(); - let item = &list(&mut library).unwrap()[0]; - let (head, tail) = url_parts(&item.summary.url); - assert_eq!((&item.url_head, &item.url_tail), (&head, &tail)); - assert!(!item.url_head.is_empty()); + restore(&mut library, &removed).unwrap(); + + assert_eq!(entry(&mut library, &id).unwrap().item.request_id, None); } - /// Both were columns of their own, readable beside the instant of the send. #[test] - fn the_method_and_the_status_of_a_send_are_read_from_its_sealed_summary() { + fn an_entry_not_there_is_named_and_the_history_clears_whole() { let mut library = crate::db::open_in_memory().unwrap(); - record_at(&mut library, "2026-10-07T12:00:00Z".parse().unwrap()); + write(&mut library, "a", None, now()); + write(&mut library, "b", None, now()); - let item = list(&mut library).unwrap().remove(0); - assert_eq!((item.method, item.status), (HttpMethod::Delete, Some(401))); + assert!( + matches!(entry(&mut library, "missing"), Err(StorageError::HttpItemNotFound(id)) if id == "missing") + ); + assert!(matches!(delete(&mut library, "missing"), Err(StorageError::HttpItemNotFound(_)))); + assert_eq!(clear(&mut library).unwrap(), 2); + assert_eq!(count(&mut library).unwrap(), 0); + } - let removed = delete(&mut library, &item.id).unwrap(); - restore(&mut library, &removed).unwrap(); - let back = entry(&mut library, &item.id).unwrap().item; - assert_eq!((back.method, back.status), (HttpMethod::Delete, Some(401))); + /// ⚠️ In the clear, a reader of the raw file would read « a DELETE answered 401 at 14:02 »: + /// the method, the status, the URL and the name are sealed with the rest. + #[test] + fn a_send_is_sealed_but_for_its_instant() { + let mut library = crate::db::open_in_memory().unwrap(); + write(&mut library, "Delete the order", None, now()); + + let (summary, sealed): (String, String) = http_history::table + .select((http_history::summary, http_history::record)) + .first(library.db()) + .unwrap(); + + // Never as short as a status: three characters fall in a ciphertext by chance. + for clear in ["DELETE", "Delete", "status", "api.shop.test", "orders"] { + assert!(!summary.contains(clear) && !sealed.contains(clear), "{clear} in the clear"); + } } - fn record_at(library: &mut Library, at: DateTime) { - super::record(library, Some("gone"), &summary(), &record(), at).unwrap(); + /// What does not read is named by its field rather than skipped. + #[test] + fn an_entry_that_does_not_read_is_named_by_its_field() { + let mut library = crate::db::open_in_memory().unwrap(); + let id = write(&mut library, "a", None, now()); + let garbage = library.vault().seal("not json").unwrap(); + + diesel::update(http_history::table.find(&id)) + .set(http_history::record.eq(&garbage)) + .execute(library.db()) + .unwrap(); + assert!(matches!(entry(&mut library, &id), Err(StorageError::CorruptRow { field: "record", .. }))); + diesel::update(http_history::table.find(&id)) + .set(http_history::summary.eq(&garbage)) + .execute(library.db()) + .unwrap(); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "summary", .. }))); + let readable = seal_json(library.vault(), &summary("a")).unwrap(); + diesel::update(http_history::table.find(&id)) + .set((http_history::summary.eq(readable), http_history::sent_at.eq("not a date"))) + .execute(library.db()) + .unwrap(); + assert!(matches!(list(&mut library), Err(StorageError::CorruptRow { field: "sentAt", .. }))); } } diff --git a/crates/engine/src/http/model.rs b/crates/engine/src/http/model.rs index 721f863d1..70dffa320 100644 --- a/crates/engine/src/http/model.rs +++ b/crates/engine/src/http/model.rs @@ -114,11 +114,7 @@ pub struct RequestScripts { /// What a request sends as its body. A file is a path, read by Rust when the request is sent: /// its bytes never enter the library. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestBody { #[default] None, @@ -162,12 +158,8 @@ impl RequestBody { match self { Self::None => false, Self::Json { text } | Self::Text { text } => !text.is_empty(), - Self::Form { fields } => fields - .iter() - .any(|row| row.enabled && !row.key.trim().is_empty()), - Self::Multipart { parts } => parts - .iter() - .any(|part| part.enabled && !part.key.trim().is_empty()), + Self::Form { fields } => fields.iter().any(|row| row.enabled && !row.key.trim().is_empty()), + Self::Multipart { parts } => parts.iter().any(|part| part.enabled && !part.key.trim().is_empty()), Self::Binary { path } => !path.trim().is_empty(), } } @@ -213,11 +205,7 @@ pub enum KeyPlace { /// `Inherit` takes the auth of the nearest folder, then the collection, that sets one. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -#[serde( - tag = "kind", - rename_all = "camelCase", - rename_all_fields = "camelCase" -)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum RequestAuth { #[default] Inherit, @@ -274,12 +262,7 @@ pub struct KeyValue { /// Enabled: a row is typed to be sent. impl Default for KeyValue { fn default() -> Self { - Self { - enabled: true, - key: String::new(), - value: String::new(), - description: String::new(), - } + Self { enabled: true, key: String::new(), value: String::new(), description: String::new() } } } @@ -414,13 +397,8 @@ pub struct HttpRequestPatch { #[derive(Debug, Clone, PartialEq, Eq)] pub enum HttpNode { - Folder { - folder: HttpFolder, - children: Vec, - }, - Request { - request: HttpRequestSummary, - }, + Folder { folder: HttpFolder, children: Vec }, + Request { request: HttpRequestSummary }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -453,9 +431,7 @@ pub struct HttpPlace { /// The type a multipart file part is sent with, read off its name: what an attachment knows, /// and the web's own files besides; `application/octet-stream` for the rest. pub fn part_type(file_name: &str) -> String { - let extension = file_name - .rsplit_once('.') - .map(|(_, extension)| extension.to_ascii_lowercase()); + let extension = file_name.rsplit_once('.').map(|(_, extension)| extension.to_ascii_lowercase()); let web = match extension.as_deref() { Some("html" | "htm") => "text/html", Some("xml") => "application/xml", @@ -483,17 +459,21 @@ pub fn validated_name(raw: &str) -> Result { mod tests { use super::*; - #[test] - fn a_file_part_takes_the_type_of_its_extension() { - assert_eq!(part_type("image-test.PNG"), "image/png"); - assert_eq!(part_type("index.html"), "text/html"); - assert_eq!(part_type("data.json"), "application/json"); - assert_eq!(part_type("archive.tar.gz"), "application/gzip"); - assert_eq!(part_type("Makefile"), "application/octet-stream"); + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } + } + + fn part(key: &str, value: &str, file: bool, enabled: bool) -> FormPart { + FormPart { enabled, key: key.to_string(), value: value.to_string(), file, ..FormPart::default() } + } + + fn json(text: &str) -> RequestBody { + RequestBody::Json { text: text.to_string() } } + /// Stored as written: a method or a kind reads back from its spelling. #[test] - fn every_method_and_kind_survives_its_stored_spelling() { + fn every_method_and_kind_reads_back_from_its_spelling() { for method in HttpMethod::ALL { assert_eq!(method.as_str().parse::(), Ok(method)); } @@ -502,72 +482,109 @@ mod tests { } } - /// Key `X-Recette: 1`, value `rsgfdregr`: accepted, then every request failed on its URL. + /// `GET` and `HEAD` seldom carry a body; what changes nothing is what a protected + /// environment lets leave without asking. #[test] - fn a_header_name_is_a_token_and_a_value_holds_no_control_character() { - for name in ["X-Recette", "accept", "X_a.b~c!#$%&'*+^`|", " Trimmed "] { - assert_eq!(header_fault(name, "v"), None, "{name}"); - } - for name in [ - "X-Recette: 1", - "X Recette", - "Clé", - "", - "a\tb", - "a(b)", - "a\"b", - "a/b", - "a@b", + fn each_method_says_whether_it_carries_a_body_and_changes_anything() { + use HttpMethod::{Delete, Get, Head, Options, Patch, Post, Put}; + for (method, seldom_a_body, changes_nothing) in [ + (Get, true, true), + (Head, true, true), + (Options, false, true), + (Post, false, false), + (Put, false, false), + (Patch, false, false), + (Delete, false, false), ] { - assert_eq!(header_fault(name, "v"), Some(HeaderFault::Name), "{name}"); + assert_eq!(method.seldom_carries_a_body(), seldom_a_body, "{method:?}"); + assert_eq!(method.changes_nothing(), changes_nothing, "{method:?}"); } - for value in [ - "", - "application/json; charset=utf-8", - "Équipe/1", - "a\tb", - " padded ", + } + + /// The files a send reads: a binary body's, and each file part that leaves. + #[test] + fn a_body_names_the_files_the_send_reads() { + let multipart = RequestBody::Multipart { + parts: vec![ + part("avatar", "/a.png", true, true), + part("off", "/off.png", true, false), + part(" ", "/unnamed.png", true, true), + part("name", "Ada", false, true), + ], + }; + let binary = RequestBody::Binary { path: "/dump.bin".to_string() }; + + assert_eq!(multipart.files(), ["/a.png"]); + assert_eq!(binary.files(), ["/dump.bin"]); + assert!(json("{}").files().is_empty()); + } + + /// A kind chosen and left empty sends none. + #[test] + fn a_body_carries_something_only_once_filled() { + let named = || vec![row("q", "1")]; + let off = || vec![KeyValue { enabled: false, ..row("q", "1") }]; + for (body, carries) in [ + (RequestBody::None, false), + (json(""), false), + (json("{}"), true), + (RequestBody::Text { text: "t".to_string() }, true), + (RequestBody::Form { fields: named() }, true), + (RequestBody::Form { fields: off() }, false), + (RequestBody::Form { fields: vec![row(" ", "1")] }, false), + (RequestBody::Multipart { parts: vec![part("a", "", false, true)] }, true), + (RequestBody::Multipart { parts: vec![part("a", "", false, false)] }, false), + (RequestBody::Binary { path: " ".to_string() }, false), + (RequestBody::Binary { path: "/f".to_string() }, true), ] { - assert_eq!(header_fault("X-A", value), None, "{value:?}"); + assert_eq!(body.carries_something(), carries, "{body:?}"); } - for value in ["a\nb", "a\r\nX-Injected: 1", "bell\u{7}", "del\u{7f}"] { - assert_eq!( - header_fault("X-A", value), - Some(HeaderFault::Value), - "{value:?}" - ); + } + + /// Sent as typed whatever the method; the editor only says it. + #[test] + fn a_body_is_unusual_only_when_filled_on_a_get_or_a_head() { + assert!(json("{}").is_unusual_on(HttpMethod::Get)); + assert!(json("{}").is_unusual_on(HttpMethod::Head)); + assert!(!json("{}").is_unusual_on(HttpMethod::Post)); + assert!(!json("").is_unusual_on(HttpMethod::Get)); + } + + /// A name is an HTTP token — no space, no colon, no accent —, a `{{name}}` standing for a + /// letter; a value holds no line break nor control character but a tab. + #[test] + fn a_header_is_sent_only_with_a_token_for_a_name_and_a_value_without_a_break() { + for (name, value, fault) in [ + ("X-Request-Id", "abc", None), + (" Accept ", "a\tb", None), + ("X-{{tenant}}-Id", "x", None), + ("!#$%&'*+-.^_`|~", "x", None), + ("", "x", Some(HeaderFault::Name)), + ("X Id", "x", Some(HeaderFault::Name)), + ("Accept: json", "", Some(HeaderFault::Name)), + ("Clé", "x", Some(HeaderFault::Name)), + ("{{user.name}}", "x", Some(HeaderFault::Name)), + ("X-Id", "a\nb", Some(HeaderFault::Value)), + ("X-Id", "a\u{7}b", Some(HeaderFault::Value)), + ] { + assert_eq!(header_fault(name, value), fault, "{name:?}: {value:?}"); } } - /// The rule is what the client can build: it must not refuse more, nor let through more. + /// Key `X-Recette: 1` was accepted, then every request failed on it: the rule is what the + /// client can build, refusing no more and letting through no more. #[test] fn the_rule_agrees_with_what_the_client_builds() { use reqwest::header::{HeaderName, HeaderValue}; - for name in [ - "X-Recette", - "X Recette", - "X:1", - "Clé", - "a(b)", - "x_y", - "a`b", - "", - ] { + for name in ["X-Recette", "X Recette", "X:1", "Clé", "a(b)", "x_y", "a`b", ""] { assert_eq!( header_fault(name, "").is_none(), HeaderName::from_bytes(name.as_bytes()).is_ok(), "{name}" ); } - for value in [ - "plain", - "tab\there", - "Équipe", - "line\nbreak", - "nul\u{0}", - "del\u{7f}", - ] { + for value in ["plain", "tab\there", "Équipe", "line\nbreak", "nul\u{0}", "del\u{7f}"] { assert_eq!( header_fault("X-A", value).is_none(), HeaderValue::from_str(value).is_ok(), @@ -576,151 +593,71 @@ mod tests { } } + /// Every field defaults: one added later needs no migration, and a document written by an + /// older version still opens. #[test] - fn a_variable_in_a_header_stands_for_a_letter_until_it_is_filled() { - assert_eq!(header_fault("X-{{tenant}}-Id", "{{token}}"), None); - assert_eq!(header_fault("{{name}}", ""), None); - // Not a variable: a dotted path is text, as everywhere else. - assert_eq!(header_fault("{{user.name}}", ""), Some(HeaderFault::Name)); - assert_eq!(header_fault("X {{tenant}}", ""), Some(HeaderFault::Name)); - } - - #[test] - fn a_row_switched_off_or_without_a_name_is_not_judged() { - let row = |enabled: bool, key: &str, value: &str| KeyValue { - enabled, - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - }; + fn a_document_written_before_a_field_existed_still_opens() { + let document: RequestDocument = serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); + assert_eq!(document.url, "https://exemple.fr"); + assert_eq!(document.description, ""); assert_eq!( - header_faults(&[ - row(true, "Accept", "*/*"), - row(true, "X Recette", "1"), - row(false, "X Recette", "1"), - row(true, " ", "orphan"), - row(true, "X-A", "a\nb"), - ]), - vec![ - None, - Some(HeaderFault::Name), - None, - None, - Some(HeaderFault::Value) - ] + serde_json::from_str::(r#"{"later":1}"#).unwrap(), + RequestDocument::default() ); } + /// Not sent, not judged. #[test] - fn header_lines_are_read_as_rows_at_their_first_colon() { - let read = |text: &str| -> Vec<(String, String)> { - headers_from_text(text) - .into_iter() - .map(|row| { - assert!(row.enabled); - (row.key, row.value) - }) - .collect() - }; - let pair = |key: &str, value: &str| (key.to_string(), value.to_string()); + fn a_header_switched_off_or_unnamed_is_not_judged() { + let rows = [row("X Id", "x"), KeyValue { enabled: false, ..row("X Id", "x") }, row(" ", "a\nb")]; - assert_eq!(read("X-Recette: 1"), vec![pair("X-Recette", "1")]); - assert_eq!(read("X-Recette:"), vec![pair("X-Recette", "")]); - assert_eq!( - read("Referer: https://exemple.fr:8443/a"), - vec![pair("Referer", "https://exemple.fr:8443/a")] - ); - // As a browser's network tab copies them: a request line, pseudo-headers, blank lines. - assert_eq!( - read( - "GET /events HTTP/2\r\n:authority: api.exemple.fr\r\naccept: */*\r\n\r\n x-client : web \n" - ), - vec![pair("accept", "*/*"), pair("x-client", "web")] - ); - assert_eq!(read("no colon here"), Vec::new()); + assert_eq!(header_faults(&rows), [Some(HeaderFault::Name), None, None]); } - /// A `POST` switched to `GET` kept its body and sent it, and nothing said so. + /// A line copied from a network tab: what follows the first colon is the value; a line + /// without one is no header, and a pseudo-header is the client's to write. #[test] - fn a_body_is_unusual_on_a_get_and_a_head_and_on_no_other_method() { - let json = RequestBody::Json { - text: "{\"a\":1}".to_string(), - }; - let warned: Vec = HttpMethod::ALL - .into_iter() - .filter(|method| json.is_unusual_on(*method)) - .collect(); - assert_eq!(warned, vec![HttpMethod::Get, HttpMethod::Head]); + fn header_lines_become_rows_split_at_their_first_colon() { + let rows = headers_from_text( + "Accept: application/json\n Referer : https://shop.test/a \nno colon\n:authority: shop.test\n", + ); - for method in HttpMethod::ALL { - assert!(!RequestBody::None.is_unusual_on(method)); - } + assert_eq!(rows, [row("Accept", "application/json"), row("Referer", "https://shop.test/a"),]); } + /// The web's own files by their extension, whatever its case; what an attachment knows + /// otherwise; a stream of bytes for the rest. #[test] - fn a_kind_chosen_and_left_empty_is_no_body() { - let row = |enabled: bool, key: &str| KeyValue { - enabled, - key: key.to_string(), - ..KeyValue::default() - }; - let part = |enabled: bool, key: &str| FormPart { - enabled, - key: key.to_string(), - ..FormPart::default() - }; - let empty = [ - RequestBody::None, - RequestBody::Json { - text: String::new(), - }, - RequestBody::Text { - text: String::new(), - }, - RequestBody::Form { - fields: vec![row(false, "q"), row(true, " ")], - }, - RequestBody::Multipart { - parts: vec![part(false, "file"), part(true, "")], - }, - RequestBody::Binary { - path: " ".to_string(), - }, - ]; - for body in &empty { - assert!(!body.carries_something(), "{body:?}"); - } - - let filled = [ - RequestBody::Text { - text: " ".to_string(), - }, - RequestBody::Form { - fields: vec![row(true, "q")], - }, - RequestBody::Multipart { - parts: vec![part(true, "file")], - }, - RequestBody::Binary { - path: "C:/tmp/a.bin".to_string(), - }, - ]; - for body in &filled { - assert!(body.is_unusual_on(HttpMethod::Get), "{body:?}"); + fn a_file_part_is_typed_by_its_extension() { + for (name, typed) in [ + ("index.HTML", "text/html"), + ("page.htm", "text/html"), + ("feed.xml", "application/xml"), + ("site.css", "text/css"), + ("app.mjs", "text/javascript"), + ("app.js", "text/javascript"), + ("ci.yml", "application/yaml"), + ("ci.yaml", "application/yaml"), + ("photo.avif", "image/avif"), + ("favicon.ico", "image/vnd.microsoft.icon"), + ("song.mp3", "audio/mpeg"), + ("ring.wav", "audio/wav"), + ("clip.mp4", "video/mp4"), + ("clip.webm", "video/webm"), + ("dump.gz", "application/gzip"), + ("dump.tar", "application/x-tar"), + ("photo.png", "image/png"), + ("data.unknown", "application/octet-stream"), + ("Makefile", "application/octet-stream"), + ] { + assert_eq!(part_type(name), typed, "{name}"); } } #[test] - fn a_document_written_before_a_field_existed_still_opens() { - let document: RequestDocument = - serde_json::from_str(r#"{"url":"https://exemple.fr"}"#).unwrap(); - - assert_eq!(document.url, "https://exemple.fr"); - assert_eq!(document.description, ""); - assert_eq!( - serde_json::from_str::(r#"{"later":1}"#).unwrap(), - RequestDocument::default() - ); + fn a_collection_folder_or_request_is_named_readably() { + assert_eq!(validated_name(" Orders ").unwrap(), "Orders"); + assert!(validated_name(" ").is_err()); } } diff --git a/crates/engine/src/http/query.rs b/crates/engine/src/http/query.rs index c3f1e55ea..86300e996 100644 --- a/crates/engine/src/http/query.rs +++ b/crates/engine/src/http/query.rs @@ -18,14 +18,8 @@ pub struct SyncedQuery { /// The side that was edited wins; the other is rewritten from it. pub fn sync(url: &str, params: &[KeyValue], edited: QuerySide) -> SyncedQuery { match edited { - QuerySide::Url => SyncedQuery { - url: url.to_string(), - params: params_from_url(url, params), - }, - QuerySide::Params => SyncedQuery { - url: url_with_params(url, params), - params: params.to_vec(), - }, + QuerySide::Url => SyncedQuery { url: url.to_string(), params: params_from_url(url, params) }, + QuerySide::Params => SyncedQuery { url: url_with_params(url, params), params: params.to_vec() }, } } @@ -42,39 +36,21 @@ fn parts(url: &str) -> (&str, Option<&str>, &str) { /// and stays where it was, and a description follows its key. fn params_from_url(url: &str, previous: &[KeyValue]) -> Vec { let (_, query, _) = parts(url); - let mut typed = query - .unwrap_or("") - .split('&') - .filter(|pair| !pair.is_empty()) - .map(|pair| { - let (key, value) = pair.split_once('=').unwrap_or((pair, "")); - (key.to_string(), value.to_string()) - }); + let mut typed = query.unwrap_or("").split('&').filter(|pair| !pair.is_empty()).map(|pair| { + let (key, value) = pair.split_once('=').unwrap_or((pair, "")); + (key.to_string(), value.to_string()) + }); let mut rows = Vec::with_capacity(previous.len()); for row in previous { if !row.enabled { rows.push(row.clone()); } else if let Some((key, value)) = typed.next() { - let description = if key == row.key { - row.description.clone() - } else { - String::new() - }; - rows.push(KeyValue { - enabled: true, - key, - value, - description, - }); + let description = if key == row.key { row.description.clone() } else { String::new() }; + rows.push(KeyValue { enabled: true, key, value, description }); } } - rows.extend(typed.map(|(key, value)| KeyValue { - enabled: true, - key, - value, - description: String::new(), - })); + rows.extend(typed.map(|(key, value)| KeyValue { enabled: true, key, value, description: String::new() })); rows } @@ -97,79 +73,68 @@ fn url_with_params(url: &str, params: &[KeyValue]) -> String { mod tests { use super::*; - fn row(enabled: bool, key: &str, value: &str, description: &str) -> KeyValue { - KeyValue { - enabled, - key: key.to_string(), - value: value.to_string(), - description: description.to_string(), - } + fn row(key: &str, value: &str) -> KeyValue { + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } + } + + fn described(key: &str, value: &str, description: &str) -> KeyValue { + KeyValue { description: description.to_string(), ..row(key, value) } + } + + fn off(key: &str, value: &str) -> KeyValue { + KeyValue { enabled: false, ..row(key, value) } + } + + fn from_url(url: &str, params: &[KeyValue]) -> Vec { + let synced = sync(url, params, QuerySide::Url); + assert_eq!(synced.url, url, "the URL edited is kept as typed"); + synced.params + } + + fn from_params(url: &str, params: &[KeyValue]) -> String { + let synced = sync(url, params, QuerySide::Params); + assert_eq!(synced.params, params, "the table edited is kept as typed"); + synced.url } + /// Nothing decoded: `{{page}}` and `%20` read back as typed; a pair without `=` has an empty + /// value, an empty pair is none, and the fragment ends the query. #[test] - fn a_typed_query_fills_the_table_as_written() { - let synced = sync( - "{{baseUrl}}/customers/{{customerId}}/invoices?page=1&limit=50&q=a%20b&flag#top", - &[], - QuerySide::Url, - ); + fn the_url_s_pairs_become_rows_as_typed() { + let rows = from_url("https://shop.test/a?q=a%20b&&page={{page}}&flag#top?x=1", &[]); - assert_eq!( - synced.params, - vec![ - row(true, "page", "1", ""), - row(true, "limit", "50", ""), - row(true, "q", "a%20b", ""), - row(true, "flag", "", ""), - ] - ); + assert_eq!(rows, [row("q", "a%20b"), row("page", "{{page}}"), row("flag", "")]); } + /// The pairs take the enabled rows' places in order; a row switched off is not in the URL + /// and stays where it was; a description follows its key; rows the URL no longer holds go. #[test] - fn a_disabled_row_stays_put_and_a_description_follows_its_key() { - let previous = [ - row(true, "page", "1", "Page, à partir de 1"), - row(false, "status", "paid", "Filtrer par statut"), - row(true, "limit", "50", "100 au plus"), + fn the_url_s_pairs_replace_the_enabled_rows_in_order() { + let table = [ + described("q", "old", "the search"), + off("debug", "1"), + described("page", "1", "which page"), + row("gone", "x"), ]; - let synced = sync("/invoices?page=2&size=50", &previous, QuerySide::Url); + let rows = from_url("https://shop.test/a?q=new&sort=asc", &table); - assert_eq!( - synced.params, - vec![ - row(true, "page", "2", "Page, à partir de 1"), - row(false, "status", "paid", "Filtrer par statut"), - row(true, "size", "50", ""), - ] - ); - assert_eq!( - sync("/invoices", &previous, QuerySide::Url).params, - vec![previous[1].clone()] - ); + assert_eq!(rows, [described("q", "new", "the search"), off("debug", "1"), row("sort", "asc"),]); + assert_eq!(from_url("https://shop.test/a", &table), [off("debug", "1")]); } + /// The enabled rows with a key, in order; none, no `?`; the fragment stays at the end. #[test] - fn the_table_rewrites_the_query_keeping_the_path_and_the_fragment() { - let params = [ - row(true, "page", "{{page}}", ""), - row(false, "status", "paid", ""), - row(true, "", "orphan", ""), - row(true, "limit", "50", ""), - ]; + fn the_rows_rewrite_the_url_s_query() { + let table = [row("q", "{{term}}"), off("debug", "1"), row("", "lost"), row("page", "2")]; assert_eq!( - sync("{{baseUrl}}/invoices?old=1#top", ¶ms, QuerySide::Params).url, - "{{baseUrl}}/invoices?page={{page}}&limit=50#top" + from_params("https://shop.test/a?old=1#top", &table), + "https://shop.test/a?q={{term}}&page=2#top" ); assert_eq!( - sync( - "/invoices?old=1", - &[row(false, "a", "1", "")], - QuerySide::Params - ) - .url, - "/invoices" + from_params("https://shop.test/a?old=1#top", &[off("debug", "1")]), + "https://shop.test/a#top" ); } } diff --git a/crates/engine/src/http/response.rs b/crates/engine/src/http/response.rs index 35d7b785b..dcf5607d5 100644 --- a/crates/engine/src/http/response.rs +++ b/crates/engine/src/http/response.rs @@ -88,9 +88,7 @@ fn cookie(line: &str) -> Option { for attribute in parts { let (key, value) = attribute .split_once('=') - .map_or((attribute.trim(), ""), |(key, value)| { - (key.trim(), value.trim()) - }); + .map_or((attribute.trim(), ""), |(key, value)| (key.trim(), value.trim())); match key.to_ascii_lowercase().as_str() { "domain" => cookie.domain = Some(value.to_string()), "path" => cookie.path = Some(value.to_string()), @@ -171,71 +169,111 @@ mod tests { use super::*; fn header(key: &str, value: &str) -> KeyValue { - KeyValue { - key: key.to_string(), - value: value.to_string(), - ..KeyValue::default() - } + KeyValue { key: key.to_string(), value: value.to_string(), ..KeyValue::default() } } + /// Read off its type, whatever its case and parameters; with none, a body that parses as + /// JSON is JSON. A type that says otherwise wins over a body that looks like JSON. #[test] - fn json_is_laid_out_with_its_numbers_and_strings_as_they_came() { - assert_eq!( - pretty_json(r#"{"id":12345678901234567890,"n":1.10,"s":"a, {b}: \"c\"","e":[],"o":{ },"l":[1,{"k":null}]}"#) - .unwrap(), - "{\n \"id\": 12345678901234567890,\n \"n\": 1.10,\n \"s\": \"a, {b}: \\\"c\\\"\",\n \"e\": [],\n \"o\": {},\n \"l\": [\n 1,\n {\n \"k\": null\n }\n ]\n}" - ); - assert_eq!(pretty_json(" 42 ").as_deref(), Some("42")); - assert_eq!(pretty_json("{\"a\":"), None); - } - - #[test] - fn the_language_follows_the_type_or_failing_one_the_text() { - assert_eq!( - language(Some("application/problem+json; charset=utf-8"), ""), - Language::Json - ); - assert_eq!(language(Some("text/html"), ""), Language::Html); - assert_eq!(language(Some("application/xhtml+xml"), ""), Language::Html); - assert_eq!(language(Some("application/rss+xml"), ""), Language::Xml); - assert_eq!(language(Some("text/javascript"), ""), Language::Js); - assert_eq!(language(Some("text/plain"), "{\"a\":1}"), Language::Txt); - assert_eq!(language(None, " [1, 2]"), Language::Json); - assert_eq!(language(None, "hello"), Language::Txt); + fn an_answer_is_coloured_in_the_language_its_type_names() { + for (kind, body, expected) in [ + (Some("application/json; charset=utf-8"), "", Language::Json), + (Some("application/problem+json"), "", Language::Json), + (Some("TEXT/HTML"), "", Language::Html), + (Some("application/xhtml+xml"), "", Language::Html), + (Some("image/svg+xml"), "", Language::Xml), + (Some("application/javascript"), "", Language::Js), + (Some("text/ecmascript"), "", Language::Js), + (Some("text/css"), "", Language::Css), + (Some("application/x-yaml"), "", Language::Yml), + (Some("application/graphql"), "", Language::Graphql), + (Some("text/plain"), "{\"a\":1}", Language::Txt), + (None, " [1, 2]", Language::Json), + (None, "{\"a\":1}", Language::Json), + (None, "{not json", Language::Txt), + (None, "\"just a string\"", Language::Txt), + (Some(" ; charset=utf-8"), "{}", Language::Json), + ] { + assert_eq!(language(kind, body), expected, "{kind:?} {body:?}"); + } } + /// Every `Set-Cookie`, in order, its attributes named; a quoted value read without its + /// quotes; a line that names no cookie left out. #[test] - fn a_set_cookie_is_read_with_its_attributes_and_the_other_headers_are_not() { - let found = cookies(&[ - header("content-type", "text/plain"), - header( - "set-cookie", - "session=\"abc=1\"; Path=/; Domain=example.com; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=3600; HttpOnly; Secure; SameSite=Lax", - ), + fn each_set_cookie_is_read_with_its_attributes() { + let headers = [ + header("Content-Type", "text/plain"), + header("X-Not-A-Cookie", "a=b"), + header("set-cookie", "sid=\"abc=1\"; Domain=shop.test; Path=/; HttpOnly; Secure; SameSite=Lax"), header("Set-Cookie", "theme=dark"), - header("set-cookie", "=nameless"), - ]); + header("Set-Cookie", "no equals sign"), + header("Set-Cookie", " =nameless"), + ]; + + let cookies = cookies(&headers); assert_eq!( - found, - vec![ + cookies, + [ Cookie { - name: "session".to_string(), + name: "sid".to_string(), value: "abc=1".to_string(), - domain: Some("example.com".to_string()), + domain: Some("shop.test".to_string()), path: Some("/".to_string()), - expires: Some("Max-Age=3600".to_string()), http_only: true, secure: true, same_site: Some("Lax".to_string()), - from: None, - }, - Cookie { - name: "theme".to_string(), - value: "dark".to_string(), ..Cookie::default() }, + Cookie { name: "theme".to_string(), value: "dark".to_string(), ..Cookie::default() }, ] ); } + + /// As a browser reads them, whichever comes first. + #[test] + fn max_age_wins_over_expires() { + for line in [ + "a=1; Expires=Wed, 21 Oct 2026 07:28:00 GMT; Max-Age=60", + "a=1; Max-Age=60; Expires=Wed, 21 Oct 2026 07:28:00 GMT", + ] { + let read = cookies(&[header("Set-Cookie", line)]); + + assert_eq!(read[0].expires.as_deref(), Some("Max-Age=60"), "{line}"); + } + let expires = cookies(&[header("Set-Cookie", "a=1; expires=Wed, 21 Oct 2026 07:28:00 GMT")]); + assert_eq!(expires[0].expires.as_deref(), Some("Wed, 21 Oct 2026 07:28:00 GMT")); + } + + /// Two spaces a level; an empty object or array stays on its line; what a string holds is + /// left alone. + #[test] + fn json_is_laid_out_two_spaces_a_level() { + let pretty = pretty_json( + r#"{"a":[1,{"b":"x, y: {z}"}],"empty":{ },"none":[ ],"q":"say \"hi, you: {x}\" now"}"#, + ) + .unwrap(); + + assert_eq!( + pretty, + "{\n \"a\": [\n 1,\n {\n \"b\": \"x, y: {z}\"\n }\n ],\n \"empty\": {},\n \"none\": [],\n \"q\": \"say \\\"hi, you: {x}\\\" now\"\n}" + ); + } + + /// Its tokens copied as they came: re-serialising would round a number past `f64` and write + /// `1.10` as `1.1`. + #[test] + fn json_laid_out_keeps_its_numbers_as_written() { + let pretty = pretty_json("[12345678901234567890, 1.10, -0e5]").unwrap(); + + assert_eq!(pretty, "[\n 12345678901234567890,\n 1.10,\n -0e5\n]"); + } + + #[test] + fn what_is_not_json_is_not_laid_out_and_a_lone_value_is_bare() { + assert_eq!(pretty_json("{\"a\":"), None); + assert_eq!(pretty_json("plain text"), None); + assert_eq!(pretty_json(" 42 ").as_deref(), Some("42")); + } } diff --git a/crates/engine/src/http/runner.rs b/crates/engine/src/http/runner.rs index 3ce4a454b..7228663e9 100644 --- a/crates/engine/src/http/runner.rs +++ b/crates/engine/src/http/runner.rs @@ -45,11 +45,7 @@ pub fn read_file(path: &str) -> Result { /// A CSV with its header, or a JSON array of objects: what the file's text reads as. pub fn read_data(text: &str) -> Result { let text = text.trim_start_matches('\u{feff}'); - let data = if text.trim_start().starts_with('[') { - from_json(text)? - } else { - from_csv(text)? - }; + let data = if text.trim_start().starts_with('[') { from_json(text)? } else { from_csv(text)? }; if data.rows.is_empty() { return Err(DataFault::Empty); } @@ -225,12 +221,7 @@ impl RunSummary { #[must_use] pub fn of(results: &[RunResult]) -> Self { let count = |held: usize| u32::try_from(held).unwrap_or(u32::MAX); - let ran = || { - results - .iter() - .flat_map(|result| &result.tests) - .filter(|test| !test.skipped) - }; + let ran = || results.iter().flat_map(|result| &result.tests).filter(|test| !test.skipped); Self { failures: count(results.iter().filter(|result| result.failed()).count()), requests: count(results.len()), @@ -344,10 +335,7 @@ pub fn run_order(saved: &[RunEntry], placed: &[Placed]) -> Vec { } for request in placed { if !order.iter().any(|kept| kept.id == request.id) { - order.push(RunEntry { - id: request.id.clone(), - enabled: true, - }); + order.push(RunEntry { id: request.id.clone(), enabled: true }); } } order @@ -389,10 +377,7 @@ pub fn result_of( } Err(error) if error.code == ErrorCode::HttpScriptSkipped => result.skipped = true, Err(error) => { - result.error = Some(RunError { - code: error.code, - params: error.params, - }); + result.error = Some(RunError { code: error.code, params: error.params }); } } result @@ -412,10 +397,7 @@ pub fn gone(iteration: u32, placed: &Placed, error: AppError) -> RunResult { reason: String::new(), millis: 0, tests: Vec::new(), - error: Some(RunError { - code: error.code, - params: error.params, - }), + error: Some(RunError { code: error.code, params: error.params }), stop: None, skipped: false, response: None, @@ -463,9 +445,7 @@ impl Runs { pub fn cancel_all(&self) { if let Ok(mut running) = self.running.lock() { - running - .values_mut() - .for_each(|(cancelled, _)| *cancelled = true); + running.values_mut().for_each(|(cancelled, _)| *cancelled = true); } } @@ -495,11 +475,94 @@ pub fn next_index(order: &[Placed], at: usize, next: Option<&Next>) -> Option Vec<&str> { + data.columns.iter().map(String::as_str).collect() + } + + fn row(pairs: &[(&str, &str)]) -> BTreeMap { + pairs + .iter() + .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + .collect() + } + + /// A JSON array of objects: its keys in the order first met, a text as it is and the rest + /// as JSON; a byte-order mark before it is no reason to refuse it. + #[test] + fn a_json_array_of_objects_is_read_a_row_an_object() { + let data = + read_data("\u{feff} [{\"user\":\"ada\",\"age\":36},{\"admin\":true,\"user\":\"bob\"}]").unwrap(); + + assert_eq!(columns(&data), ["user", "age", "admin"]); + assert_eq!( + data.rows, + [row(&[("user", "ada"), ("age", "36")]), row(&[("admin", "true"), ("user", "bob")])] + ); + } + + /// RFC 4180: a quoted field holds commas, line breaks and doubled quotes; a short row ends + /// on empty values, an unnamed column is left out, blank lines and CRs are nothing. + #[test] + fn a_csv_with_its_header_is_read_a_row_a_line() { + let data = + read_data("user , note,,age\r\nada,\"a, \"\"quoted\"\"\nnote\",x,36\r\n\r\nbob\n").unwrap(); + + assert_eq!(columns(&data), ["user", "note", "", "age"]); + assert_eq!( + data.rows, + [ + row(&[("user", "ada"), ("note", "a, \"quoted\"\nnote"), ("age", "36")]), + row(&[("user", "bob"), ("note", ""), ("age", "")]), + ] + ); + } + + /// What reads as neither — a quote left open, a sentence alone, a JSON + /// that is no array of objects — is said so; a file of no row is said empty, a line of commas being blank. + #[test] + fn a_file_that_reads_as_no_data_is_refused_for_what_it_is() { + for (text, fault) in [ + ("user\n\"ada", DataFault::Unreadable), + ("just a sentence here", DataFault::Unreadable), + (",,\nx,y", DataFault::Empty), + ("[1, 2]", DataFault::Unreadable), + ("[{\"a\":", DataFault::Unreadable), + ("user,age\n", DataFault::Empty), + ("[]", DataFault::Empty), + ("", DataFault::Empty), + ] { + assert_eq!(read_data(text), Err(fault), "{text:?}"); + } + // A lone word is a header waiting for its rows, not a sentence. + assert_eq!(read_data("token"), Err(DataFault::Empty)); + } + + /// Read where it lies; past the size a run reads, refused before it is read. + #[test] + fn a_data_file_is_read_from_disk_up_to_its_limit() { + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("users.csv"); + std::fs::write(&path, "user\nada\n").unwrap(); + let missing = scratch.path().join("missing.csv"); + + let data = read_file(path.to_str().unwrap()).unwrap(); + + assert_eq!(data.rows, [row(&[("user", "ada")])]); + assert_eq!(read_file(missing.to_str().unwrap()).unwrap_err().code, ErrorCode::FileAccess); + } + + /// A data file past the cap is refused before it is read whole (a defect once met). #[test] fn a_data_file_past_the_cap_is_refused_unread() { - let folder = tempfile::tempdir().unwrap(); - let path = folder.path().join("rows.csv"); + let scratch = tempfile::tempdir().unwrap(); + let path = scratch.path().join("rows.csv"); let file = std::fs::File::create(&path).unwrap(); file.set_len(RUN_DATA_LIMIT + 1).unwrap(); @@ -508,198 +571,307 @@ mod tests { assert_eq!(refused.params["fault"], "tooLarge"); } - /// A script that names its own request again stops at the cap, not at « Cancel » - /// (#1477, N21). - #[test] - fn a_run_stops_at_its_cap_only_when_it_would_go_on() { - assert!(!capped(MAX_STEPS - 1, Some(0))); - assert!(capped(MAX_STEPS, Some(0))); - assert!( - !capped(MAX_STEPS, None), - "a run that ends there is not capped" - ); + fn folder(id: &str, name: &str, children: Vec) -> HttpNode { + HttpNode::Folder { + folder: HttpFolder { + id: id.to_string(), + collection_id: "c-1".to_string(), + parent_id: None, + name: name.to_string(), + position: 0, + }, + children, + } } - use super::*; + fn request(id: &str) -> HttpNode { + HttpNode::Request { + request: HttpRequestSummary { + id: id.to_string(), + collection_id: "c-1".to_string(), + folder_id: None, + name: id.to_uppercase(), + kind: RequestKind::Http, + method: HttpMethod::Get, + position: 0, + }, + } + } - fn row(pairs: &[(&str, &str)]) -> BTreeMap { - pairs - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) + fn tree() -> HttpTree { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); + let collection = |id: &str, children| HttpCollectionNode { + collection: HttpCollection { + id: id.to_string(), + name: id.to_string(), + position: 0, + created_at: at, + }, + children, + }; + HttpTree { + collections: vec![ + collection( + "c-1", + vec![ + request("a"), + folder("f-1", "Auth", vec![request("b"), folder("f-2", "Deep", vec![request("c")])]), + request("d"), + ], + ), + collection("c-2", vec![request("other")]), + ], + } + } + + fn placed(item: HttpItemKind, id: &str) -> Vec<(String, Vec)> { + placed_under(&tree(), &HttpItem { kind: item, id: id.to_string() }) + .into_iter() + .map(|placed| (placed.id, placed.path)) .collect() } + /// Each request under a collection or a folder, in the tree's order, with the folders + /// between; another collection's never, and a request is nothing to run under. #[test] - fn a_csv_reads_with_its_header_quotes_and_blank_lines() { - let data = read_data( - "\u{feff}customer,amount,note\r\ncus_QX12a9,12,\"a, b\"\r\n\r\ncus_R7a01x,8,\"say \"\"hi\"\"\nthen\"\n", - ) - .unwrap(); - assert_eq!(data.columns, ["customer", "amount", "note"]); + fn the_requests_under_an_item_are_found_in_the_tree_s_order() { + let path = |names: &[&str]| names.iter().map(ToString::to_string).collect::>(); + assert_eq!( - data.rows, + placed(HttpItemKind::Collection, "c-1"), [ - row(&[ - ("customer", "cus_QX12a9"), - ("amount", "12"), - ("note", "a, b") - ]), - row(&[ - ("customer", "cus_R7a01x"), - ("amount", "8"), - ("note", "say \"hi\"\nthen") - ]), + ("a".to_string(), path(&[])), + ("b".to_string(), path(&["Auth"])), + ("c".to_string(), path(&["Auth", "Deep"])), + ("d".to_string(), path(&[])), ] ); - let short = read_data("a,b\n1").unwrap(); - assert_eq!(short.rows, [row(&[("a", "1"), ("b", "")])]); + assert_eq!(placed(HttpItemKind::Folder, "f-2"), [("c".to_string(), path(&[]))]); + assert!(placed(HttpItemKind::Folder, "missing").is_empty()); + assert!(placed(HttpItemKind::Request, "a").is_empty()); + } + + fn entry(id: &str, enabled: bool) -> RunEntry { + RunEntry { id: id.to_string(), enabled } } + /// The order last arranged, less what went since and once each, then what was added since + /// in the tree's order, switched on. #[test] - fn a_json_array_of_objects_reads_a_row_an_object() { - let data = - read_data(r#"[{"customer":"cus_1","amount":12},{"customer":"cus_2","vip":true}]"#) - .unwrap(); - assert_eq!(data.columns, ["customer", "amount", "vip"]); - assert_eq!( - data.rows[0], - row(&[("customer", "cus_1"), ("amount", "12")]) - ); - assert_eq!(data.rows[1], row(&[("customer", "cus_2"), ("vip", "true")])); + fn a_run_takes_the_order_last_arranged_and_what_came_since() { + let here: Vec = + placed_under(&tree(), &HttpItem { kind: HttpItemKind::Collection, id: "c-1".to_string() }); + let saved = [entry("d", false), entry("gone", true), entry("b", true), entry("d", true)]; + + let order = run_order(&saved, &here); + + assert_eq!(order, [entry("d", false), entry("b", true), entry("a", true), entry("c", true)]); } + /// `run:#.` belongs to its run; any other send to none. #[test] - fn a_file_that_is_neither_or_holds_nothing_is_said() { - assert_eq!(read_data("[1, 2]"), Err(DataFault::Unreadable)); - assert_eq!(read_data("a,b\n\"open"), Err(DataFault::Unreadable)); - assert_eq!(read_data("a,b\n"), Err(DataFault::Empty)); + fn a_send_says_the_run_it_belongs_to() { + assert_eq!(run_of("run:r-1#2.3"), Some("r-1")); + assert_eq!(run_of("run:r-1"), Some("r-1")); + assert_eq!(run_of("send-7"), None); + } + + fn held(name: &str) -> HttpRequest { + let at = crate::db::iso8601::parse("2026-07-25T09:00:00.000Z").unwrap(); + HttpRequest { + id: name.to_lowercase(), + collection_id: "c-1".to_string(), + folder_id: None, + name: name.to_string(), + kind: RequestKind::Graphql, + method: HttpMethod::Post, + document: RequestDocument::default(), + created_at: at, + updated_at: at, + } + } + + fn answer(tests: Vec, failure: Option) -> SentResponse { + SentResponse { + status: 201, + reason: "Created".to_string(), + millis: 42, + size: 3, + url: String::new(), + headers: Vec::new(), + body: String::new(), + binary: false, + cut: false, + incomplete: false, + redirects: Vec::new(), + language: Language::Txt, + pretty: None, + cookies: Vec::new(), + exchange: crate::http::send::Exchange { + method: HttpMethod::Post, + url: String::new(), + headers: Vec::new(), + body: crate::http::send::SentBody::None, + }, + graphql: None, + scripts: ScriptsAnswer { failure, tests, ..ScriptsAnswer::default() }, + } + } + + fn test(name: &str, passed: bool, skipped: bool) -> TestResult { + TestResult { name: name.to_string(), passed, skipped, ..TestResult::default() } + } + + /// An answer's status, time, tests and stop, its body kept only when asked; a skip is not a + /// failure; another error is kept as its code and what it states. + #[test] + fn a_request_of_a_run_ends_as_its_answer_says() { + let stop = ScriptStop { message: "boom".to_string(), ..ScriptStop::default() }; + let answered = result_of( + 2, + &held("Login"), + vec!["Auth".to_string()], + Ok(answer(vec![test("ok", true, false)], Some(stop.clone()))), + false, + ); + let kept = result_of(1, &held("Login"), Vec::new(), Ok(answer(Vec::new(), None)), true); + let skipped = result_of( + 1, + &held("Login"), + Vec::new(), + Err(AppError::new(ErrorCode::HttpScriptSkipped, String::new())), + true, + ); + let failed = result_of( + 1, + &held("Login"), + Vec::new(), + Err(AppError::with(ErrorCode::HttpTimeout, String::new(), "delay", "30 s")), + true, + ); + assert_eq!( - read_data("ceci n’est ni un CSV avec en-tête ni un tableau JSON\n"), - Err(DataFault::Unreadable), - "one line without a separator" + (answered.iteration, answered.request_id.as_str(), answered.name.as_str()), + (2, "login", "Login") ); - assert!(read_data("id\n1\n").is_ok(), "one column, with its rows"); assert_eq!( - read_data("customer\n"), - Err(DataFault::Empty), - "a header alone" + (answered.kind, answered.method, answered.path.as_slice()), + (RequestKind::Graphql, HttpMethod::Post, ["Auth".to_string()].as_slice()) + ); + assert_eq!((answered.status, answered.reason.as_str(), answered.millis), (Some(201), "Created", 42)); + assert_eq!((answered.tests.len(), answered.stop, answered.response), (1, Some(stop), None)); + assert!(kept.response.is_some()); + assert!(skipped.skipped && skipped.error.is_none() && !skipped.failed()); + assert_eq!( + failed.error, + Some(RunError { + code: ErrorCode::HttpTimeout, + params: BTreeMap::from([("delay".to_string(), "30 s".to_string())]) + }) ); - assert_eq!(read_data("[]"), Err(DataFault::Empty)); - assert_eq!(read_data(""), Err(DataFault::Empty)); } + /// No answer, a script that stopped, or a test that failed; a test skipped is no failure, and + /// a request skipped fails nothing. #[test] - fn the_order_kept_drops_what_is_gone_and_ends_on_what_was_added() { - let placed: Vec = ["a", "b", "c", "d"] - .iter() - .map(|id| Placed { - id: (*id).to_string(), - name: (*id).to_uppercase(), - path: Vec::new(), - }) - .collect(); - let entry = |id: &str, enabled: bool| RunEntry { - id: id.to_string(), - enabled, + fn a_result_fails_by_its_error_its_stop_or_a_test() { + let base = result_of( + 1, + &held("A"), + Vec::new(), + Ok(answer(vec![test("ok", true, false), test("later", false, true)], None)), + false, + ); + let failing_test = RunResult { tests: vec![test("bad", false, false)], ..base.clone() }; + let stopped = RunResult { stop: Some(ScriptStop::default()), ..base.clone() }; + let errored = RunResult { + error: Some(RunError { code: ErrorCode::HttpTimeout, params: BTreeMap::new() }), + ..base.clone() }; + let skipped = RunResult { skipped: true, ..failing_test.clone() }; - assert_eq!( - run_order(&[], &placed), - [ - entry("a", true), - entry("b", true), - entry("c", true), - entry("d", true) - ], - "nothing arranged: the tree's order" - ); - assert_eq!( - run_order( - &[ - entry("c", true), - entry("gone", true), - entry("a", false), - entry("c", false) - ], - &placed - ), - [ - entry("c", true), - entry("a", false), - entry("b", true), - entry("d", true) - ] + assert!(!base.failed()); + assert!(failing_test.failed() && stopped.failed() && errored.failed()); + assert!(!skipped.failed()); + } + + /// The requests that failed of those that ended, the tests that passed of those that ran. + #[test] + fn a_report_sums_up_its_failures_and_its_tests() { + let base = result_of( + 1, + &held("A"), + Vec::new(), + Ok(answer(vec![test("a", true, false), test("b", false, false), test("c", false, true)], None)), + false, ); + let clean = RunResult { tests: vec![test("d", true, false)], ..base.clone() }; + + let summary = RunSummary::of(&[base, clean]); + + assert_eq!(summary, RunSummary { failures: 1, requests: 2, passed: 2, tests: 3 }); + assert_eq!(RunSummary::of(&[]), RunSummary::default()); } + /// A request gone when its turn comes ends as the error that says so, under its place. #[test] - fn a_run_goes_on_follows_the_request_a_script_named_or_stops() { - let order: Vec = [("a", "Login"), ("b", "Payer"), ("c", "Reçu")] + fn a_request_gone_since_ends_as_its_error() { + let placed = + Placed { id: "r-9".to_string(), name: "Gone".to_string(), path: vec!["Auth".to_string()] }; + + let result = + gone(3, &placed, AppError::with(ErrorCode::HttpItemNotFound, String::new(), "id", "r-9")); + + assert_eq!((result.iteration, result.request_id.as_str(), result.name.as_str()), (3, "r-9", "Gone")); + assert_eq!(result.path, ["Auth"]); + assert_eq!(result.error.unwrap().code, ErrorCode::HttpItemNotFound); + assert_eq!(result.status, None); + } + + /// On, to the request a script named — by its name —, or to the end; a name not in the + /// order ends it too. + #[test] + fn a_run_goes_on_to_the_next_request_or_where_a_script_points() { + let order: Vec = ["a", "b", "c"] .iter() - .map(|(id, name)| Placed { - id: (*id).to_string(), - name: (*name).to_string(), - path: Vec::new(), - }) + .map(|name| Placed { id: (*name).to_string(), name: name.to_uppercase(), path: Vec::new() }) .collect(); + assert_eq!(next_index(&order, 0, None), Some(1)); assert_eq!(next_index(&order, 2, None), None); - let to = |name: &str| Next::To(name.to_string()); - assert_eq!(next_index(&order, 0, Some(&to("Reçu"))), Some(2)); - assert_eq!(next_index(&order, 2, Some(&to("Login"))), Some(0)); - assert_eq!(next_index(&order, 0, Some(&to("Ailleurs"))), None); + assert_eq!(next_index(&order, 2, Some(&Next::To("A".to_string()))), Some(0)); + assert_eq!(next_index(&order, 0, Some(&Next::To("missing".to_string()))), None); assert_eq!(next_index(&order, 0, Some(&Next::End)), None); } + /// A script naming its own request again would loop until « Cancel »: one iteration sends + /// at most so many, and only stops where it would go on. #[test] - fn a_result_fails_on_an_error_a_stop_or_a_failed_test_never_when_skipped() { - let base = RunResult { - iteration: 0, - request_id: "a".to_string(), - name: "Login".to_string(), - path: Vec::new(), - kind: RequestKind::Http, - method: HttpMethod::Get, - status: Some(200), - reason: "OK".to_string(), - millis: 1, - tests: vec![TestResult { - passed: true, - ..TestResult::default() - }], - error: None, - stop: None, - skipped: false, - response: None, - }; - assert!(!base.failed()); - let failing_test = RunResult { - tests: vec![TestResult::default()], - ..base.clone() - }; - assert!(failing_test.failed()); - assert!( - RunResult { - error: Some(RunError { - code: ErrorCode::HttpRefused, - params: BTreeMap::new(), - }), - ..base.clone() - } - .failed() - ); - assert!( - !RunResult { - skipped: true, - ..failing_test - } - .failed() - ); + fn an_iteration_stops_at_the_most_steps_it_sends() { + assert!(capped(MAX_STEPS, Some(0))); + assert!(!capped(MAX_STEPS - 1, Some(0))); + assert!(!capped(MAX_STEPS, None)); } + /// « Annuler » reaches the run and the send it is at; a run not under way is cancelled as far + /// as anyone asks, and answers no send; leaving cancels them all. #[test] - fn a_send_names_the_run_it_belongs_to() { - assert_eq!(run_of("run:7#0.3"), Some("7")); - assert_eq!(run_of("send-7"), None); + fn a_run_under_way_is_cancelled_with_the_send_it_is_at() { + let runs = Runs::default(); + runs.start("r-1"); + runs.start("r-2"); + assert!(!runs.cancelled("r-1")); + + runs.at("r-1", "run:r-1#1.1"); + runs.at("missing", "x"); + + assert_eq!(runs.cancel("r-1"), Some(Some("run:r-1#1.1".to_string()))); + assert!(runs.cancelled("r-1")); + assert_eq!(runs.cancel("missing"), None); + assert!(runs.cancelled("missing")); + runs.cancel_all(); + assert!(runs.cancelled("r-2")); + runs.finish("r-2"); + assert_eq!(runs.cancel("r-2"), None); } } diff --git a/crates/engine/src/http/scripts/around.rs b/crates/engine/src/http/scripts/around.rs index 9be05f413..1411d0a85 100644 --- a/crates/engine/src/http/scripts/around.rs +++ b/crates/engine/src/http/scripts/around.rs @@ -60,17 +60,9 @@ impl Around { scripts: &above.scripts, }) .collect(); - levels.push(Holder { - level: ScriptLevel::Request, - owner: None, - name: request, - scripts: own, - }); + levels.push(Holder { level: ScriptLevel::Request, owner: None, name: request, scripts: own }); Self { - before: levels - .iter() - .filter_map(|level| level.script(ScriptKind::Before)) - .collect(), + before: levels.iter().filter_map(|level| level.script(ScriptKind::Before)).collect(), after: levels .iter() .rev() @@ -84,11 +76,6 @@ impl Around { } } - #[must_use] - pub fn is_empty(&self) -> bool { - self.before.is_empty() && self.after.is_empty() && self.tests.is_empty() - } - /// What runs once the answer came: the scripts after it, then the tests. #[must_use] pub fn answered(&self) -> Veca"), + "a" + ); + } } diff --git a/crates/richtext/src/inlines.rs b/crates/richtext/src/inlines.rs index c3f936cb5..6635bdc8b 100644 --- a/crates/richtext/src/inlines.rs +++ b/crates/richtext/src/inlines.rs @@ -43,14 +43,8 @@ pub fn split(content: &[Inline], at: usize) -> (Vec, Vec) { right.push(inline.clone()); } else if let Inline::Text { text, marks } = inline { let byte = byte_of(text, at - seen); - left.push(Inline::Text { - text: text[..byte].to_owned(), - marks: marks.clone(), - }); - right.push(Inline::Text { - text: text[byte..].to_owned(), - marks: marks.clone(), - }); + left.push(Inline::Text { text: text[..byte].to_owned(), marks: marks.clone() }); + right.push(Inline::Text { text: text[byte..].to_owned(), marks: marks.clone() }); } seen += length; } @@ -58,9 +52,7 @@ pub fn split(content: &[Inline], at: usize) -> (Vec, Vec) { } fn byte_of(text: &str, chars: usize) -> usize { - text.char_indices() - .nth(chars) - .map_or(text.len(), |(at, _)| at) + text.char_indices().nth(chars).map_or(text.len(), |(at, _)| at) } pub fn insert(content: &mut Vec, at: usize, inline: Inline) { @@ -86,13 +78,8 @@ pub fn normalize(content: &mut Vec) { if inline.is_empty() { continue; } - if let ( - Some(Inline::Text { text, marks }), - Inline::Text { - text: more, - marks: worn, - }, - ) = (joined.last_mut(), &inline) + if let (Some(Inline::Text { text, marks }), Inline::Text { text: more, marks: worn }) = + (joined.last_mut(), &inline) && marks == worn { text.push_str(more); @@ -130,7 +117,7 @@ pub fn marks_at(content: &[Inline], at: usize) -> Marks { marks } -fn wears(marks: &Marks, mark: &Mark) -> bool { +pub fn wears(marks: &Marks, mark: &Mark) -> bool { match mark { Mark::Bold => marks.bold, Mark::Italic => marks.italic, @@ -179,51 +166,171 @@ mod tests { use super::*; fn bold(text: &str) -> Inline { - Inline::Text { - text: text.to_owned(), - marks: Marks { - bold: true, - ..Marks::default() - }, + let marks = Marks { bold: true, ..Marks::default() }; + let text = text.to_owned(); + Inline::Text { text, marks } + } + + fn linked(text: &str, href: &str) -> Inline { + let marks = Marks { link: Some(href.to_owned()), ..Marks::default() }; + let text = text.to_owned(); + Inline::Text { text, marks } + } + + #[test] + fn a_break_counts_one_and_reads_as_a_line_end() { + let content = [Inline::text("é"), Inline::HardBreak, bold("cd")]; + + assert_eq!(len(&content), 4); + assert_eq!(plain(&content), "é\ncd"); + assert!(Inline::text("").is_empty() && !Inline::HardBreak.is_empty()); + } + + #[test] + fn runs_are_split_at_a_char_each_half_with_its_marks() { + let content = [Inline::text("ab"), bold("cdé"), Inline::HardBreak]; + let whole = content.to_vec(); + + for (at, left) in [ + (0, vec![]), + (1, vec![Inline::text("a")]), + (2, vec![Inline::text("ab")]), + (4, vec![Inline::text("ab"), bold("cd")]), + (5, vec![Inline::text("ab"), bold("cdé")]), + (6, whole.clone()), + (9, whole.clone()), + ] { + let (before, after) = split(&content, at); + assert_eq!(before, left, "at {at}"); + let mut joined = [before, after].concat(); + normalize(&mut joined); + assert_eq!(joined, whole, "at {at}"); + } + } + + #[test] + fn a_run_goes_in_at_a_char_and_joins_one_of_its_marks() { + let mut content = vec![Inline::text("ab"), bold("c")]; + + insert(&mut content, 1, Inline::text("é")); + assert_eq!(content, [Inline::text("aéb"), bold("c")]); + insert(&mut content, 3, bold("x")); + assert_eq!(content, [Inline::text("aéb"), bold("xc")]); + insert(&mut content, 1, Inline::HardBreak); + assert_eq!(content, [Inline::text("a"), Inline::HardBreak, Inline::text("éb"), bold("xc")]); + } + + #[test] + fn what_is_deleted_goes_and_the_runs_around_it_join() { + for (range, left) in [ + (1..4, vec![Inline::text("a"), bold("é"), Inline::HardBreak]), + (0..0, vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak]), + (2..5, vec![Inline::text("ab"), Inline::HardBreak]), + (5..6, vec![Inline::text("ab"), bold("cdé")]), + (0..6, vec![]), + ] { + let mut content = vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak]; + delete(&mut content, range.clone()); + assert_eq!(content, left, "{range:?}"); } + let mut content = vec![Inline::text("a"), bold("b"), Inline::text("c")]; + delete(&mut content, 1..2); + assert_eq!(content, [Inline::text("ac")]); } #[test] - fn a_run_splits_inside_and_joins_back() { - let mut content = vec![Inline::text("ab"), bold("cdé"), Inline::HardBreak]; - let (left, right) = split(&content, 3); - assert_eq!(left, vec![Inline::text("ab"), bold("c")]); - assert_eq!(right, vec![bold("dé"), Inline::HardBreak]); - insert(&mut content, 5, bold("!")); - assert_eq!( - content, - vec![Inline::text("ab"), bold("cdé!"), Inline::HardBreak] - ); - delete(&mut content, 1..4); - assert_eq!( - content, - vec![Inline::text("a"), bold("é!"), Inline::HardBreak] - ); + fn runs_of_equal_marks_are_one_and_empty_ones_none() { + let mut content = vec![ + Inline::text(""), + bold("a"), + bold("b"), + Inline::text("c"), + bold(""), + Inline::text("d"), + Inline::HardBreak, + Inline::HardBreak, + ]; + normalize(&mut content); + + assert_eq!(content, [bold("ab"), Inline::text("cd"), Inline::HardBreak, Inline::HardBreak]); + } + + #[test] + fn typing_writes_with_the_marks_before_the_caret() { + let content = [Inline::text("ab"), bold("cd"), Inline::text("e")]; + let typed_bold = |at| marks_at(&content, at).bold; + + assert_eq!([0, 1, 2, 3, 4, 5].map(typed_bold), [false, false, false, true, true, false]); + assert!(marks_at(&[bold("a")], 0).bold, "with nothing before, those after"); + assert!(!marks_at(&[Inline::text("a"), Inline::HardBreak, bold("b")], 2).bold); + assert_eq!(marks_at(&[], 0), Marks::default()); + assert_eq!(marks_at(&[bold("a")], 4), Marks::default()); } + /// Text typed at a link's end is after it. #[test] - fn a_mark_toggles_over_a_range_and_typing_takes_the_one_before() { - let mut content = vec![Inline::text("hello")]; - set(&mut content, 1..3, &Mark::Bold, true); - assert!(has(&content, 1..3, &Mark::Bold)); - assert!(!has(&content, 0..3, &Mark::Bold)); - assert!(marks_at(&content, 3).bold); - assert!(!marks_at(&content, 1).bold); - set( - &mut content, - 0..5, - &Mark::Link(Some("https://a.fr".into())), - true, - ); - assert!(marks_at(&content, 2).link.is_some()); - assert!( - marks_at(&content, 5).link.is_none(), - "a link does not grow at its end" - ); + fn a_link_grows_from_inside_alone() { + let content = [Inline::text("a"), linked("bc", "u"), linked("d", "v")]; + let link_at = |at| marks_at(&content, at).link; + + assert_eq!([0, 1, 2, 3, 4].map(link_at), [None, None, Some("u".to_owned()), None, None]); + assert_eq!(marks_at(&content[1..], 0).link, Some("u".to_owned())); + } + + #[test] + fn a_range_wears_a_mark_where_every_char_of_it_does() { + let content = [Inline::text("a"), bold("b"), Inline::HardBreak, bold("c")]; + let has_bold = |range| has(&content, range, &Mark::Bold); + + assert!(has_bold(1..4), "a break wears any"); + assert!(has_bold(1..2) && has_bold(3..4) && has_bold(2..2)); + assert!(!has_bold(0..2) && !has_bold(0..4)); + assert!(!has(&content, 1..2, &Mark::Italic)); + } + + #[test] + fn each_mark_is_put_over_a_range_and_taken_off_it() { + let link = Mark::Link(Some("u".to_owned())); + for mark in [Mark::Bold, Mark::Italic, Mark::Strike, Mark::Code, link] { + let mut content = vec![Inline::text("abcd")]; + + set(&mut content, 1..3, &mark, true); + assert!(has(&content, 1..3, &mark), "{mark:?}"); + assert!(!has(&content, 0..2, &mark) && !has(&content, 2..4, &mark)); + assert_eq!(content.len(), 3); + + set(&mut content, 0..4, &mark, false); + assert_eq!(content, [Inline::text("abcd")], "{mark:?}"); + } + } + + #[test] + fn a_link_is_worn_by_its_own_address_and_none_by_no_link() { + let content = [linked("a", "u")]; + let to = |href: Option<&str>| Mark::Link(href.map(str::to_owned)); + + assert!(has(&content, 0..1, &to(Some("u")))); + assert!(!has(&content, 0..1, &to(Some("v"))) && !has(&content, 0..1, &to(None))); + assert!(has(&[Inline::text("a")], 0..1, &to(None))); + } + + #[test] + fn a_mark_is_put_on_text_alone() { + let mut content = vec![Inline::text("a"), Inline::HardBreak, Inline::text("b")]; + set(&mut content, 0..3, &Mark::Bold, true); + + assert_eq!(content, [bold("a"), Inline::HardBreak, bold("b")]); + } + + /// The first run after the caret says whether it is inside the link. + #[test] + fn a_caret_between_two_runs_of_one_link_is_inside_it() { + let mut second = linked("b", "u"); + if let Inline::Text { marks, .. } = &mut second { + marks.bold = true; + } + + let marks = marks_at(&[linked("a", "u"), second, Inline::text("c")], 1); + assert_eq!((marks.link.as_deref(), marks.bold), (Some("u"), false)); } } diff --git a/crates/richtext/src/model.rs b/crates/richtext/src/model.rs index c8d18a13e..bc3f2e366 100644 --- a/crates/richtext/src/model.rs +++ b/crates/richtext/src/model.rs @@ -2,10 +2,7 @@ /// The marks a run of text wears; a link is a mark, as the reference's schema had it. #[derive(Debug, Clone, Default, PartialEq, Eq, Hash)] -#[expect( - clippy::struct_excessive_bools, - reason = "marks are worn together, not one of a set" -)] +#[expect(clippy::struct_excessive_bools, reason = "marks are worn together, not one of a set")] pub struct Marks { pub bold: bool, pub italic: bool, @@ -26,10 +23,7 @@ pub enum Inline { impl Inline { pub fn text(text: impl Into) -> Self { - Inline::Text { - text: text.into(), - marks: Marks::default(), - } + Inline::Text { text: text.into(), marks: Marks::default() } } /// How many `char`s it takes: a break is one. @@ -113,10 +107,7 @@ pub struct Selection { impl Selection { pub fn caret(at: Position) -> Self { - Self { - anchor: at.clone(), - head: at, - } + Self { anchor: at.clone(), head: at } } pub fn is_empty(&self) -> bool { diff --git a/crates/richtext/src/picture.rs b/crates/richtext/src/picture.rs index e26a71cdc..aaa5193a7 100644 --- a/crates/richtext/src/picture.rs +++ b/crates/richtext/src/picture.rs @@ -49,9 +49,7 @@ pub(crate) fn written(src: &str, width: Option) -> String { reason = "clamped between the narrowest and the widest" )] pub fn width_near(percent: f32) -> u8 { - let stop = STOPS - .into_iter() - .find(|stop| (f32::from(*stop) - percent).abs() <= NEAR); + let stop = STOPS.into_iter().find(|stop| (f32::from(*stop) - percent).abs() <= NEAR); let within = percent.clamp(f32::from(NARROWEST), f32::from(WIDEST)); stop.unwrap_or_else(|| within.round() as u8) } @@ -59,11 +57,8 @@ pub fn width_near(percent: f32) -> u8 { /// A step wider or narrower, on a multiple of the step. pub fn width_beside(width: u8, wider: bool) -> u8 { const STEP: u8 = 5; - let stepped = if wider { - (width / STEP + 1) * STEP - } else { - width.div_ceil(STEP).saturating_sub(1) * STEP - }; + let stepped = + if wider { (width / STEP + 1) * STEP } else { width.div_ceil(STEP).saturating_sub(1) * STEP }; stepped.clamp(NARROWEST, WIDEST) } @@ -102,29 +97,24 @@ pub fn beside(document: &Document, path: &[usize], forward: bool) -> Option Selection { let before = match beside(document, path, false) { Some(Beside::Leaf(position)) => position, - _ => Position { - path: path.to_vec(), - offset: 0, - }, + _ => Position { path: path.to_vec(), offset: 0 }, }; if let Some((blocks, index)) = tree::siblings_mut(document, path) { blocks.remove(index); @@ -142,78 +132,156 @@ mod tests { #[test] fn the_width_is_read_and_written_back() { - let mut document = read_note(SIZED); + let document = read_note(SIZED); + assert_eq!(width(&document, &[1]), Some(50)); assert!(matches!( &document.blocks[1], Block::Image { src, .. } if src == "devnotes:drawing/a1" )); assert_eq!(write(&document), SIZED); + } + + #[test] + fn every_width_from_the_narrowest_to_the_widest_is_read() { + for (written, width_read) in [(9, None), (10, Some(10)), (100, Some(100)), (101, None)] { + let document = read_note(&format!("![a](devnotes:drawing/a1?w={written})")); + assert_eq!(width(&document, &[0]), width_read, "{written}"); + } + } + + #[test] + fn a_drawing_takes_a_width_and_gives_it_back() { + let mut document = read_note(SIZED); assert!(set_width(&mut document, &[1], Some(75))); assert!(!set_width(&mut document, &[1], Some(75)), "as it was"); assert!(write(&document).contains("devnotes:drawing/a1?w=75)")); - set_width(&mut document, &[1], None); + assert!(set_width(&mut document, &[1], None)); assert!(write(&document).contains("devnotes:drawing/a1)")); - assert!(!set_width(&mut document, &[0], Some(50)), "a paragraph"); } #[test] - fn what_is_not_a_width_is_left_as_written_and_the_drawing_still_found() { + fn what_is_no_drawing_takes_no_width() { + let mut document = read_note("text\n\n![a](https://a.fr/a.png?w=50)"); + + for path in [&[0][..], &[1], &[7], &[]] { + assert!(!set_width(&mut document, path, Some(50)), "{path:?}"); + assert_eq!(width(&document, path), None, "{path:?}"); + } + assert!(write(&document).contains("(https://a.fr/a.png?w=50)")); + } + + #[test] + fn what_is_not_a_width_is_left_as_written() { for query in ["w=5", "w=101", "w=large", "x=50", "w=50&x=1", "w="] { let written = format!("![a](devnotes:drawing/a1?{query})"); let document = read_note(&written); assert_eq!(width(&document, &[0]), None, "{query}"); assert_eq!(write(&document), written); } - assert_eq!(drawing_id("devnotes:drawing/a1?w=large"), Some("a1")); - assert_eq!(drawing_id("https://a.fr/a.png"), None); - let remote = "![a](https://a.fr/a.png?w=50)"; - let mut document = read_note(remote); - assert_eq!(width(&document, &[0]), None, "a query of its own"); - assert!(!set_width(&mut document, &[0], Some(50))); - assert_eq!(write(&document), remote); } #[test] - fn a_drag_stops_on_the_quarters_and_a_step_on_fives() { - let stopped = [23.0, 28.0, 51.4, 98.0, 140.0, 2.0, 61.0].map(width_near); - assert_eq!(stopped, [25, 25, 50, 100, 100, 10, 61]); - assert_eq!(width_beside(50, true), 55); - assert_eq!(width_beside(50, false), 45); - assert_eq!(width_beside(52, true), 55); - assert_eq!(width_beside(52, false), 50); - assert_eq!(width_beside(100, true), 100); - assert_eq!(width_beside(10, false), 10); + fn a_drawing_is_found_whatever_its_query() { + for (src, id) in [ + ("devnotes:drawing/a1", Some("a1")), + ("devnotes:drawing/a1?w=large", Some("a1")), + ("devnotes:drawing/a1?x=1?w=2", Some("a1")), + ("https://a.fr/a.png", None), + ("", None), + ] { + assert_eq!(drawing_id(src), id, "{src}"); + } + } + + #[test] + fn a_drag_stops_near_the_quarters() { + for (percent, stopped) in [ + (22.0, 25), + (21.9, 22), + (28.0, 25), + (28.1, 28), + (51.4, 50), + (72.0, 75), + (61.4, 61), + (61.5, 62), + (98.0, 100), + (140.0, 100), + (2.0, 10), + ] { + assert_eq!(width_near(percent), stopped, "{percent}"); + } + } + + #[test] + fn a_step_goes_to_the_next_multiple_of_five() { + for (width, narrower, wider) in + [(50, 45, 55), (52, 50, 55), (49, 45, 50), (100, 95, 100), (10, 10, 15), (12, 10, 15)] + { + assert_eq!((width_beside(width, false), width_beside(width, true)), (narrower, wider), "{width}"); + } + } + + fn leaf(path: &[usize], offset: usize) -> Beside { + let path = path.to_vec(); + Beside::Leaf(Position { path, offset }) } #[test] fn the_caret_meets_the_image_then_the_text_past_it() { let document = read_note(SIZED); + assert_eq!(beside(&document, &[0], true), Some(Beside::Image(vec![1]))); - let leaf = |path: usize, offset| { - Some(Beside::Leaf(Position { - path: vec![path], - offset, - })) - }; - assert_eq!(beside(&document, &[1], true), leaf(2, 0)); - assert_eq!(beside(&document, &[1], false), leaf(0, 5)); + assert_eq!(beside(&document, &[2], false), Some(Beside::Image(vec![1]))); + assert_eq!(beside(&document, &[1], true), Some(leaf(&[2], 0))); + assert_eq!(beside(&document, &[1], false), Some(leaf(&[0], 5))); + } + + #[test] + fn past_the_ends_there_is_nothing_to_meet() { + let document = read_note(SIZED); + + assert_eq!(beside(&document, &[0], false), None); assert_eq!(beside(&document, &[2], true), None); - let ruled = read_note("a\n\n---\n\nb"); - assert_eq!(beside(&ruled, &[0], true), leaf(2, 0)); + assert_eq!(beside(&document, &[9], true), None); } #[test] - fn removed_it_leaves_the_text_and_never_an_empty_note() { + fn a_rule_is_stepped_over_and_an_item_gone_into() { + let ruled = read_note("ab\n\n---\n\n---\n\n- c"); + assert_eq!(beside(&ruled, &[0], true), Some(leaf(&[3, 0, 0], 0))); + assert_eq!(beside(&ruled, &[3, 0, 0], false), Some(leaf(&[0], 2))); + } + + #[test] + fn an_image_removed_leaves_the_caret_in_the_text_before_it() { let mut document = read_note(SIZED); let selection = remove(&mut document, &[1]); + assert_eq!(write(&document), "avant\n\naprès"); - assert_eq!(selection.head.path, [0]); - assert_eq!(selection.head.offset, 5); + assert_eq!(selection, Selection::caret(Position { path: vec![0], offset: 5 })); + } + + #[test] + fn an_image_removed_first_leaves_the_caret_in_the_text_after_it() { + for markdown in ["![a](b)\n\naprès", "> ![a](b)\n\naprès", "![a](b)\n\n![c](d)\n\naprès"] { + let mut document = read_note(markdown); + let path = if markdown.starts_with('>') { vec![0, 0] } else { vec![0] }; + let selection = remove(&mut document, &path); + assert_eq!( + tree::leaf(&document, &selection.head.path).map(|leaf| leaf.len()), + Some(5), + "{markdown}" + ); + } + } + + #[test] + fn an_image_removed_alone_leaves_a_paragraph_to_type_in() { + let mut document = read_note("![a](devnotes:drawing/a1)"); + remove(&mut document, &[0]); - let mut alone = read_note("![a](devnotes:drawing/a1)"); - remove(&mut alone, &[0]); - assert_eq!(alone.blocks, [Block::Paragraph(Vec::new())]); + assert_eq!(document.blocks, [Block::Paragraph(Vec::new())]); } } diff --git a/crates/richtext/src/read.rs b/crates/richtext/src/read.rs index 247a47af8..a326ba717 100644 --- a/crates/richtext/src/read.rs +++ b/crates/richtext/src/read.rs @@ -53,12 +53,8 @@ struct Reader { const MAX_QUOTES: usize = 64; pub fn read(markdown: &str) -> Document { - let mut reader = Reader { - open: vec![Open::Blocks(Vec::new())], - marks: Marks::default(), - depth: [0; 3], - flattened: 0, - }; + let mut reader = + Reader { open: vec![Open::Blocks(Vec::new())], marks: Marks::default(), depth: [0; 3], flattened: 0 }; for event in Parser::new_ext(markdown, OPTIONS) { reader.event(event); } @@ -90,15 +86,10 @@ impl Reader { } Event::Text(text) => self.text(&text), Event::Code(code) => { - let marks = Marks { - code: true, - ..self.marks.clone() - }; - self.inline(Inline::Text { - text: code.into_string(), - marks, - }); + let marks = Marks { code: true, ..self.marks.clone() }; + self.inline(Inline::Text { text: code.into_string(), marks }); } + Event::InlineHtml(html) if is_break(&html) => self.inline(Inline::HardBreak), Event::Html(html) | Event::InlineHtml(html) => { let text = without_tags(&html); self.text(text.trim_end_matches('\n')); @@ -124,10 +115,7 @@ impl Reader { } let open = match tag { Tag::Paragraph => Open::Paragraph(Vec::new()), - Tag::Heading { level, .. } => Open::Heading { - level: heading_level(level), - content: Vec::new(), - }, + Tag::Heading { level, .. } => Open::Heading { level: heading_level(level), content: Vec::new() }, Tag::BlockQuote(_) if self.quotes() == MAX_QUOTES => { self.flattened += 1; return; @@ -145,10 +133,7 @@ impl Reader { kind: start.map_or(ListKind::Bullet, |start| ListKind::Ordered { start }), items: Vec::new(), }, - Tag::Item => Open::Item(Item { - checked: false, - blocks: Vec::new(), - }), + Tag::Item => Open::Item(Item { checked: false, blocks: Vec::new() }), Tag::Table(_) => Open::Table(Vec::new()), Tag::TableHead | Tag::TableRow => Open::Row(Vec::new()), Tag::TableCell => Open::Cell(Vec::new()), @@ -159,29 +144,19 @@ impl Reader { self.marks.link = Some(dest_url.into_string()); return; } - Tag::Image { dest_url, .. } => Open::Image { - src: dest_url.into_string(), - alt: String::new(), - }, + Tag::Image { dest_url, .. } => Open::Image { src: dest_url.into_string(), alt: String::new() }, _ => return, }; self.open.push(open); } fn quotes(&self) -> usize { - self.open - .iter() - .filter(|open| matches!(open, Open::Quote(_))) - .count() + self.open.iter().filter(|open| matches!(open, Open::Quote(_))).count() } fn mark(&mut self, which: usize, on: bool) { let depth = &mut self.depth[which]; - *depth = if on { - *depth + 1 - } else { - depth.saturating_sub(1) - }; + *depth = if on { *depth + 1 } else { depth.saturating_sub(1) }; let worn = *depth > 0; match which { 0 => self.marks.italic = worn, @@ -196,9 +171,10 @@ impl Reader { }; match open { Open::Blocks(blocks) => self.open.push(Open::Blocks(blocks)), - Open::Quote(blocks) => self.block(Block::Quote(blocks)), + Open::Quote(blocks) => self.block(Block::Quote(typed_in(blocks))), Open::List { kind, items } => self.block(Block::List { kind, items }), - Open::Item(item) => { + Open::Item(mut item) => { + item.blocks = typed_in(item.blocks); if let Some(Open::List { items, .. }) = self.open.last_mut() { items.push(item); } @@ -272,30 +248,18 @@ impl Reader { } if self.marks.link.is_some() { let marks = self.marks.clone(); - self.inline(Inline::Text { - text: text.to_owned(), - marks, - }); + self.inline(Inline::Text { text: text.to_owned(), marks }); return; } for (piece, link) in autolinks(text) { - let marks = Marks { - link, - ..self.marks.clone() - }; - self.inline(Inline::Text { - text: piece.to_owned(), - marks, - }); + let marks = Marks { link, ..self.marks.clone() }; + self.inline(Inline::Text { text: piece.to_owned(), marks }); } } /// Into the paragraph, heading or cell being read; a list's tight item opens one of its own. fn inline(&mut self, inline: Inline) { - if matches!( - self.open.last(), - Some(Open::Item(_) | Open::Blocks(_) | Open::Quote(_)) - ) { + if matches!(self.open.last(), Some(Open::Item(_) | Open::Blocks(_) | Open::Quote(_))) { self.open.push(Open::Loose(Vec::new())); } let Some( @@ -307,13 +271,8 @@ impl Reader { else { return; }; - if let ( - Some(Inline::Text { text, marks }), - Inline::Text { - text: more, - marks: worn, - }, - ) = (content.last_mut(), &inline) + if let (Some(Inline::Text { text, marks }), Inline::Text { text: more, marks: worn }) = + (content.last_mut(), &inline) && marks == worn { text.push_str(more); @@ -323,6 +282,14 @@ impl Reader { } } +/// An item or a quote with nothing in it holds a paragraph to type in. +fn typed_in(blocks: Vec) -> Vec { + if blocks.is_empty() { + return vec![Block::Paragraph(Vec::new())]; + } + blocks +} + fn is_block(tag: &Tag<'_>) -> bool { matches!( tag, @@ -348,6 +315,11 @@ fn heading_level(level: HeadingLevel) -> u8 { } } +/// `
`, how a cell or a heading writes a break. +fn is_break(html: &str) -> bool { + html.trim_matches(['<', '>', '/', ' ']).eq_ignore_ascii_case("br") +} + /// HTML read as the text it shows. fn without_tags(html: &str) -> String { let mut text = String::new(); @@ -367,14 +339,8 @@ fn without_tags(html: &str) -> String { fn autolinks(text: &str) -> Vec<(&str, Option)> { let mut pieces = Vec::new(); let mut rest = text; - while let Some(at) = ["https://", "http://"] - .iter() - .filter_map(|scheme| rest.find(scheme)) - .min() - { - let end = rest[at..] - .find(char::is_whitespace) - .map_or(rest.len(), |end| at + end); + while let Some(at) = ["https://", "http://"].iter().filter_map(|scheme| rest.find(scheme)).min() { + let end = rest[at..].find(char::is_whitespace).map_or(rest.len(), |end| at + end); let url = rest[at..end].trim_end_matches(['.', ',', ';', ':', '!', '?', ')']); let end = at + url.len(); if !rest[..at].is_empty() { @@ -388,3 +354,168 @@ fn autolinks(text: &str) -> Vec<(&str, Option)> { } pieces } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_item_or_quote_has_a_paragraph_to_type_in() { + let empty = Block::Paragraph(Vec::new()); + let item = |checked| Item { checked, blocks: vec![empty.clone()] }; + for (markdown, kind, checked) in [ + ("-", ListKind::Bullet, false), + ("2.", ListKind::Ordered { start: 2 }, false), + ("- [x] \n", ListKind::Task, true), + ] { + let items = vec![item(checked)]; + assert_eq!(read(markdown).blocks, [Block::List { kind, items }], "{markdown}"); + } + assert_eq!(read(">").blocks, [Block::Quote(vec![empty])]); + } + + #[test] + fn a_break_written_in_html_is_a_break() { + for html in ["
", "
", "
", "
"] { + let document = read(&format!("a{html}b")); + let expected = vec![Inline::text("a"), Inline::HardBreak, Inline::text("b")]; + assert_eq!(document.blocks, [Block::Paragraph(expected)], "{html}"); + } + let document = read("ab"); + assert_eq!(document.blocks, [Block::Paragraph(vec![Inline::text("ab")])]); + } + + fn only(markdown: &str) -> Block { + let mut blocks = read(markdown).blocks; + assert_eq!(blocks.len(), 1, "{markdown}"); + blocks.remove(0) + } + + fn run(text: &str, marks: Marks) -> Inline { + let text = text.to_owned(); + Inline::Text { text, marks } + } + + #[test] + fn marks_nest_and_end_where_they_end() { + let italic = Marks { italic: true, ..Marks::default() }; + let both = Marks { bold: true, ..italic.clone() }; + assert_eq!( + only("*a **b** c* d"), + Block::Paragraph(vec![ + run("a ", italic.clone()), + run("b", both), + run(" c", italic.clone()), + Inline::text(" d") + ]) + ); + assert_eq!(only("*a *b* c* d"), Block::Paragraph(vec![run("a b c", italic), Inline::text(" d")])); + } + + #[test] + fn a_bare_address_is_a_link_to_itself_without_the_mark_that_ends_its_sentence() { + let links = |text: &str| -> Vec { + autolinks(text).into_iter().filter_map(|(_, link)| link).collect() + }; + + assert_eq!(links("voir https://a.fr."), ["https://a.fr"]); + assert_eq!(links("(http://a.fr/b?c=d), puis https://e.fr!"), ["http://a.fr/b?c=d", "https://e.fr"]); + assert_eq!(links("https://a.fr\nb"), ["https://a.fr"]); + assert!(links("a.fr, ftp://b.fr").is_empty()); + assert_eq!( + autolinks("a https://b c"), + [("a ", None), ("https://b", Some("https://b".to_owned())), (" c", None)] + ); + } + + #[test] + fn an_address_inside_a_link_is_that_link_s() { + let link = Marks { link: Some("https://b".to_owned()), ..Marks::default() }; + assert_eq!(only("[https://a](https://b)"), Block::Paragraph(vec![run("https://a", link)])); + } + + #[test] + fn html_is_the_text_it_shows() { + for (html, text) in + [("a b > c", "a b > c"), ("
\na\n
", "a"), ("a c", "a c")] + { + let shown = match only(html) { + Block::Paragraph(content) => crate::inlines::plain(&content), + other => panic!("{other:?}"), + }; + assert_eq!(shown, text, "{html}"); + } + } + + #[test] + fn an_image_among_words_stands_between_two_paragraphs() { + let blocks = read("a ![b *c*](d) e").blocks; + + assert_eq!(blocks.len(), 3); + assert!(matches!(&blocks[1], Block::Image { alt, src, .. } if alt == "b c" && src == "d")); + assert_eq!(read("![b](d)").blocks.len(), 1); + } + + #[test] + fn an_image_in_a_heading_or_a_cell_is_left_out() { + for markdown in ["# a ![b](c)", "| a ![b](c) |\n| --- |"] { + assert_eq!(read(markdown).blocks.len(), 1, "{markdown}"); + } + } + + #[test] + fn a_tight_item_s_text_comes_before_the_blocks_under_it() { + let Block::List { items, .. } = only("- a\n > b\n- c\n - d\n\n e") else { + panic!("a list"); + }; + + let kinds = |item: &Item| item.blocks.iter().map(std::mem::discriminant).collect::>(); + let paragraph = std::mem::discriminant(&Block::Paragraph(Vec::new())); + assert_eq!(items.len(), 2); + assert!(items.iter().all(|item| item.blocks.len() == 2 && kinds(item)[0] == paragraph)); + } + + #[test] + fn a_box_makes_its_list_a_task_list() { + let Block::List { kind, items } = only("1. [x] a\n2. [ ] b") else { + panic!("a list"); + }; + + assert_eq!(kind, ListKind::Task); + assert_eq!(items.iter().map(|item| item.checked).collect::>(), [true, false]); + } + + #[test] + fn a_fence_gives_its_language_and_an_indented_block_none() { + let code = |markdown: &str| match only(markdown) { + Block::CodeBlock { language, text } => (language, text), + other => panic!("{other:?}"), + }; + + assert_eq!(code("```rust\na\n\n```"), ("rust".into(), "a\n".into())); + assert_eq!(code(" a\n b"), (String::new(), "a\nb".into())); + assert_eq!(code("```\n```"), (String::new(), String::new())); + } + + /// The quotes past the depth kept are read as the one around them. + #[test] + fn quotes_nested_too_deep_are_flattened_and_their_text_kept_in_order() { + let deep = "> ".repeat(MAX_QUOTES + 5); + let mut block = only(&format!("{deep}a\n>\n> b")); + + let mut depth = 0; + let mut texts = Vec::new(); + while let Block::Quote(inner) = block { + depth += 1; + for other in &inner[1..] { + if let Block::Paragraph(content) = other { + texts.push(crate::inlines::plain(content)); + } + } + block = inner.into_iter().next().unwrap(); + } + assert_eq!(depth, MAX_QUOTES); + assert_eq!(block, Block::Paragraph(vec![Inline::text("a")])); + assert_eq!(texts, ["b"]); + } +} diff --git a/crates/richtext/src/rules.rs b/crates/richtext/src/rules.rs index c2771b211..dceccde6e 100644 --- a/crates/richtext/src/rules.rs +++ b/crates/richtext/src/rules.rs @@ -32,10 +32,7 @@ pub fn after_typing(document: &mut Document, selection: &Selection) -> Option Option Option { let start = number.parse().unwrap_or(1); return Some(BlockRule::List(ListKind::Ordered { start }, false)); } - let fence = body - .strip_prefix("```") - .or_else(|| body.strip_prefix("~~~"))?; + let fence = body.strip_prefix("```").or_else(|| body.strip_prefix("~~~"))?; fence .chars() .all(|glyph| glyph.is_ascii_lowercase()) .then(|| BlockRule::Code(fence.to_owned())) } -fn apply_block( - document: &mut Document, - selection: &Selection, - rule: BlockRule, - typed: usize, -) -> Selection { +fn apply_block(document: &mut Document, selection: &Selection, rule: BlockRule, typed: usize) -> Selection { let path = selection.head.path.clone(); let cleared = edit::delete_selection( document, &Selection { - anchor: crate::model::Position { - path: path.clone(), - offset: 0, - }, - head: crate::model::Position { - path, - offset: typed, - }, + anchor: crate::model::Position { path: path.clone(), offset: 0 }, + head: crate::model::Position { path, offset: typed }, }, ); match rule { @@ -124,12 +105,16 @@ fn apply_block( edit::set_heading(document, &cleared, Some(level)); cleared } + // Typed again in its own quote or list, a marker is only taken out. + BlockRule::Quote if edit::in_quote(document, &cleared.head.path) => cleared, BlockRule::Quote => edit::toggle_quote(document, &cleared), BlockRule::List(kind, checked) => { - let listed = edit::toggle_list(document, &cleared, kind); - if checked - && let Some((list, item, _)) = tree::innermost_item(document, &listed.head.path) - { + let listed = if in_list(document, &cleared, kind) { + cleared + } else { + edit::toggle_list(document, &cleared, kind) + }; + if checked && let Some((list, item, _)) = tree::innermost_item(document, &listed.head.path) { edit::toggle_task(document, &list, item); } listed @@ -139,6 +124,15 @@ fn apply_block( } } +fn in_list(document: &Document, selection: &Selection, kind: ListKind) -> bool { + let list = tree::innermost_item(document, &selection.head.path); + let current = list.and_then(|(list, _, _)| match tree::block(document, &list) { + Some(Block::List { kind, .. }) => Some(std::mem::discriminant(kind)), + _ => None, + }); + current == Some(std::mem::discriminant(&kind)) +} + /// A mark closed at the end of `text`: the mark, where its opening delimiter starts, the inner /// range, and the closing delimiter's length — all in `char`s. fn mark_rule(text: &str) -> Option<(Mark, usize, std::ops::Range, usize)> { @@ -180,10 +174,7 @@ fn emphasis(glyphs: &[char], delimiter: &str) -> Option<(usize, std::ops::Range< } let inner = open + width..close; let flanked = open == 0 || glyphs[open - 1].is_whitespace(); - let filled = !inner.is_empty() - && !glyphs[inner.clone()] - .iter() - .all(|glyph| glyph.is_whitespace()); + let filled = !inner.is_empty() && !glyphs[inner.clone()].iter().all(|glyph| glyph.is_whitespace()); let clean = !glyphs[inner.clone()].contains(&mark); (flanked && filled && clean).then_some((open, inner)) } diff --git a/crates/richtext/src/rules/tests.rs b/crates/richtext/src/rules/tests.rs index ae013c2ac..5edb5490f 100644 --- a/crates/richtext/src/rules/tests.rs +++ b/crates/richtext/src/rules/tests.rs @@ -4,53 +4,247 @@ use super::*; use crate::model::{Marks, Position}; use crate::{read, write}; -/// What a fresh Note holds after `typed`, each rule applied as it closes. -fn typed(typed: &str) -> String { - let mut document = read(""); - document.blocks.push(Block::Paragraph(Vec::new())); - let mut selection = Selection::caret(Position { - path: vec![0], - offset: 0, - }); - for glyph in typed.chars() { - selection = edit::insert_text( - &mut document, - &selection, - &glyph.to_string(), - &Marks::default(), - ); +/// What `markdown` holds once `text` is typed at the end of its last text, each rule applied as +/// it closes. +fn typed_in(markdown: &str, text: &str) -> Document { + let mut document = read(markdown); + if document.blocks.is_empty() { + document.blocks.push(Block::Paragraph(Vec::new())); + } + let path = tree::leaves(&document).pop().unwrap(); + let offset = tree::leaf(&document, &path).unwrap().len(); + let mut selection = Selection::caret(Position { path, offset }); + for glyph in text.chars() { + let glyph = glyph.to_string(); + selection = edit::insert_text(&mut document, &selection, &glyph, &Marks::default()); if let Some(applied) = after_typing(&mut document, &selection) { selection = applied.selection; } } - write(&document) + document +} + +fn typed(text: &str) -> String { + write(&typed_in("", text)) +} + +/// Read back, what was typed is one paragraph of that text. +fn stays(text: &str) -> bool { + let expected = Block::Paragraph(vec![Inline::text(text)]); + typed_in("", text).blocks == [expected] +} + +#[test] +fn a_paragraph_s_start_becomes_the_block_it_writes() { + for (text, markdown) in [ + ("# a", "# a"), + ("###### a", "###### a"), + ("> a", "> a"), + (" > a", "> a"), + ("- a", "- a"), + ("+ a", "- a"), + ("* a", "- a"), + ("1. a", "1. a"), + ("12. a", "12. a"), + ("[] a", "- [ ] a"), + ("[ ] a", "- [ ] a"), + ("[(] a", "- [ ] a"), + ("[x] a", "- [x] a"), + ("``` a", "```\na\n```"), + ("~~~ a", "```\na\n```"), + ("```sql a", "```sql\na\n```"), + ("---", "---"), + ("—-", "---"), + ("___ ", "---"), + ("*** ", "---"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } +} + +#[test] +fn a_start_that_writes_no_block_stays_text() { + for text in [ + "####### a", + "#a", + "a # b", + "a - b", + "1 . a", + "1) a", + ". a", + "a1. b", + "-a", + "--", + "__ ", + "** ", + "[y] a", + "[xx] a", + "```C a", + ">a", + "a > b", + "a ---", + "—— ", + ] { + let document = typed_in("", text); + assert!(matches!(document.blocks.as_slice(), [Block::Paragraph(_)]), "{text}: {document:?}"); + } +} + +/// The rule reads what is before the caret; what is after it stays in the block. +#[test] +fn a_rule_typed_before_a_text_keeps_it() { + let mut document = read("a"); + let start = Selection::caret(Position { path: vec![0], offset: 0 }); + let hash = edit::insert_text(&mut document, &start, "# ", &Marks::default()); + + let applied = after_typing(&mut document, &hash).unwrap(); + assert_eq!(write(&document), "# a"); + assert_eq!(applied.selection, start); + assert_eq!(applied.mark, None); +} + +#[test] +fn a_block_rule_is_for_a_paragraph_alone() { + for markdown in ["# ", "| a |\n| --- |", "```\n```"] { + let after = typed_in(markdown, "# "); + let path = tree::leaves(&after).pop().unwrap(); + let text = match tree::leaf(&after, &path) { + Some(Leaf::Inlines(content)) => inlines::plain(content), + Some(Leaf::Code(text)) => text.clone(), + None => String::new(), + }; + assert!(text.ends_with("# "), "{markdown}: {text:?}"); + } +} + +#[test] +fn a_rule_in_an_item_is_of_that_item() { + for (text, markdown) in [ + ("- # a", "- # a"), + ("- [ ] a", "- [ ] a"), + ("- [x] a", "- [x] a"), + ("- 1. a", "1. a"), + ("- ```js a", "- ```js\n a\n ```"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } +} + +#[test] +fn a_mark_closed_at_the_caret_is_put_on_what_it_encloses() { + for (text, markdown) in [ + ("**a b**", "**a b**"), + ("du **gras** ici", "du **gras** ici"), + ("__a__", "**a**"), + ("un *mot*", "un *mot*"), + ("un _mot_", "un *mot*"), + ("~~a~~", "~~a~~"), + ("a `b` c", "a `b` c"), + ("a`b`", "a`b`"), + ("`a b `", "`a b `"), + ("**é**x", "**é**x"), + ] { + assert_eq!(typed(text), markdown, "{text}"); + } } +/// What is typed next does not wear it. #[test] -fn block_rules_turn_the_paragraph_into_what_its_start_writes() { - assert_eq!(typed("## Titre"), "## Titre"); - assert_eq!(typed("> cité"), "> cité"); - assert_eq!(typed("- un"), "- un"); - assert_eq!(typed("+ un"), "- un"); - assert_eq!(typed("3. trois"), "3. trois"); - assert_eq!(typed("[x] fait"), "- [x] fait"); - assert_eq!(typed("[ ] à faire"), "- [ ] à faire"); - assert_eq!(typed("```sql code"), "```sql\ncode\n```"); - assert_eq!(typed("---"), "---"); - assert_eq!(typed("####### sept"), "####### sept", "seven is no heading"); +fn the_mark_applied_is_named() { + for (text, mark) in + [("**a**", Mark::Bold), ("*a*", Mark::Italic), ("~~a~~", Mark::Strike), ("`a`", Mark::Code)] + { + let mut document = read(""); + document.blocks.push(Block::Paragraph(vec![Inline::text(text)])); + let end = Position { path: vec![0], offset: text.chars().count() }; + + let applied = after_typing(&mut document, &Selection::caret(end)).unwrap(); + assert_eq!(applied.mark, Some(mark), "{text}"); + assert_eq!(applied.selection, Selection::caret(Position { path: vec![0], offset: 1 })); + } } #[test] -fn marks_close_at_the_caret_and_spaced_emphasis_stays_as_typed() { - assert_eq!(typed("du **gras** ici"), "du **gras** ici"); - assert_eq!(typed("un *mot*"), "un *mot*"); - assert_eq!(typed("un _mot_"), "un *mot*"); - assert_eq!(typed("du ~~barré~~"), "du ~~barré~~"); - assert_eq!(typed("du `code`"), "du `code`"); - assert_eq!(typed("2 * 3 * 4"), "2 * 3 * 4"); - assert_eq!( - typed("snake_case_name"), +fn what_encloses_nothing_or_stands_in_a_word_stays_text() { + for text in [ + "2 * 3 * 4", + "2 *3 * 4", + "2 * 3* 4", + "a*b*", "snake_case_name", - "no italic inside a word" - ); + "a**b**", + "a~~b~~", + "****", + "** **", + "a * *", + "~~~~", + "~a~", + "`", + "``", + "``a`", + "** a", + "*a", + "__", + "_ _", + "**a*", + ] { + assert!(stays(text), "{text}: {:?}", typed_in("", text)); + } +} + +#[test] +fn nothing_is_read_inside_code() { + let mut document = read("`a *b`"); + let code = Marks { code: true, ..Marks::default() }; + let end = Selection::caret(Position { path: vec![0], offset: 4 }); + + let after = edit::insert_text(&mut document, &end, "*", &code); + assert!(after_typing(&mut document, &after).is_none()); + assert_eq!(write(&document), "`a *b*`"); +} + +#[test] +fn nothing_is_read_over_a_selection_or_off_a_text() { + let mut document = read("*a*"); + let place = |path: usize, offset| Position { path: vec![path], offset }; + document.blocks = vec![Block::Paragraph(vec![Inline::text("*a*")])]; + + let selected = Selection { anchor: place(0, 0), head: place(0, 3) }; + assert!(after_typing(&mut document, &selected).is_none()); + assert!(after_typing(&mut document, &Selection::caret(place(4, 0))).is_none()); + let mut code = read("```\n*a*\n```"); + assert!(after_typing(&mut code, &Selection::caret(place(0, 3))).is_none()); +} + +/// Under a hundred billion billions: past that, a number has no start of its own. +#[test] +fn a_number_too_long_to_hold_starts_at_one() { + assert_eq!(typed(&format!("{}. a", "9".repeat(30))), "1. a"); +} + +/// Enter has opened the next item already: its marker typed by habit is not a second one. +#[test] +fn a_marker_typed_in_its_own_list_or_quote_is_only_taken_out() { + for (markdown, marker, after) in [ + ("- a\n- b", "- ", "- a\n- b\n- c"), + ("1. a\n2. b", "3. ", "1. a\n2. b\n3. c"), + ("- [ ] a", "[ ] ", "- [ ] a\n- [ ] c"), + ("- [ ] a", "[x] ", "- [ ] a\n- [x] c"), + ("> a", "> ", "> a\n>\n> c"), + ("- a", "[ ] ", "- [ ] a\n- [ ] c"), + ("- a", "1. ", "1. a\n2. c"), + ] { + let mut document = read(markdown); + let path = tree::leaves(&document).pop().unwrap(); + let end = Selection::caret(Position { path, offset: 1 }); + let mut selection = edit::split(&mut document, &end); + for glyph in format!("{marker}c").chars() { + let glyph = glyph.to_string(); + selection = edit::insert_text(&mut document, &selection, &glyph, &Marks::default()); + if let Some(applied) = after_typing(&mut document, &selection) { + selection = applied.selection; + } + } + assert_eq!(write(&document), after, "{marker:?} in {markdown:?}"); + } } diff --git a/crates/richtext/src/table.rs b/crates/richtext/src/table.rs index aa9d71d6c..7d44bedf8 100644 --- a/crates/richtext/src/table.rs +++ b/crates/richtext/src/table.rs @@ -9,9 +9,7 @@ use crate::tree; pub fn insert(document: &mut Document, selection: &Selection) -> Selection { let after = crate::edit::after_top(document, selection); let row = || vec![Cell::new(); 3]; - document - .blocks - .insert(after, Block::Table(vec![row(), row(), row()])); + document.blocks.insert(after, Block::Table(vec![row(), row(), row()])); caret(vec![after, 0, 0]) } @@ -22,8 +20,7 @@ fn caret(path: Vec) -> Selection { /// The table the caret is in: its path, the caret's row and column. pub fn cell_of(document: &Document, path: &[usize]) -> Option<(Vec, usize, usize)> { let (table, at) = path.split_at(path.len().checked_sub(2)?); - matches!(tree::block(document, table), Some(Block::Table(_))) - .then(|| (table.to_vec(), at[0], at[1])) + matches!(tree::block(document, table), Some(Block::Table(_))).then(|| (table.to_vec(), at[0], at[1])) } fn rows_mut<'a>(document: &'a mut Document, table: &[usize]) -> Option<&'a mut Vec>> { @@ -88,10 +85,7 @@ pub fn delete_column(document: &mut Document, selection: &Selection) -> Selectio if left == 0 { return delete(document, selection); } - clamped( - document, - [table.as_slice(), &[row, column.min(left - 1)]].concat(), - ) + clamped(document, [table.as_slice(), &[row, column.min(left - 1)]].concat()) } /// The whole table out; the caret where it stood, on the next text. @@ -139,40 +133,172 @@ mod tests { use super::*; use crate::{read, write}; + const TABLE: &str = "x\n\n| a | b |\n| --- | --- |\n| c | d |\n\ny"; + fn at(path: &[usize]) -> Selection { caret(path.to_vec()) } + /// Each row as its cells' text. + fn cells(document: &Document) -> Vec> { + document + .blocks + .iter() + .find_map(|block| match block { + Block::Table(rows) => Some(rows), + _ => None, + }) + .map(|rows| { + let row = |row: &Vec| row.iter().map(|cell| crate::inlines::plain(cell)).collect(); + rows.iter().map(row).collect() + }) + .unwrap_or_default() + } + + type Edit = fn(&mut Document, &Selection) -> Selection; + + fn after(edit: Edit, row: usize, column: usize) -> (Vec>, Vec) { + let mut document = read(TABLE); + let selection = edit(&mut document, &at(&[1, row, column])); + (cells(&document), selection.head.path) + } + #[test] - fn rows_and_columns_come_and_go_and_the_table_with_them() { - let mut document = read("| a | b |\n| --- | --- |\n| 1 | 2 |"); - let after = add_row_after(&mut document, &at(&[0, 1, 1])); - assert_eq!(after, at(&[0, 2, 1])); - let after = add_column_after(&mut document, &at(&[0, 0, 0])); - assert_eq!(after, at(&[0, 0, 1])); - assert_eq!( - write(&document), - "| a | | b |\n| --- | --- | --- |\n| 1 | | 2 |\n| | | |" - ); - delete_column(&mut document, &at(&[0, 0, 1])); - delete_row(&mut document, &at(&[0, 2, 0])); + fn a_new_table_goes_after_the_top_block_three_rows_of_three_columns() { + for (markdown, path, landed) in + [("a\n\nb", vec![0], 1), ("- a\n- b", vec![0, 1, 0], 1), ("a", vec![7], 1)] + { + let mut document = read(markdown); + let selection = insert(&mut document, &at(&path)); + assert_eq!(selection, at(&[landed, 0, 0])); + assert_eq!(cells(&document), vec![vec![String::new(); 3]; 3]); + assert!(matches!(document.blocks[landed], Block::Table(_))); + } + } + + #[test] + fn a_cell_is_its_table_its_row_and_its_column() { + let document = read("- | a | b |\n | --- | --- |\n | c | d |\n- e"); + + assert_eq!(cell_of(&document, &[0, 0, 0, 1, 0]), Some((vec![0, 0, 0], 1, 0))); + for path in [&[0, 1, 0][..], &[0], &[]] { + assert_eq!(cell_of(&document, path), None, "{path:?}"); + } + } + + #[test] + fn a_row_is_added_under_the_caret_s() { assert_eq!( - write(&document), - "| a | b |\n| --- | --- |\n| 1 | 2 |" + after(add_row_after, 0, 1), + ( + vec![vec!["a".into(), "b".into()], vec![String::new(); 2], vec!["c".into(), "d".into()]], + vec![1, 1, 1] + ) ); - delete(&mut document, &at(&[0, 1, 0])); - assert_eq!(write(&document), ""); + assert_eq!(after(add_row_after, 1, 0).1, [1, 2, 0]); } #[test] - fn tab_walks_the_cells_and_adds_a_row_past_the_last() { - let mut document = read("| a | b |\n| --- | --- |\n| 1 | 2 |"); - assert_eq!(step(&mut document, &at(&[0, 0, 1]), false), at(&[0, 1, 0])); - assert_eq!(step(&mut document, &at(&[0, 1, 0]), true), at(&[0, 0, 1])); - assert_eq!(step(&mut document, &at(&[0, 1, 1]), false), at(&[0, 2, 0])); + fn a_column_is_added_right_of_the_caret_s() { assert_eq!( - write(&document), - "| a | b |\n| --- | --- |\n| 1 | 2 |\n| | |" + after(add_column_after, 1, 0), + ( + vec![ + vec!["a".into(), String::new(), "b".into()], + vec!["c".into(), String::new(), "d".into()] + ], + vec![1, 1, 1] + ) ); + assert_eq!(after(add_column_after, 0, 1).0[0], ["a", "b", ""]); + } + + /// Imported, a row can hold fewer cells than the others. + #[test] + fn a_column_is_added_at_the_end_of_a_row_too_short() { + let cell = |text: &str| vec![crate::Inline::text(text)]; + let mut document = + Document { blocks: vec![Block::Table(vec![vec![cell("a"), cell("b")], vec![cell("c")]])] }; + + add_column_after(&mut document, &at(&[0, 0, 1])); + assert_eq!(cells(&document), [vec!["a", "b", ""], vec!["c", ""]]); + delete_column(&mut document, &at(&[0, 0, 2])); + assert_eq!(cells(&document), [vec!["a", "b"], vec!["c", ""]]); + } + + #[test] + fn the_caret_s_row_goes_and_the_caret_is_in_the_one_that_takes_its_place() { + assert_eq!(after(delete_row, 0, 1), (vec![vec!["c".into(), "d".into()]], vec![1, 0, 1])); + assert_eq!(after(delete_row, 1, 1), (vec![vec!["a".into(), "b".into()]], vec![1, 0, 1])); + } + + #[test] + fn the_caret_s_column_goes_and_the_caret_is_in_the_one_that_takes_its_place() { + assert_eq!(after(delete_column, 1, 0), (vec![vec!["b".into()], vec!["d".into()]], vec![1, 1, 0])); + assert_eq!(after(delete_column, 1, 1).1, [1, 1, 0]); + } + + #[test] + fn the_last_row_or_the_last_column_takes_the_table_with_it() { + for edit in [delete_row as Edit, delete_column] { + let mut document = read("x\n\n| a |\n| --- |\n\ny"); + let selection = edit(&mut document, &at(&[1, 0, 0])); + assert_eq!(write(&document), "x\n\ny"); + assert_eq!(selection, at(&[1])); + } + } + + #[test] + fn a_table_deleted_leaves_the_caret_in_the_next_text() { + let mut document = read(TABLE); + assert_eq!(delete(&mut document, &at(&[1, 0, 1])), at(&[1])); + assert_eq!(write(&document), "x\n\ny"); + } + + #[test] + fn a_table_deleted_alone_leaves_a_paragraph_to_type_in() { + for markdown in ["| a |\n| --- |", "> | a |\n> | --- |"] { + let mut document = read(markdown); + let path = tree::leaves(&document).remove(0); + let selection = delete(&mut document, &at(&path)); + let left = tree::leaves(&document); + assert_eq!(left.len(), 1, "{markdown}"); + assert_eq!(selection, at(&left[0])); + } + } + + #[test] + fn tab_goes_to_the_next_cell_and_shift_tab_to_the_one_before() { + let mut document = read(TABLE); + for (from, back, to) in [ + ([0, 0], false, [0, 1]), + ([0, 1], false, [1, 0]), + ([1, 1], true, [1, 0]), + ([1, 0], true, [0, 1]), + ([0, 0], true, [0, 0]), + ] { + let from = at(&[1, from[0], from[1]]); + assert_eq!(step(&mut document, &from, back), at(&[1, to[0], to[1]])); + } + assert_eq!(cells(&document).len(), 2); + } + + #[test] + fn tab_past_the_last_cell_adds_a_row() { + let mut document = read(TABLE); + + assert_eq!(step(&mut document, &at(&[1, 1, 1]), false), at(&[1, 2, 0])); + assert_eq!(cells(&document)[2], ["", ""]); + } + + #[test] + fn out_of_a_table_nothing_is_done() { + let tab: Edit = |document, selection| step(document, selection, false); + for edit in [add_row_after as Edit, add_column_after, delete_row, delete_column, delete, tab] { + let mut document = read(TABLE); + let outside = at(&[0]); + assert_eq!(edit(&mut document, &outside), outside); + assert_eq!(document, read(TABLE)); + } } } diff --git a/crates/richtext/src/tree.rs b/crates/richtext/src/tree.rs index e3399beab..a0eedc47f 100644 --- a/crates/richtext/src/tree.rs +++ b/crates/richtext/src/tree.rs @@ -36,9 +36,7 @@ pub fn leaf<'a>(document: &'a Document, path: &[usize]) -> Option> { fn leaf_in<'a>(blocks: &'a [Block], path: &[usize]) -> Option> { let (first, rest) = path.split_first()?; match (blocks.get(*first)?, rest) { - (Block::Paragraph(content) | Block::Heading { content, .. }, []) => { - Some(Leaf::Inlines(content)) - } + (Block::Paragraph(content) | Block::Heading { content, .. }, []) => Some(Leaf::Inlines(content)), (Block::CodeBlock { text, .. }, []) => Some(Leaf::Code(text)), (Block::List { items, .. }, [item, rest @ ..]) => leaf_in(&items.get(*item)?.blocks, rest), (Block::Quote(inner), rest) => leaf_in(inner, rest), @@ -54,17 +52,13 @@ pub fn leaf_mut<'a>(document: &'a mut Document, path: &[usize]) -> Option(blocks: &'a mut [Block], path: &[usize]) -> Option> { let (first, rest) = path.split_first()?; match (blocks.get_mut(*first)?, rest) { - (Block::Paragraph(content) | Block::Heading { content, .. }, []) => { - Some(LeafMut::Inlines(content)) - } + (Block::Paragraph(content) | Block::Heading { content, .. }, []) => Some(LeafMut::Inlines(content)), (Block::CodeBlock { text, .. }, []) => Some(LeafMut::Code(text)), (Block::List { items, .. }, [item, rest @ ..]) => { leaf_mut_in(&mut items.get_mut(*item)?.blocks, rest) } (Block::Quote(inner), rest) => leaf_mut_in(inner, rest), - (Block::Table(rows), [row, cell]) => { - Some(LeafMut::Inlines(rows.get_mut(*row)?.get_mut(*cell)?)) - } + (Block::Table(rows), [row, cell]) => Some(LeafMut::Inlines(rows.get_mut(*row)?.get_mut(*cell)?)), _ => None, } } @@ -106,10 +100,7 @@ fn collect(blocks: &[Block], prefix: &mut Vec, found: &mut Vec /// The list of blocks a path's block sits in, and its index there: the document's, a quote's /// or an item's. `None` for a table's cell. -pub fn siblings_mut<'a>( - document: &'a mut Document, - path: &[usize], -) -> Option<(&'a mut Vec, usize)> { +pub fn siblings_mut<'a>(document: &'a mut Document, path: &[usize]) -> Option<(&'a mut Vec, usize)> { let (last, parent) = path.split_last()?; let blocks = container_mut(&mut document.blocks, parent)?; (*last < blocks.len()).then_some((blocks, *last)) @@ -128,6 +119,11 @@ fn container_mut<'a>(blocks: &'a mut Vec, path: &[usize]) -> Option<&'a m } } +pub fn block_mut<'a>(document: &'a mut Document, path: &[usize]) -> Option<&'a mut Block> { + let (blocks, index) = siblings_mut(document, path)?; + blocks.get_mut(index) +} + pub fn block<'a>(document: &'a Document, path: &[usize]) -> Option<&'a Block> { let (last, parent) = path.split_last()?; container(&document.blocks, parent)?.get(*last) @@ -138,9 +134,7 @@ fn container<'a>(blocks: &'a [Block], path: &[usize]) -> Option<&'a [Block]> { return Some(blocks); }; match (blocks.get(*first)?, rest) { - (Block::List { items, .. }, [item, rest @ ..]) => { - container(&items.get(*item)?.blocks, rest) - } + (Block::List { items, .. }, [item, rest @ ..]) => container(&items.get(*item)?.blocks, rest), (Block::Quote(inner), rest) => container(inner, rest), _ => None, } @@ -148,10 +142,7 @@ fn container<'a>(blocks: &'a [Block], path: &[usize]) -> Option<&'a [Block]> { /// Where a leaf's path enters a list: the list's path, the item's index, and what follows in /// the item. `None` when the leaf is in no list. -pub fn innermost_item( - document: &Document, - path: &[usize], -) -> Option<(Vec, usize, Vec)> { +pub fn innermost_item(document: &Document, path: &[usize]) -> Option<(Vec, usize, Vec)> { let mut found = None; let mut blocks = document.blocks.as_slice(); let mut at = 0; @@ -177,20 +168,154 @@ pub fn innermost_item( /// next one in reading order, or the end of the last. pub fn clamp(document: &Document, position: &Position) -> Position { if let Some(found) = leaf(document, &position.path) { - return Position { - path: position.path.clone(), - offset: position.offset.min(found.len()), - }; + return Position { path: position.path.clone(), offset: position.offset.min(found.len()) }; } let all = leaves(document); if let Some(next) = all.iter().find(|path| **path >= position.path) { - return Position { - path: next.clone(), - offset: 0, - }; + return Position { path: next.clone(), offset: 0 }; } all.last().map_or_else(Position::default, |path| Position { path: path.clone(), offset: leaf(document, path).map_or(0, |found| found.len()), }) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::read; + + /// A paragraph, a list with a nested one, a quote, a table and code, an image and a rule among + /// them. + const NOTE: &str = "ab\n\n- c\n - d\n\n e\n\n---\n\n> f\n>\n> - g\n\n![h](i)\n\n| j | k |\n| --- | --- |\n| l | m |\n\n```\nnop\n```"; + + fn text(document: &Document, path: &[usize]) -> Option { + leaf(document, path).map(|found| match found { + Leaf::Inlines(content) => crate::inlines::plain(content), + Leaf::Code(text) => text.clone(), + }) + } + + #[test] + fn the_leaves_are_met_in_reading_order() { + let document = read(NOTE); + let met: Vec = leaves(&document).iter().map(|path| text(&document, path).unwrap()).collect(); + + assert_eq!(met, ["ab", "c", "d", "e", "f", "g", "j", "k", "l", "m", "nop"]); + } + + #[test] + fn a_path_that_ends_on_no_text_is_no_leaf() { + let mut document = read(NOTE); + for path in [ + &[][..], + &[9], + &[0, 0], + &[1], + &[1, 0], + &[1, 0, 9], + &[1, 9, 0], + &[2], + &[3], + &[3, 9], + &[4], + &[5], + &[5, 0], + &[5, 9, 0], + &[5, 0, 9], + &[5, 0, 0, 0], + &[6, 0], + ] { + assert!(leaf(&document, path).is_none(), "{path:?}"); + assert!(leaf_mut(&mut document, path).is_none(), "{path:?}"); + } + } + + #[test] + fn each_leaf_is_changed_by_its_path() { + let mut document = read(NOTE); + for path in leaves(&document) { + match leaf_mut(&mut document, &path) { + Some(LeafMut::Inlines(content)) => *content = vec![Inline::text("x")], + Some(LeafMut::Code(code)) => "x".clone_into(code), + None => panic!("{path:?}"), + } + assert_eq!(text(&document, &path).as_deref(), Some("x"), "{path:?}"); + } + } + + #[test] + fn a_leaf_s_length_counts_chars_and_breaks() { + let document = read("é \nb\n\n```\né\nb\n```"); + + assert_eq!([0, 1].map(|block| leaf(&document, &[block]).unwrap().len()), [3, 3]); + assert!(!leaf(&document, &[0]).unwrap().is_empty()); + assert!(leaf(&read("-"), &[0, 0, 0]).unwrap().is_empty()); + } + + #[test] + fn a_block_is_found_with_the_blocks_it_sits_among() { + let mut document = read(NOTE); + for (path, among) in + [(&[2][..], 7), (&[1, 0, 2], 3), (&[1, 0, 1, 0, 0], 1), (&[3, 1], 2), (&[3, 1, 0, 0], 1)] + { + let found = block(&document, path).cloned(); + let (blocks, index) = siblings_mut(&mut document, path).unwrap(); + assert_eq!(blocks.len(), among, "{path:?}"); + assert_eq!(blocks.get(index), found.as_ref(), "{path:?}"); + } + } + + #[test] + fn a_cell_and_what_is_past_the_end_are_no_block() { + let mut document = read(NOTE); + for path in [&[][..], &[7], &[0, 0], &[1, 0], &[1, 9, 0], &[1, 0, 3], &[3, 2], &[5, 0, 0], &[9, 0]] { + assert!(block(&document, path).is_none(), "{path:?}"); + assert!(siblings_mut(&mut document, path).is_none(), "{path:?}"); + } + } + + #[test] + fn a_leaf_s_item_is_that_of_the_innermost_list() { + let document = read(NOTE); + for (path, found) in [ + (&[1, 0, 0][..], Some((vec![1], 0, vec![0]))), + (&[1, 0, 2], Some((vec![1], 0, vec![2]))), + (&[1, 0, 1, 0, 0], Some((vec![1, 0, 1], 0, vec![0]))), + (&[3, 1, 0, 0], Some((vec![3, 1], 0, vec![0]))), + (&[3, 0], None), + (&[0], None), + (&[1], None), + (&[1, 9, 0], None), + (&[9], None), + (&[], None), + ] { + assert_eq!(innermost_item(&document, path), found, "{path:?}"); + } + } + + #[test] + fn a_position_is_brought_back_on_a_text() { + let document = read(NOTE); + let clamped = |path: &[usize], offset| { + let found = clamp(&document, &Position { path: path.to_vec(), offset }); + (found.path, found.offset) + }; + + assert_eq!(clamped(&[0], 1), (vec![0], 1)); + assert_eq!(clamped(&[0], 9), (vec![0], 2)); + assert_eq!(clamped(&[1], 9), (vec![1, 0, 0], 0)); + assert_eq!(clamped(&[2], 0), (vec![3, 0], 0)); + assert_eq!(clamped(&[3, 1, 0, 9], 0), (vec![5, 0, 0], 0)); + assert_eq!(clamped(&[], 4), (vec![0], 0)); + assert_eq!(clamped(&[9], 0), (vec![6], 3)); + } + + #[test] + fn a_document_without_text_holds_no_position() { + let alone = read("![a](b)"); + + assert!(leaves(&alone).is_empty()); + assert_eq!(clamp(&alone, &Position { path: vec![3], offset: 1 }), Position::default()); + } +} diff --git a/crates/richtext/src/write.rs b/crates/richtext/src/write.rs index fd72522c8..d9260ea71 100644 --- a/crates/richtext/src/write.rs +++ b/crates/richtext/src/write.rs @@ -2,16 +2,17 @@ //! line apart, tight lists, a table padded to its widest cell and set apart by one more blank //! line on each side, a hard break as two spaces, and typed text escaped by `escape`. +use std::cmp::Reverse; + use crate::escape::escape; -use crate::model::{Block, Cell, Document, Inline, Item, ListKind}; +use crate::inlines::{Mark, normalize, put, wears}; +use crate::model::{Block, Cell, Document, Inline, Item, ListKind, Marks}; /// The narrowest column a table writes, as its separator's `---`. const MIN_COLUMN: usize = 3; pub fn write(document: &Document) -> String { - blocks(&document.blocks, "\n\n") - .trim_matches('\n') - .to_owned() + blocks(&document.blocks, "\n\n").trim_matches('\n').to_owned() } fn blocks(blocks: &[Block], between: &str) -> String { @@ -22,27 +23,24 @@ fn block(block: &Block) -> String { match block { Block::Paragraph(content) => inlines(content), Block::Heading { level, content } => { - format!("{} {}", "#".repeat(usize::from(*level)), inlines(content)) + format!("{} {}", "#".repeat(usize::from(*level)), one_line(content)) } Block::List { kind, items } => list(*kind, items), Block::Quote(inner) => blocks(inner, "\n\n") .split('\n') - .map(|line| { - if line.is_empty() { - ">".to_owned() - } else { - format!("> {line}") - } - }) + .map(|line| if line.is_empty() { ">".to_owned() } else { format!("> {line}") }) .collect::>() .join("\n"), Block::CodeBlock { language, text } => { let newline = if text.is_empty() { "" } else { "\n" }; - format!("```{language}\n{text}{newline}```") + let fence = "`".repeat(longest_backticks(text).max(2) + 1); + format!("{fence}{language}\n{text}{newline}{fence}") } Block::Table(rows) => format!("\n{}\n", table(rows)), Block::Image { alt, src, width } => { - format!("![{alt}]({})", crate::picture::written(src, *width)) + let alt = escape(alt, false).replace(']', "\\]"); + let src = crate::picture::written(src, *width); + format!("![{alt}]({})", address(&src)) } Block::Rule => "---".to_owned(), } @@ -65,17 +63,11 @@ fn list(kind: ListKind, items: &[Item]) -> String { ListKind::Ordered { .. } => " ".repeat(marker.len()), ListKind::Bullet | ListKind::Task => " ".to_owned(), }; - let body = blocks(&item.blocks, "\n"); + let body = item_blocks(kind, &item.blocks); let mut lines = body.split('\n'); let first = lines.next().unwrap_or_default(); let rest: Vec = lines - .map(|line| { - if line.is_empty() { - String::new() - } else { - format!("{indent}{line}") - } - }) + .map(|line| if line.is_empty() { String::new() } else { format!("{indent}{line}") }) .collect(); std::iter::once(format!("{marker}{first}")) .chain(rest) @@ -86,10 +78,53 @@ fn list(kind: ListKind, items: &[Item]) -> String { .join("\n") } +/// An item's blocks a line apart, one more where the next would be read into the one before. +fn item_blocks(kind: ListKind, blocks: &[Block]) -> String { + let mut out = String::new(); + // A box is followed by text alone, and `- ---` is one rule. + let text = matches!(blocks.first(), Some(Block::Paragraph(_) | Block::Image { .. })); + if kind == ListKind::Task && !text || blocks.first() == Some(&Block::Rule) { + out.push('\n'); + } + for (at, each) in blocks.iter().enumerate() { + if at > 0 { + let between = if joins(&blocks[at - 1], each) { "\n\n" } else { "\n" }; + out.push_str(between); + } + out.push_str(&block(each)); + } + out +} + +fn joins(before: &Block, after: &Block) -> bool { + let paragraph = match before { + Block::Paragraph(content) => !content.is_empty(), + Block::Image { .. } => true, + _ => false, + }; + // Lists and quotes end on a paragraph, which the next line continues. + let continued = paragraph || matches!(before, Block::List { .. } | Block::Quote(_)); + match after { + Block::Paragraph(content) => continued && !content.is_empty(), + Block::Image { .. } => continued, + Block::Quote(_) => matches!(before, Block::Quote(_)), + Block::Rule => paragraph, + // Only a list starting at 1, on an item with something in it, interrupts a paragraph. + Block::List { kind, items } => { + let blank = items.first().is_some_and(|item| match item.blocks.first() { + Some(Block::Paragraph(content)) => content.is_empty(), + first => first == Some(&Block::Rule), + }); + paragraph && (blank || matches!(kind, ListKind::Ordered { start: 0 | 2.. })) + } + _ => false, + } +} + fn table(rows: &[Vec]) -> String { let written: Vec> = rows .iter() - .map(|row| row.iter().map(|cell| inlines(cell)).collect()) + .map(|row| row.iter().map(|content| cell(content)).collect()) .collect(); let columns = written.iter().map(Vec::len).max().unwrap_or(0); let widths: Vec = (0..columns) @@ -128,41 +163,172 @@ fn table(rows: &[Vec]) -> String { out.join("\n") } -/// Marked runs: each mark's delimiters around the run that wears it. +fn cell(content: &[Inline]) -> String { + one_line(content).replace('|', "\\|") +} + +/// What a cell and a heading hold: their breaks are `
`. +fn one_line(content: &[Inline]) -> String { + inlines(content).replace(" \n", "
").replace('\n', " ") +} + +/// Marked runs: a mark is opened before the first run that wears it and closed after the last. fn inlines(content: &[Inline]) -> String { + let runs = unmarked_edges(content); let mut out = String::new(); - for inline in content { - match inline { - Inline::HardBreak => out.push_str(" \n"), - Inline::Text { text, marks } => { - let starts_line = out.is_empty() || out.ends_with('\n'); - let mut run = if marks.code { - format!("`{text}`") - } else { - escape(text, starts_line) - }; - if marks.strike { - run = format!("~~{run}~~"); - } - if marks.italic { - run = format!("*{run}*"); - } - if marks.bold { - run = format!("**{run}**"); - } - if let Some(href) = &marks.link { - run = format!("[{run}]({href})"); - } - out.push_str(&run); - } + let mut open: Vec = Vec::new(); + for (at, inline) in runs.iter().enumerate() { + let Inline::Text { text, marks } = inline else { + close(&mut out, &mut open, 0); + out.push_str(" \n"); + continue; + }; + let still = open.iter().take_while(|mark| wears(marks, mark)).count(); + close(&mut out, &mut open, still); + let starts_line = out.is_empty() || out.ends_with('\n'); + let mut opening = worn(marks); + opening.retain(|mark| !open.contains(mark)); + opening.sort_by_key(|mark| Reverse(lasts(&runs[at..], mark))); + for mark in opening { + out.push_str(delimiter(&mark)); + open.push(mark); + } + if marks.code { + out.push_str(&code_span(text)); + continue; + } + let text = escape(text, starts_line); + if marks.link.is_some() { + out.push_str(&text.replace(']', "\\]")); + } else { + out.push_str(&text); } } + close(&mut out, &mut open, 0); out } +fn close(out: &mut String, open: &mut Vec, still: usize) { + for mark in open.drain(still..).rev() { + if let Mark::Link(Some(href)) = &mark { + out.push_str("]("); + out.push_str(&address(href)); + out.push(')'); + } else { + out.push_str(delimiter(&mark)); + } + } +} + +fn delimiter(mark: &Mark) -> &'static str { + match mark { + Mark::Link(_) => "[", + Mark::Bold => "**", + Mark::Italic => "*", + Mark::Strike => "~~", + Mark::Code => "`", + } +} + +/// The marks of a run but its code, the outermost first where all last as long. +fn worn(marks: &Marks) -> Vec { + let mut worn = Vec::new(); + if marks.link.is_some() { + worn.push(Mark::Link(marks.link.clone())); + } + for mark in [Mark::Bold, Mark::Italic, Mark::Strike] { + if wears(marks, &mark) { + worn.push(mark); + } + } + worn +} + +/// How many runs wear the mark, from the first on. +fn lasts(runs: &[Inline], mark: &Mark) -> usize { + runs.iter() + .take_while(|run| matches!(run, Inline::Text { marks, .. } if wears(marks, mark))) + .count() +} + +/// Emphasis is read as such only against a word: the spaces at its ends go outside it. +fn unmarked_edges(content: &[Inline]) -> Vec { + let mut pieces: Vec = content.iter().flat_map(around_spaces).collect(); + for mark in [Mark::Bold, Mark::Italic, Mark::Strike] { + unmark_spaces(pieces.iter_mut(), &mark); + unmark_spaces(pieces.iter_mut().rev(), &mark); + } + normalize(&mut pieces); + pieces +} + +/// The spaces a run starts with, what is between, and those it ends with. +fn around_spaces(inline: &Inline) -> Vec { + let Inline::Text { text, marks } = inline else { + return vec![inline.clone()]; + }; + if marks.code { + return vec![inline.clone()]; + } + let ended = text.trim_end(); + let word = ended.trim_start(); + [&ended[..ended.len() - word.len()], word, &text[ended.len()..]] + .into_iter() + .map(|text| Inline::Text { text: text.to_owned(), marks: marks.clone() }) + .collect() +} + +/// The spaces met before the first word of each run wearing `mark`. +fn unmark_spaces<'a>(pieces: impl Iterator, mark: &Mark) { + let mut inside = false; + for piece in pieces { + let Inline::Text { text, marks } = piece else { + inside = false; + continue; + }; + if !inside && !marks.code && text.trim().is_empty() { + put(marks, mark, false); + } else { + inside = wears(marks, mark); + } + } +} + +/// Fenced by one backtick more than it holds, set off by a space its own edge would lose. +fn code_span(text: &str) -> String { + let fence = "`".repeat(longest_backticks(text) + 1); + let spaced = text.starts_with(' ') && text.ends_with(' ') && !text.trim().is_empty(); + let set_off = spaced || text.starts_with('`') || text.ends_with('`'); + let pad = if set_off { " " } else { "" }; + format!("{fence}{pad}{text}{pad}{fence}") +} + +fn longest_backticks(text: &str) -> usize { + text.split(|glyph| glyph != '`').map(str::len).max().unwrap_or(0) +} + +/// Between angle brackets where a space or a lone parenthesis would end it. +fn address(href: &str) -> String { + let mut depth = 0; + let mut balanced = true; + for glyph in href.chars() { + match glyph { + '(' => depth += 1, + ')' => depth -= 1, + _ => {} + } + balanced &= depth >= 0; + } + if balanced && depth == 0 && !href.starts_with('<') && !href.contains(char::is_whitespace) { + return href.to_owned(); + } + format!("<{}>", href.replace('<', "\\<").replace('>', "\\>")) +} + #[cfg(test)] mod tests { - use crate::{read, write}; + use super::*; + use crate::read; fn round(markdown: &str) -> String { write(&read(markdown)) @@ -170,27 +336,234 @@ mod tests { #[test] fn nested_numbered_lists_indent_under_their_marker() { - assert_eq!( - round("1. un\n 1. un bis\n2. deux"), - "1. un\n 1. un bis\n2. deux" - ); + assert_eq!(round("1. un\n 1. un bis\n2. deux"), "1. un\n 1. un bis\n2. deux"); } #[test] fn an_image_in_a_paragraph_stands_on_its_own() { let written = round("avant ![x](devnotes:drawing/1)"); - assert!( - written.ends_with("\n\n![x](devnotes:drawing/1)"), - "{written}" - ); + assert!(written.ends_with("\n\n![x](devnotes:drawing/1)"), "{written}"); } #[test] fn a_code_block_keeps_its_text_and_a_bold_link_its_marks() { assert_eq!(round("```\na * b\n```"), "```\na * b\n```"); - assert_eq!( - round("**[gras](https://a.fr)**"), - "[**gras**](https://a.fr)" - ); + assert_eq!(round("**[gras](https://a.fr)**"), "[**gras**](https://a.fr)"); + } + + /// A run wearing the marks named by `worn`: `b`, `i`, `s`, `c`, and `l` a link. + fn run(worn: &str, text: &str) -> Inline { + let link = worn.contains('l').then(|| "https://a.fr".to_owned()); + Inline::Text { + text: text.to_owned(), + marks: Marks { + bold: worn.contains('b'), + italic: worn.contains('i'), + strike: worn.contains('s'), + code: worn.contains('c'), + link, + }, + } + } + + fn paragraph(content: Vec) -> Document { + Document { blocks: vec![Block::Paragraph(content)] } + } + + #[track_caller] + fn written(document: &Document, expected: &str) { + let markdown = write(document); + assert_eq!(markdown, expected); + assert_eq!(read(&markdown), *document, "read back"); + } + + #[test] + fn a_mark_is_written_once_around_the_runs_that_wear_it() { + for (content, expected) in [ + (vec![run("b", "a "), run("bi", "b")], "**a *b***"), + (vec![run("bi", "a"), run("b", " b")], "***a* b**"), + (vec![run("bi", "a"), run("i", " b")], "***a** b*"), + (vec![run("i", "a "), run("bi", "b"), run("i", " c")], "*a **b** c*"), + (vec![run("b", "a"), run("i", "b")], "**a***b*"), + (vec![run("b", "x "), run("bl", "a"), run("b", " y")], "**x [a](https://a.fr) y**"), + (vec![run("l", "a"), run("lb", "b")], "[a**b**](https://a.fr)"), + (vec![run("bisl", "a")], "[***~~a~~***](https://a.fr)"), + (vec![run("bc", "a"), run("b", "b")], "**`a`b**"), + ] { + written(¶graph(content), expected); + } + } + + #[test] + fn a_mark_is_closed_before_a_break_and_opened_after_it() { + written(¶graph(vec![run("b", "a"), Inline::HardBreak, run("b", "b")]), "**a** \n**b**"); + let spaced = paragraph(vec![run("b", "a"), Inline::HardBreak, run("b", " b")]); + assert_eq!(write(&spaced), "**a** \n **b**"); + let tabbed = paragraph(vec![run("", "a"), Inline::HardBreak, run("", "\tb")]); + assert_eq!(write(&tabbed), "a \n b"); + written(¶graph(vec![run("bc", " "), run("b", "a")]), "**` `a**"); + } + + /// `**a **b` is stars and letters, for Markdown. + #[test] + fn the_spaces_at_the_ends_of_a_mark_are_written_outside_it() { + for (content, expected) in [ + (vec![run("b", "a "), run("", "b")], "**a** b"), + (vec![run("", "a"), run("i", " b")], "a *b*"), + (vec![run("s", " \u{a0}a "), run("", "b")], " \u{a0}~~a~~ b"), + (vec![run("b", "a "), run("bi", " "), run("", "b")], "**a** b"), + (vec![run("", "a"), run("b", " "), run("", "b")], "a b"), + ] { + assert_eq!(write(¶graph(content)), expected); + } + } + + #[test] + fn a_code_span_is_fenced_by_more_backticks_than_it_holds() { + for (text, expected) in [ + ("a`b", "``a`b``"), + ("`a", "`` `a ``"), + ("a``", "``` a`` ```"), + (" a ", "` a `"), + (" a", "` a`"), + (" ", "` `"), + ] { + written(¶graph(vec![run("c", text)]), expected); + } + } + + #[test] + fn a_code_block_is_fenced_by_more_backticks_than_it_holds() { + for (text, fence) in [("a ` b", "```"), ("```\na\n```", "````"), ("`````", "``````")] { + let block = Block::CodeBlock { language: "md".to_owned(), text: text.to_owned() }; + written(&Document { blocks: vec![block] }, &format!("{fence}md\n{text}\n{fence}")); + } + } + + #[test] + fn a_cell_holds_one_line_and_its_bars() { + for (content, expected) in [ + (vec![run("", "a"), Inline::HardBreak, run("", "b")], "a
b"), + (vec![run("", "a|b")], r"a\|b"), + (vec![run("", r"a\|b")], r"a\\\|b"), + (vec![run("c", "a|b")], r"`a\|b`"), + ] { + let table = Block::Table(vec![vec![content, vec![run("", "c")]]]); + let dashes = "-".repeat(expected.len()); + written(&Document { blocks: vec![table] }, &format!("| {expected} | c |\n| {dashes} | --- |")); + } + } + + #[test] + fn a_heading_holds_one_line() { + let heading = |content| Document { blocks: vec![Block::Heading { level: 2, content }] }; + written(&heading(vec![run("", "a"), Inline::HardBreak, run("b", "b")]), "## a
**b**"); + assert_eq!(write(&heading(vec![run("", "a\nb")])), "## a b"); + } + + #[test] + fn a_bracket_stays_in_its_link_or_in_its_image() { + for (text, expected) in [("a]b", r"[a\]b](https://a.fr)"), ("[a]", r"[\[a\]](https://a.fr)")] { + written(¶graph(vec![run("l", text)]), expected); + } + let image = Block::Image { alt: "a]b*c*".to_owned(), src: "x.png".to_owned(), width: None }; + written(&Document { blocks: vec![image] }, r"![a\]b\*c\*](x.png)"); + } + + #[test] + fn an_address_ends_where_it_ended() { + for (href, expected) in [ + ("https://a.fr/b_(c)", "https://a.fr/b_(c)"), + ("", ""), + ("a b", ""), + ("a)", ""), + ("(a", "<(a>"), + (")a(", "<)a(>"), + ("", r"<\>"), + ] { + let mut link = run("", "x"); + if let Inline::Text { marks, .. } = &mut link { + marks.link = Some(href.to_owned()); + } + written(¶graph(vec![link]), &format!("[x]({expected})")); + } + } + + /// Tight, as an item is, where what follows would not be read into it. + #[test] + fn an_item_s_blocks_are_parted_where_the_next_would_continue_the_one_before() { + for (markdown, tight) in [ + ("- a\n\n b", false), + ("- a\n\n ---", false), + ("- a\n\n 3. b", false), + ("- a\n\n 0. b", false), + ("- a\n\n 1. ", false), + ("- a\n\n - ", false), + ("- a\n\n - \n ---", false), + ("- \n ---\n - b", true), + ("- > a\n\n b", false), + ("- > a\n\n > b", false), + ("- - a\n\n b", false), + ("- a\n\n ![b](c)", false), + ("- a\n 1. b", true), + ("- a\n - b", true), + ("- a\n > b", true), + ("- a\n # b", true), + ("- # a\n b", true), + ("- ```\n a\n ```\n b", true), + ] { + let document = read(markdown); + assert_eq!(write(&document), markdown); + assert_eq!(document.blocks.len(), 1, "{markdown}"); + assert_eq!(!markdown.contains("\n\n"), tight); + } + } + + #[test] + fn what_starts_an_item_is_read_in_it() { + for markdown in [ + "- \n ---", + "1. \n ---\n a", + "- [ ] \n # a", + "- [x] \n ```\n a\n ```", + "- [ ] \n > a", + "- [ ] \n - a", + "- [ ] ![a](b)", + "- # a", + "- > a", + ] { + let document = read(markdown); + assert_eq!(write(&document), markdown); + assert_eq!(document.blocks.len(), 1, "{markdown}"); + } + let rule = Block::List { + kind: ListKind::Task, + items: vec![Item { + checked: true, + blocks: vec![Block::Rule, Block::Paragraph(vec![run("", "a")])], + }], + }; + let document = Document { blocks: vec![rule] }; + assert_eq!(read(&write(&document)), document); + } + + #[test] + fn a_star_against_a_field_is_a_star() { + for (text, expected) in + [("*{{a}}*", r"\*{{a}}\*"), ("{{a}}_{{b}}", "{{a}}\\_{{b}}"), ("{{a}} * {{b}}", "{{a}} * {{b}}")] + { + written(¶graph(vec![run("", text)]), expected); + } + } + + #[test] + fn four_spaces_that_start_a_paragraph_are_no_code() { + for (text, expected) in + [(" a", " a"), (" a", " a"), ("\ta", " a"), (" \ta", " a")] + { + let markdown = write(¶graph(vec![run("", text)])); + assert_eq!(markdown, expected); + assert!(matches!(read(&markdown).blocks[0], Block::Paragraph(_))); + } } } diff --git a/crates/richtext/tests/golden.rs b/crates/richtext/tests/golden.rs index 31beda54f..b726b77dc 100644 --- a/crates/richtext/tests/golden.rs +++ b/crates/richtext/tests/golden.rs @@ -15,8 +15,7 @@ fn markdown_is_read_and_written_back_as_stored() { let input = case["input"].as_str().unwrap(); let written = richtext::write(&richtext::read(input)); let expected = case["output"].as_str().unwrap(); - (written != expected) - .then(|| format!("{input:?}\n gave {written:?}\n want {expected:?}")) + (written != expected).then(|| format!("{input:?}\n gave {written:?}\n want {expected:?}")) }) .collect(); assert!(differing.is_empty(), "{}", differing.join("\n")); diff --git a/crates/richtext/tests/past_the_end.rs b/crates/richtext/tests/past_the_end.rs index fea6e5ac1..560627865 100644 --- a/crates/richtext/tests/past_the_end.rs +++ b/crates/richtext/tests/past_the_end.rs @@ -4,17 +4,13 @@ use richtext::{Document, ListKind, Position, Selection, edit, read, table}; fn beyond() -> Selection { - Selection::caret(Position { - path: vec![5, 3], - offset: 40, - }) + Selection::caret(Position { path: vec![5, 3], offset: 40 }) } #[test] fn every_command_answers_a_selection_past_the_end() { - let commands: [fn(&mut Document, &Selection); 12] = [ + let commands: [fn(&mut Document, &Selection); 11] = [ |d, s| drop(edit::toggle_quote(d, s)), - |d, s| drop(edit::insert_rule(d, s)), |d, s| drop(edit::replace_with_rule(d, s)), |d, s| drop(edit::toggle_list(d, s, ListKind::Bullet)), |d, s| drop(edit::toggle_code_block(d, s)), diff --git a/crates/text/src/buffer.rs b/crates/text/src/buffer.rs index 9a890341a..3f5a5159e 100644 --- a/crates/text/src/buffer.rs +++ b/crates/text/src/buffer.rs @@ -20,10 +20,7 @@ pub struct Selection { impl Selection { pub fn caret(at: usize) -> Self { - Self { - anchor: at, - head: at, - } + Self { anchor: at, head: at } } pub fn range(self) -> Range { @@ -64,11 +61,7 @@ pub struct Buffer { impl Buffer { pub fn new(text: &str) -> Self { - Self { - rope: Rope::from_str(text), - selection: Selection::default(), - history: History::default(), - } + Self { rope: Rope::from_str(text), selection: Selection::default(), history: History::default() } } pub fn text(&self) -> String { @@ -122,18 +115,12 @@ impl Buffer { /// The caret moved by itself: typing after this is a step of its own. pub fn select(&mut self, selection: Selection) { let len = self.len(); - self.selection = Selection { - anchor: selection.anchor.min(len), - head: selection.head.min(len), - }; + self.selection = Selection { anchor: selection.anchor.min(len), head: selection.head.min(len) }; self.history.break_group(); } pub fn select_all(&mut self) { - self.select(Selection { - anchor: 0, - head: self.len(), - }); + self.select(Selection { anchor: 0, head: self.len() }); } /// The caret to `at`, the anchor kept when `extend`. @@ -174,10 +161,7 @@ impl Buffer { /// One replacement as one step of undo, the selection where the edit puts it. pub fn apply(&mut self, edit: &TextEdit) -> Edited { - let selection = Selection { - anchor: edit.selection_start, - head: edit.selection_end, - }; + let selection = Selection { anchor: edit.selection_start, head: edit.selection_end }; self.replace(edit.from..edit.to, &edit.insert, selection, Kind::Other) } @@ -195,7 +179,8 @@ impl Buffer { Some(self.apply(&edit)) } - /// Alt+↑ / Alt+↓: the selected lines swap with the one above or below. + /// Alt+↑ / Alt+↓: the selected lines swap with the one above or below. The line ending + /// between them stays between them, whichever it is. pub fn move_lines(&mut self, direction: Direction) -> Option { let range = self.selection.range(); let first = self.line_of(range.start); @@ -203,44 +188,22 @@ impl Buffer { if range.end > range.start && range.end == self.line_start(last) && last > first { last -= 1; } - let lines: Vec = (first..=last).map(|line| self.line(line)).collect(); - let block = lines.join("\n"); - let shift = |at: usize, by: isize| at.saturating_add_signed(by); - match direction { - Direction::Backward if first > 0 => { - let above = self.line(first - 1); - let from = self.line_start(first - 1); - let to = self.line_end(last); - let moved = isize::try_from(above.chars().count() + 1).unwrap_or(0); - let selection = Selection { - anchor: shift(self.selection.anchor, -moved), - head: shift(self.selection.head, -moved), - }; - Some(self.replace( - from..to, - &format!("{block}\n{above}"), - selection, - Kind::Other, - )) - } - Direction::Forward if last + 1 < self.line_count() => { - let below = self.line(last + 1); - let from = self.line_start(first); - let to = self.line_end(last + 1); - let moved = isize::try_from(below.chars().count() + 1).unwrap_or(0); - let selection = Selection { - anchor: shift(self.selection.anchor, moved), - head: shift(self.selection.head, moved), - }; - Some(self.replace( - from..to, - &format!("{below}\n{block}"), - selection, - Kind::Other, - )) - } - _ => None, - } + let (upper, lower) = match direction { + Direction::Backward if first > 0 => ((first - 1, first - 1), (first, last)), + Direction::Forward if last + 1 < self.line_count() => ((first, last), (last + 1, last + 1)), + _ => return None, + }; + let (from, upper_end) = (self.line_start(upper.0), self.line_end(upper.1)); + let (lower_start, to) = (self.line_start(lower.0), self.line_end(lower.1)); + let part = |range: Range| self.rope.slice(range).to_string(); + let swapped = [part(lower_start..to), part(upper_end..lower_start), part(from..upper_end)].concat(); + let shifted = |at: usize| match direction { + Direction::Backward => at.saturating_sub(lower_start - from), + Direction::Forward => at + (to - upper_end), + }; + let selection = + Selection { anchor: shifted(self.selection.anchor), head: shifted(self.selection.head) }; + Some(self.replace(from..to, &swapped, selection, Kind::Other)) } /// Ctrl+/: `token ` before every line of the selection, or off them all when each has it. @@ -265,10 +228,8 @@ impl Buffer { let indent = line.len() - line.trim_start().len(); let (head, rest) = line.split_at(indent); if commented { - let uncommented = rest - .strip_prefix(&marked) - .or_else(|| rest.strip_prefix(token)) - .unwrap_or(rest); + let uncommented = + rest.strip_prefix(&marked).or_else(|| rest.strip_prefix(token)).unwrap_or(rest); format!("{head}{uncommented}") } else { format!("{head}{marked}{rest}") @@ -283,13 +244,9 @@ impl Buffer { let end = span.start + grown - usize::from(body.len() < text.len()); let selection = if range.is_empty() { let column = self.selection.head - self.line_start(first); - let line_now = changed.first().map_or(0, |line| line.chars().count()); - Selection::caret(span.start + column.min(line_now)) + Selection::caret(span.start + followed(column, lines[0], &changed[0])) } else { - Selection { - anchor: span.start, - head: end, - } + Selection { anchor: span.start, head: end } }; self.replace(span, &insert, selection, Kind::Other) } @@ -340,10 +297,7 @@ impl Buffer { let selected = self.selection.range(); Count { total: found.len(), - current: found - .iter() - .position(|hit| *hit == selected) - .map(|at| at + 1), + current: found.iter().position(|hit| *hit == selected).map(|at| at + 1), capped: found.len() >= search::COUNT_CAP, } } @@ -352,23 +306,13 @@ impl Buffer { pub fn seek(&mut self, query: &Query, from: usize, direction: Direction) -> bool { let found = self.find(query, usize::MAX); let hit = match direction { - Direction::Forward => found - .iter() - .find(|hit| hit.start >= from) - .or_else(|| found.first()), - Direction::Backward => found - .iter() - .rev() - .find(|hit| hit.end <= from) - .or_else(|| found.last()), + Direction::Forward => found.iter().find(|hit| hit.start >= from).or_else(|| found.first()), + Direction::Backward => found.iter().rev().find(|hit| hit.end <= from).or_else(|| found.last()), }; let Some(hit) = hit.cloned() else { return false; }; - self.select(Selection { - anchor: hit.start, - head: hit.end, - }); + self.select(Selection { anchor: hit.start, head: hit.end }); true } @@ -383,12 +327,7 @@ impl Buffer { } let replacement = query.replacement(&self.selected_text()); let end = selected.start + replacement.chars().count(); - let edited = self.replace( - selected.clone(), - &replacement, - Selection::caret(end), - Kind::Other, - ); + let edited = self.replace(selected.clone(), &replacement, Selection::caret(end), Kind::Other); self.seek(query, end, Direction::Forward); Some(edited) } @@ -409,11 +348,7 @@ impl Buffer { let at = hit.start.saturating_add_signed(shift); shift += isize::try_from(inserted.chars().count()).unwrap_or(0) - isize::try_from(removed.chars().count()).unwrap_or(0); - changes.push(Change { - at, - removed, - inserted, - }); + changes.push(Change { at, removed, inserted }); } for change in &changes { let end = change.at + change.removed.chars().count(); @@ -421,12 +356,7 @@ impl Buffer { } let caret = Selection::caret(before.head.min(self.len())); self.selection = caret; - self.history.record(Step { - changes, - before, - after: caret, - kind: Kind::Other, - }); + self.history.record(Step { changes, before, after: caret, kind: Kind::Other }); (found.len(), Some(Edited { first_line })) } @@ -437,11 +367,7 @@ impl Buffer { let first_line = self.splice(range.clone(), text); self.selection = after; self.history.record(Step { - changes: vec![Change { - at: range.start, - removed, - inserted: text.to_owned(), - }], + changes: vec![Change { at: range.start, removed, inserted: text.to_owned() }], before, after, kind, @@ -464,11 +390,7 @@ impl Buffer { if range.end > range.start && range.end == self.line_start(last) && last > first { last -= 1; } - let end = if last + 1 < self.line_count() { - self.line_start(last + 1) - } else { - self.len() - }; + let end = if last + 1 < self.line_count() { self.line_start(last + 1) } else { self.len() }; self.line_start(first)..end } @@ -483,10 +405,9 @@ impl Buffer { .chain(std::iter::once(text.chars().count())) .collect(); match direction { - Direction::Forward => bounds - .iter() - .find(|bound| **bound > offset) - .map_or(at, |bound| start + bound), + Direction::Forward => { + bounds.iter().find(|bound| **bound > offset).map_or(at, |bound| start + bound) + } Direction::Backward if offset == 0 => { if line == 0 { return 0; @@ -510,18 +431,20 @@ impl Buffer { let class = crate::words::class; let char_at = |i: usize| self.rope.char(i); let len = self.len(); + let ends_line = + |i: usize| char_at(i) == '\n' || (char_at(i) == '\r' && i + 1 < len && char_at(i + 1) == '\n'); let mut i = at; match direction { Direction::Forward => { - if i < len && char_at(i) == '\n' { - return i + 1; + if i < len && ends_line(i) { + return self.grapheme(i, Direction::Forward); } - while i < len && char_at(i) != '\n' && class(char_at(i)) == 0 { + while i < len && !ends_line(i) && class(char_at(i)) == 0 { i += 1; } - if i < len && char_at(i) != '\n' { + if i < len && !ends_line(i) { let run = class(char_at(i)); - while i < len && char_at(i) != '\n' && class(char_at(i)) == run { + while i < len && !ends_line(i) && class(char_at(i)) == run { i += 1; } } @@ -546,5 +469,16 @@ impl Buffer { } } +/// Where `column` of `before` is in `after`, the same line with its indentation followed by +/// more or by less. +fn followed(column: usize, before: &str, after: &str) -> usize { + let indent = before.chars().take_while(|c| c.is_whitespace()).count(); + if column <= indent { + return column; + } + let (was, now) = (before.chars().count(), after.chars().count()); + (column + now).saturating_sub(was).max(indent) +} + #[cfg(test)] mod tests; diff --git a/crates/text/src/buffer/tests.rs b/crates/text/src/buffer/tests.rs index 3667971b3..0b3f639fc 100644 --- a/crates/text/src/buffer/tests.rs +++ b/crates/text/src/buffer/tests.rs @@ -12,6 +12,22 @@ fn at(text: &str, caret: usize) -> Buffer { buffer } +fn over(text: &str, anchor: usize, head: usize) -> Buffer { + let mut buffer = Buffer::new(text); + buffer.select(Selection { anchor, head }); + buffer +} + +fn query(search: &str, replace: &str) -> Query { + Query { search: search.into(), replace: replace.into(), ..Query::default() } +} + +fn selected(buffer: &Buffer) -> (usize, usize) { + (buffer.selection().anchor, buffer.selection().head) +} + +// ── Undo ── + #[test] fn a_word_typed_is_undone_in_one_step_and_the_next_word_in_another() { let mut buffer = Buffer::new(""); @@ -21,158 +37,550 @@ fn a_word_typed_is_undone_in_one_step_and_the_next_word_in_another() { assert_eq!(buffer.text(), "SELECT"); buffer.undo(); assert_eq!(buffer.text(), ""); +} + +#[test] +fn what_was_undone_is_redone_with_its_selection() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "SELECT 1"); + buffer.undo(); + buffer.undo(); + buffer.redo(); - assert_eq!(buffer.text(), "SELECT"); - assert_eq!(buffer.selection(), Selection::caret(6)); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("SELECT", (6, 6))); + buffer.redo(); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("SELECT 1", (8, 8))); + assert!(buffer.redo().is_none()); +} + +#[test] +fn spaces_typed_in_a_row_are_one_step_with_the_word_they_start() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a b"); + + buffer.undo(); + + assert_eq!(buffer.text(), "a"); +} + +#[test] +fn a_line_typed_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "ab\ncd"); + + buffer.undo(); + + assert_eq!(buffer.text(), "ab"); } #[test] fn typing_after_the_caret_moved_starts_a_step_of_its_own() { let mut buffer = Buffer::new(""); typed(&mut buffer, "ab"); - buffer.move_to(0, false); + buffer.move_to(2, false); typed(&mut buffer, "x"); buffer.undo(); assert_eq!(buffer.text(), "ab"); } +#[test] +fn typing_after_an_undo_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a b"); + buffer.undo(); + typed(&mut buffer, "c"); + + buffer.undo(); + assert_eq!(buffer.text(), "a"); +} + #[test] fn a_new_edit_drops_what_could_be_redone() { let mut buffer = Buffer::new(""); typed(&mut buffer, "a"); buffer.undo(); typed(&mut buffer, "b"); + assert!(buffer.redo().is_none()); assert_eq!(buffer.text(), "b"); } #[test] -fn backspace_takes_a_whole_grapheme_and_a_crlf_at_once() { - let mut buffer = at("cafe\u{301}", 5); - buffer.delete(Direction::Backward, Unit::Grapheme); - assert_eq!(buffer.text(), "caf"); +fn letters_erased_one_after_the_other_are_one_step_either_way() { + for (caret, direction) in [(5, Direction::Backward), (0, Direction::Forward)] { + let mut buffer = at("hello", caret); + for _ in 0..3 { + buffer.delete(direction, Unit::Grapheme); + } + assert_eq!(buffer.len(), 2); - let mut buffer = at("a\r\nb", 3); + buffer.undo(); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("hello", (caret, caret))); + } +} + +#[test] +fn letters_typed_then_erased_are_two_steps() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "ab"); buffer.delete(Direction::Backward, Unit::Grapheme); + + buffer.undo(); assert_eq!(buffer.text(), "ab"); } #[test] -fn erasing_letter_by_letter_is_undone_in_one_step() { - let mut buffer = at("hello", 5); - for _ in 0..3 { - buffer.delete(Direction::Backward, Unit::Grapheme); +fn a_paste_is_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a"); + buffer.insert("pasted"); + typed(&mut buffer, "b"); + + buffer.undo(); + assert_eq!(buffer.text(), "apasted"); + buffer.undo(); + assert_eq!(buffer.text(), "a"); +} + +#[test] +fn only_so_many_steps_are_kept_the_oldest_going_first() { + let mut buffer = Buffer::new(""); + for _ in 0..502 { + buffer.insert("ab"); } - assert_eq!(buffer.text(), "he"); + + let undone = std::iter::from_fn(|| buffer.undo()).count(); + + assert_eq!((undone, buffer.text().as_str()), (500, "abab")); +} + +#[test] +fn nothing_to_undo_is_no_edit() { + assert!(Buffer::new("a").undo().is_none()); +} + +// ── The selection ── + +#[test] +fn a_selection_stays_within_the_text() { + assert_eq!(selected(&over("abc", 9, 1)), (3, 1)); + assert_eq!(over("abc", 9, 1).selected_text(), "bc"); +} + +#[test] +fn the_caret_moved_keeps_its_anchor_only_when_it_extends() { + let mut buffer = over("abcdef", 1, 2); + + buffer.move_to(4, true); + assert_eq!(selected(&buffer), (1, 4)); + buffer.move_to(5, false); + assert_eq!(selected(&buffer), (5, 5)); + buffer.select_all(); + assert_eq!(selected(&buffer), (0, 6)); +} + +#[test] +fn what_is_typed_takes_the_place_of_the_selection() { + let mut buffer = over("abcd", 3, 1); + + buffer.insert("é!"); + + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("aé!d", (3, 3))); buffer.undo(); - assert_eq!(buffer.text(), "hello"); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("abcd", (3, 1))); } +// ── Lines ── + #[test] -fn a_word_goes_with_the_spaces_before_it() { - let mut buffer = at("let user_id = 1", 11); - buffer.delete(Direction::Backward, Unit::Word); - assert_eq!(buffer.text(), "let = 1"); +fn lines_are_counted_as_an_editor_does() { + let buffer = Buffer::new("a\r\nbé\n"); - let mut buffer = at("a.b(c)", 0); - assert_eq!(buffer.step(0, Direction::Forward, Unit::Word), 1); - assert_eq!(buffer.step(1, Direction::Forward, Unit::Word), 2); - buffer.move_to(6, false); - assert_eq!(buffer.step(6, Direction::Backward, Unit::Word), 5); + assert_eq!(buffer.line_count(), 3); + assert_eq!([buffer.line(0), buffer.line(1), buffer.line(2)], ["a", "bé", ""]); + assert_eq!([0, 1, 2].map(|line| buffer.line_start(line)), [0, 3, 6]); + assert_eq!([0, 1, 2].map(|line| buffer.line_end(line)), [1, 5, 6]); + assert_eq!([0, 3, 5, 6, 99].map(|at| buffer.line_of(at)), [0, 1, 1, 2, 2]); + assert!(Buffer::new("").is_empty() && !buffer.is_empty()); } #[test] -fn a_line_deleted_takes_its_line_ending() { - let mut buffer = at("a\nb\nc", 2); - buffer.delete(Direction::Forward, Unit::Line); - assert_eq!(buffer.text(), "a\nc"); +fn an_edit_its_undo_and_its_redo_say_the_first_line_they_touched() { + let mut buffer = at("a\nb\nc", 4); + + assert_eq!(buffer.insert("!").first_line, 2); + assert_eq!(buffer.undo().unwrap().first_line, 2); + assert_eq!(buffer.redo().unwrap().first_line, 2); + assert_eq!(buffer.replace_all(&query("b", "x")).1.unwrap().first_line, 1); + assert_eq!(buffer.undo().unwrap().first_line, 1); +} + +// ── Moving by a unit ── + +/// `é` as `e` and a combining accent, a family of joined emoji, `\r\n`: one each. +#[test] +fn a_step_by_grapheme_never_stops_inside_one() { + for (text, bounds) in [ + ("ab", vec![0, 1, 2]), + ("e\u{301}x", vec![0, 2, 3]), + ("👩‍👩‍👧!", vec![0, 5, 6]), + ("a\r\nb", vec![0, 1, 3, 4]), + ("\n\n", vec![0, 1, 2]), + ] { + let buffer = Buffer::new(text); + for pair in bounds.windows(2) { + assert_eq!(buffer.step(pair[0], Direction::Forward, Unit::Grapheme), pair[1], "{text:?}"); + assert_eq!(buffer.step(pair[1], Direction::Backward, Unit::Grapheme), pair[0], "{text:?}"); + } + let end = *bounds.last().unwrap(); + assert_eq!(buffer.step(end, Direction::Forward, Unit::Grapheme), end); + assert_eq!(buffer.step(0, Direction::Backward, Unit::Grapheme), 0); + } +} + +/// Over the spaces, then over one run of word characters or of punctuation. +#[test] +fn a_step_by_word_goes_over_one_run() { + let text = "let user_id=(1)"; + let forward = [(0, 3), (3, 12), (12, 14), (14, 15), (15, 16), (16, 16)]; + let backward = [(16, 15), (15, 14), (14, 12), (12, 5), (5, 0), (0, 0)]; + let buffer = Buffer::new(text); + + for (from, to) in forward { + assert_eq!(buffer.step(from, Direction::Forward, Unit::Word), to, "from {from}"); + } + for (from, to) in backward { + assert_eq!(buffer.step(from, Direction::Backward, Unit::Word), to, "from {from}"); + } +} + +#[test] +fn a_step_by_word_goes_past_a_line_ending_whole() { + for ending in ["\n", "\r\n"] { + let text = format!("ab {ending} cd"); + let buffer = Buffer::new(&text); + let after = 4 + ending.len(); + + assert_eq!(buffer.step(2, Direction::Forward, Unit::Word), 4); + assert_eq!(buffer.step(4, Direction::Forward, Unit::Word), after); + assert_eq!(buffer.step(after + 2, Direction::Backward, Unit::Word), after); + assert_eq!(buffer.step(after, Direction::Backward, Unit::Word), 4); + } +} + +#[test] +fn a_step_by_line_goes_to_its_ends() { + let buffer = Buffer::new("a\nbcd\r\ne"); + + assert_eq!(buffer.step(3, Direction::Backward, Unit::Line), 2); + assert_eq!(buffer.step(3, Direction::Forward, Unit::Line), 5); +} + +// ── Deleting ── + +#[test] +fn a_deletion_takes_a_grapheme_a_word_or_a_line() { + for (text, caret, direction, unit, left) in [ + ("cafe\u{301}", 5, Direction::Backward, Unit::Grapheme, "caf"), + ("a\r\nb", 3, Direction::Backward, Unit::Grapheme, "ab"), + ("a\r\nb", 1, Direction::Forward, Unit::Grapheme, "ab"), + ("let user_id = 1", 11, Direction::Backward, Unit::Word, "let = 1"), + ("let x", 3, Direction::Forward, Unit::Word, "let"), + ("a\nb\nc", 2, Direction::Forward, Unit::Line, "a\nc"), + ("a\nb\nc", 2, Direction::Backward, Unit::Line, "a\nc"), + ("a\nb", 3, Direction::Forward, Unit::Line, "a\n"), + ] { + let mut buffer = at(text, caret); + assert!(buffer.delete(direction, unit).is_some()); + assert_eq!(buffer.text(), left, "{text:?}"); + } +} + +#[test] +fn a_selection_is_deleted_whole_whatever_the_unit() { + for unit in [Unit::Grapheme, Unit::Word, Unit::Line] { + let mut buffer = over("abcd", 3, 1); + buffer.delete(Direction::Forward, unit); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("ad", (1, 1))); + } } #[test] fn nothing_to_delete_is_no_edit() { - let mut buffer = at("a", 0); - assert!(buffer.delete(Direction::Backward, Unit::Grapheme).is_none()); - assert!(buffer.undo().is_none()); + assert!(at("a", 0).delete(Direction::Backward, Unit::Grapheme).is_none()); + assert!(at("a", 1).delete(Direction::Forward, Unit::Word).is_none()); + assert!(at("", 0).delete(Direction::Forward, Unit::Line).is_none()); } +// ── Moving lines, commenting, indenting ── + #[test] fn lines_move_up_and_down_with_the_caret() { - let mut buffer = at("a\nb\nc", 2); - buffer.move_lines(Direction::Backward); - assert_eq!(buffer.text(), "b\na\nc"); - assert_eq!(buffer.selection(), Selection::caret(0)); + let mut buffer = at("a\nbcd\nc", 3); + + assert_eq!(buffer.move_lines(Direction::Backward).unwrap().first_line, 0); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("bcd\na\nc", (1, 1))); buffer.move_lines(Direction::Forward); buffer.move_lines(Direction::Forward); - assert_eq!(buffer.text(), "a\nc\nb"); - assert!(buffer.move_lines(Direction::Forward).is_none()); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("a\nc\nbcd", (5, 5))); } #[test] -fn a_comment_goes_on_every_line_then_comes_off() { - let mut buffer = Buffer::new("a\n b\n\nc"); - buffer.select_all(); - buffer.toggle_comment("//"); - assert_eq!(buffer.text(), "// a\n // b\n\n// c"); - buffer.select_all(); +fn the_first_line_does_not_move_up_nor_the_last_down() { + assert!(at("a\nb", 0).move_lines(Direction::Backward).is_none()); + assert!(at("a\nb", 3).move_lines(Direction::Forward).is_none()); +} + +/// A selection ending at the start of a line leaves that line where it is. +#[test] +fn every_line_a_selection_touches_moves() { + let mut buffer = over("a\nb\nc\nd", 2, 6); + + buffer.move_lines(Direction::Forward); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("a\nd\nb\nc", (4, 8))); + buffer.move_lines(Direction::Backward); + buffer.move_lines(Direction::Backward); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("b\nc\na\nd", (0, 4))); +} + +/// Joined with `\n` alone, they left the text with both endings and the caret one character off. +#[test] +fn lines_moved_in_a_crlf_text_keep_their_endings() { + let mut buffer = at("a\r\nbc\r\nd", 4); + + buffer.move_lines(Direction::Backward); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("bc\r\na\r\nd", (1, 1))); + + buffer.move_lines(Direction::Forward); + buffer.move_lines(Direction::Forward); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("a\r\nd\r\nbc", (7, 7))); +} + +fn commented(text: &str, anchor: usize, head: usize) -> (String, (usize, usize)) { + let mut buffer = over(text, anchor, head); buffer.toggle_comment("//"); - assert_eq!(buffer.text(), "a\n b\n\nc"); + (buffer.text(), selected(&buffer)) +} + +#[test] +fn a_comment_goes_before_every_line_selected_and_not_before_a_blank_one() { + assert_eq!(commented("a\n b\n\n \nc", 0, 10), ("// a\n // b\n\n \n// c".to_string(), (0, 19))); +} + +#[test] +fn a_comment_comes_off_only_when_every_line_has_it() { + assert_eq!(commented("// a\n //b\n\n// c", 0, 16).0, "a\n b\n\nc"); + assert_eq!(commented("// a\nb", 0, 6).0, "// // a\n// b"); +} + +#[test] +fn a_comment_at_a_caret_takes_its_line_and_the_caret_follows_its_text() { + for (before, at, after, then) in [ + ( + "a +bc +d", + 3, + "a +// bc +d", + 6, + ), + ( + "a +// bc +d", + 6, + "a +bc +d", + 3, + ), + ( + "a +// bc +d", + 7, + "a +bc +d", + 4, + ), + ("// a", 4, "a", 1), + ("//a", 3, "a", 1), + (" ab", 2, " // ab", 2), + (" ab", 1, " // ab", 1), + (" ab", 4, " // ab", 7), + (" // ab", 4, " ab", 2), + (" ", 2, " ", 2), + ] { + let expected = (after.to_string(), (then, then)); + assert_eq!(commented(before, at, at), expected, "{before:?} at {at}"); + } +} + +#[test] +fn a_comment_leaves_the_line_a_selection_ends_at_the_start_of() { + assert_eq!(commented("a\nb\nc", 0, 2), ("// a\nb\nc".to_string(), (0, 4))); } #[test] fn tab_and_shift_tab_are_one_step_each() { let mut buffer = Buffer::new("a\nb"); buffer.select_all(); + buffer.indent(" "); assert_eq!(buffer.text(), " a\n b"); - buffer.outdent(" "); + assert!(buffer.outdent(" ").is_some()); assert_eq!(buffer.text(), "a\nb"); + assert!(buffer.outdent(" ").is_none()); buffer.undo(); assert_eq!(buffer.text(), " a\n b"); } +// ── Searching and replacing ── + +#[test] +fn a_search_is_counted_with_the_match_the_selection_is_on() { + let mut buffer = over("id x id x id", 5, 7); + + let on = buffer.count(&query("id", "")); + assert_eq!((on.total, on.current, on.capped), (3, Some(2), false)); + buffer.move_to(6, false); + assert_eq!(buffer.count(&query("id", "")).current, None); +} + +#[test] +fn a_count_stops_at_its_cap() { + let matches = |count: usize| Buffer::new(&"a ".repeat(count)).count(&query("a", "")); + + assert!(!matches(search::COUNT_CAP - 1).capped); + let capped = matches(search::COUNT_CAP + 5); + assert_eq!((capped.total, capped.capped), (search::COUNT_CAP, true)); +} + +#[test] +fn a_seek_selects_the_next_match_that_way_and_wraps_round() { + use Direction::{Backward, Forward}; + let mut buffer = Buffer::new("id x id x id"); + for (from, direction, found) in [ + (4, Forward, 5..7), + (5, Forward, 5..7), + (11, Forward, 0..2), + (7, Backward, 5..7), + (6, Backward, 0..2), + (0, Backward, 10..12), + ] { + assert!(buffer.seek(&query("id", ""), from, direction)); + assert_eq!(buffer.selection().range(), found, "from {from}"); + } +} + #[test] -fn search_counts_seeks_and_wraps() { - let query = Query { - search: "id".into(), - ..Query::default() - }; - let mut buffer = at("id x id x id", 4); - assert!(buffer.seek(&query, 4, Direction::Forward)); - assert_eq!(buffer.selection().range(), 5..7); - let count = buffer.count(&query); - assert_eq!((count.total, count.current), (3, Some(2))); - buffer.seek(&query, 11, Direction::Forward); - assert_eq!(buffer.selection().range(), 0..2, "wraps round to the start"); - buffer.seek(&query, 0, Direction::Backward); - assert_eq!(buffer.selection().range(), 10..12); +fn a_seek_that_finds_nothing_leaves_the_selection() { + let mut buffer = over("abc", 1, 2); + + assert!(!buffer.seek(&query("z", ""), 0, Direction::Forward)); + assert_eq!(selected(&buffer), (1, 2)); } #[test] -fn replace_one_selects_first_then_replaces_and_replace_all_is_one_step() { - let query = Query { - search: "a".into(), - replace: "xyz".into(), - ..Query::default() - }; +fn replacing_one_selects_a_match_first_then_replaces_it_and_selects_the_next() { let mut buffer = at("a b a", 0); - assert!(buffer.replace_one(&query).is_none()); - assert_eq!(buffer.selection().range(), 0..1); - buffer.replace_one(&query); - assert_eq!(buffer.text(), "xyz b a"); - assert_eq!(buffer.selection().range(), 6..7); - let mut buffer = Buffer::new("a b a"); - let (count, _) = buffer.replace_all(&query); - assert_eq!((count, buffer.text().as_str()), (2, "xyz b xyz")); + assert!(buffer.replace_one(&query("a", "xyz")).is_none()); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("a b a", (0, 1))); + assert!(buffer.replace_one(&query("a", "xyz")).is_some()); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("xyz b a", (6, 7))); +} + +/// The replacement holds what is searched: it is not replaced again. +#[test] +fn replacing_one_goes_past_what_it_wrote() { + let mut buffer = over("a a", 0, 1); + + buffer.replace_one(&query("a", "aa")); + + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("aa a", (3, 4))); +} + +#[test] +fn replacing_all_is_one_step_of_undo() { + let mut buffer = at("é a b a", 7); + + let (count, _) = buffer.replace_all(&query("a", "xyz")); + assert_eq!((count, buffer.text().as_str()), (2, "é xyz b xyz")); + assert_eq!(selected(&buffer), (7, 7)); buffer.undo(); - assert_eq!(buffer.text(), "a b a"); + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("é a b a", (7, 7))); + buffer.redo(); + assert_eq!(buffer.text(), "é xyz b xyz"); } #[test] -fn an_edit_says_the_line_it_starts_on() { - let mut buffer = at("a\nb\nc", 4); - assert_eq!(buffer.insert("!").first_line, 2); - assert_eq!(buffer.line_count(), 3); - assert_eq!(buffer.line(2), "!c"); +fn replacing_all_keeps_the_caret_within_what_is_left() { + let mut buffer = at("aaaa", 4); + + buffer.replace_all(&query("a", "")); + + assert_eq!((buffer.text().as_str(), selected(&buffer)), ("", (0, 0))); +} + +#[test] +fn replacing_all_of_nothing_is_no_edit() { + let mut buffer = Buffer::new("a"); + + assert_eq!(buffer.replace_all(&query("z", "x")), (0, None)); + assert!(buffer.undo().is_none()); +} + +#[test] +fn a_regular_expression_s_groups_are_replaced_in_each_match() { + let swap = Query { regexp: true, ..query(r"(\w+):(\d+)", "$2px $1") }; + let mut buffer = Buffer::new("a:1 b:22"); + + buffer.replace_all(&swap); + + assert_eq!(buffer.text(), "1px a 22px b"); +} + +#[test] +fn a_letter_typed_over_a_selection_is_a_step_of_its_own() { + let mut buffer = over("abc", 0, 2); + typed(&mut buffer, "xy"); + + buffer.undo(); + assert_eq!(buffer.text(), "xc"); + buffer.undo(); + assert_eq!(buffer.text(), "abc"); +} + +#[test] +fn a_line_typed_after_a_space_starts_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a \nb"); + + buffer.undo(); + assert_eq!(buffer.text(), "a "); +} + +#[test] +fn what_was_redone_is_undone_again_and_typing_after_it_is_a_step_of_its_own() { + let mut buffer = Buffer::new(""); + typed(&mut buffer, "a"); + buffer.undo(); + buffer.redo(); + typed(&mut buffer, "b"); + + buffer.undo(); + assert_eq!(buffer.text(), "a"); + buffer.undo(); + assert_eq!(buffer.text(), ""); +} + +/// A carriage return alone is a space like another, for a word. +#[test] +fn a_step_by_word_goes_over_a_carriage_return_alone() { + assert_eq!(Buffer::new("a\r b").step(1, Direction::Forward, Unit::Word), 4); } diff --git a/crates/text/src/diff.rs b/crates/text/src/diff.rs index 2970eff95..fcfd08ecd 100644 --- a/crates/text/src/diff.rs +++ b/crates/text/src/diff.rs @@ -63,10 +63,7 @@ mod tests { #[test] fn a_split_statement_marks_its_lines_and_nothing_after() { - assert_eq!( - changed_lines("keep\nf(a, b)\nend", "keep\nf(\n a,\n b,\n)\nend"), - [1, 2, 3, 4] - ); + assert_eq!(changed_lines("keep\nf(a, b)\nend", "keep\nf(\n a,\n b,\n)\nend"), [1, 2, 3, 4]); } #[test] @@ -78,9 +75,21 @@ mod tests { fn texts_too_long_to_compare_mark_every_new_line() { let before: Vec = (0..2100).map(|n| format!("old {n}")).collect(); let after: Vec = (0..2100).map(|n| format!("new {n}")).collect(); - assert_eq!( - changed_lines(&before.join("\n"), &after.join("\n")).len(), - 2100 - ); + assert_eq!(changed_lines(&before.join("\n"), &after.join("\n")).len(), 2100); + } + + #[test] + fn lines_added_at_either_end_are_marked() { + assert_eq!(changed_lines("a\nb", "x\na\nb"), [0]); + assert_eq!(changed_lines("a\nb", "a\nb\nx"), [2]); + assert_eq!(changed_lines("", "a\nb"), [0, 1]); + assert_eq!(changed_lines("a\na", "a\na\na"), [2]); + } + + /// The longest run of lines kept: the fewest marked. + #[test] + fn a_line_moved_is_the_only_one_marked() { + assert_eq!(changed_lines("a\nb\nc\nd", "b\nc\nd\na"), [3]); + assert_eq!(changed_lines("a\nb\nc\nd\ne", "e\na\nb\nx\nd"), [0, 3]); } } diff --git a/crates/text/src/format.rs b/crates/text/src/format.rs index 86690f66e..36179106f 100644 --- a/crates/text/src/format.rs +++ b/crates/text/src/format.rs @@ -45,10 +45,7 @@ impl Parser { /// Prettier's own options, as the library's settings make them. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[expect( - clippy::struct_excessive_bools, - reason = "Prettier's own switches, one for one" -)] +#[expect(clippy::struct_excessive_bools, reason = "Prettier's own switches, one for one")] pub struct Options { pub print_width: u32, pub tab_width: u32, @@ -106,10 +103,7 @@ pub fn format(request: &Request) -> Answer { }; // A snippet ends where it was written to end; Prettier's closing newline is a file's. if !request.text.ends_with('\n') { - let kept = text - .strip_suffix("\r\n") - .or_else(|| text.strip_suffix('\n')) - .map(str::len); + let kept = text.strip_suffix("\r\n").or_else(|| text.strip_suffix('\n')).map(str::len); if let Some(kept) = kept { text.truncate(kept); } diff --git a/crates/text/src/format/host.rs b/crates/text/src/format/host.rs index f87fd7903..46aa0800a 100644 --- a/crates/text/src/format/host.rs +++ b/crates/text/src/format/host.rs @@ -9,7 +9,7 @@ use rquickjs::{Array, Context, Ctx, Function, Object, Promise, Runtime, Value}; use super::{Options, Parser}; -/// Prettier's own files, as `npm run prettier` copies them: each sets a global. +/// Prettier's own files, as `scripts/prettier.mjs` copies them: each sets a global. const SOURCES: [&str; 10] = [ include_str!("../../prettier/standalone.js"), include_str!("../../prettier/angular.js"), @@ -24,8 +24,7 @@ const SOURCES: [&str; 10] = [ ]; /// Its promise settled into a plain object: the text and cursor, or where the syntax broke. -const PRINT: &str = - "globalThis.__print = (text, options) => prettier.formatWithCursor(text, options).then( +const PRINT: &str = "globalThis.__print = (text, options) => prettier.formatWithCursor(text, options).then( ({ formatted, cursorOffset }) => ({ text: formatted, cursor: cursorOffset }), (error) => ({ line: error?.loc?.start?.line, column: error?.loc?.start?.column }), );"; @@ -62,13 +61,7 @@ static HOST: OnceLock> = OnceLock::new(); /// `cursor` in UTF-16 units of `text`. pub(super) fn print(text: &str, cursor: usize, parser: Parser, options: Options) -> Printed { let (answer, answered) = mpsc::channel(); - let job = Job { - text: text.to_owned(), - cursor, - parser, - options, - answer, - }; + let job = Job { text: text.to_owned(), cursor, parser, options, answer }; if HOST.get_or_init(start).send(job).is_err() { return Printed::Failed; } @@ -84,9 +77,7 @@ fn start() -> Sender { .spawn(move || { let prettier = Prettier::load(); for job in queue { - let printed = prettier - .as_ref() - .map_or(Printed::Failed, |prettier| prettier.print(&job)); + let printed = prettier.as_ref().map_or(Printed::Failed, |prettier| prettier.print(&job)); let _ = job.answer.send(printed); } }); @@ -112,10 +103,7 @@ impl Prettier { ctx.eval::<(), _>(PRINT) }); loaded.ok()?; - Some(Self { - _runtime: runtime, - context, - }) + Some(Self { _runtime: runtime, context }) } fn print(&self, job: &Job) -> Printed { @@ -136,10 +124,7 @@ fn call<'js>(ctx: &Ctx<'js>, job: &Job) -> rquickjs::Result> { let options = Object::new(ctx.clone())?; options.set("parser", job.parser.name())?; options.set("plugins", plugins)?; - options.set( - "cursorOffset", - f64::from(u32::try_from(job.cursor).unwrap_or(0)), - )?; + options.set("cursorOffset", f64::from(u32::try_from(job.cursor).unwrap_or(0)))?; // Prettier's default is `lf`, which would rewrite a CRLF snippet's every line. options.set("endOfLine", "auto")?; options.set("printWidth", job.options.print_width)?; @@ -147,11 +132,7 @@ fn call<'js>(ctx: &Ctx<'js>, job: &Job) -> rquickjs::Result> { options.set("useTabs", job.options.use_tabs)?; options.set("singleQuote", job.options.single_quote)?; options.set("semi", job.options.semi)?; - let trailing = if job.options.trailing_comma { - "all" - } else { - "none" - }; + let trailing = if job.options.trailing_comma { "all" } else { "none" }; options.set("trailingComma", trailing)?; let print: Function<'_> = globals.get("__print")?; print.call((job.text.as_str(), options)) @@ -175,10 +156,7 @@ fn plugins_of(parser: Parser) -> &'static [&'static str] { fn read(printed: &Object<'_>) -> Printed { if let Ok(Some(text)) = printed.get::<_, Option>("text") { let cursor = printed.get::<_, f64>("cursor").unwrap_or(0.0); - return Printed::Text { - text, - cursor: whole(cursor), - }; + return Printed::Text { text, cursor: whole(cursor) }; } let place = |key| printed.get::<_, Option>(key).ok().flatten(); match (place("line"), place("column")) { diff --git a/crates/text/src/format/tests.rs b/crates/text/src/format/tests.rs index d50dab3d8..34d7f50bb 100644 --- a/crates/text/src/format/tests.rs +++ b/crates/text/src/format/tests.rs @@ -31,9 +31,7 @@ fn request(case: &Value) -> Request { let (input, options) = (&case["input"], &case["options"]); Request { text: input["text"].as_str().unwrap().to_owned(), - cursor: input["cursor"] - .as_u64() - .map_or(0, |at| usize::try_from(at).unwrap()), + cursor: input["cursor"].as_u64().map_or(0, |at| usize::try_from(at).unwrap()), parser: parser(input["parser"].as_str().unwrap()), options: Options { print_width: number(&options["printWidth"]), @@ -59,10 +57,7 @@ fn expected(output: &Value) -> Answer { .collect(), }, "unchanged" => Answer::Unchanged, - "syntax" => Answer::Syntax { - line: number(&output["line"]), - column: number(&output["column"]), - }, + "syntax" => Answer::Syntax { line: number(&output["line"]), column: number(&output["column"]) }, "fields" => Answer::Fields, other => panic!("no answer {other}"), } @@ -101,9 +96,5 @@ fn a_cursor_past_a_wide_character_lands_where_it_was() { panic!("{answer:?}"); }; assert_eq!(text, "const crab = '🦀';\nconst b = 1;"); - assert_eq!( - cursor, - text.chars().count() - 1, - "after the 1, before the semicolon" - ); + assert_eq!(cursor, text.chars().count() - 1, "after the 1, before the semicolon"); } diff --git a/crates/text/src/highlight.rs b/crates/text/src/highlight.rs index 20a129074..ec7de3632 100644 --- a/crates/text/src/highlight.rs +++ b/crates/text/src/highlight.rs @@ -55,13 +55,10 @@ pub fn is_ready() -> bool { /// Whether a grammar of that name exists; `false` while they load. pub fn has_syntax(name: &str) -> bool { - SYNTAXES - .get() - .is_some_and(|set| set.find_syntax_by_name(name).is_some()) + SYNTAXES.get().is_some_and(|set| set.find_syntax_by_name(name).is_some()) } -static KEY: LazyLock = - LazyLock::new(|| Scope::new("meta.mapping.key").expect("a valid scope")); +static KEY: LazyLock = LazyLock::new(|| Scope::new("meta.mapping.key").expect("a valid scope")); /// Which class the innermost scope that has one gives, a scope's answer kept. #[derive(Default)] @@ -70,11 +67,7 @@ struct Classes(HashMap>); impl Classes { fn of(&mut self, stack: &ScopeStack) -> Option { // A key is a property whatever it is written as, its quotes included, as Lezer reads it. - if stack - .as_slice() - .iter() - .any(|scope| KEY.is_prefix_of(*scope)) - { + if stack.as_slice().iter().any(|scope| KEY.is_prefix_of(*scope)) { return Some(Token::Property); } stack @@ -155,10 +148,7 @@ impl Highlighter { pub fn new(name: &str) -> Option { let syntax = SYNTAXES.get()?.find_syntax_by_name(name)?; Some(Self { - checkpoints: vec![Checkpoint { - state: ParseState::new(syntax), - stack: ScopeStack::new(), - }], + checkpoints: vec![Checkpoint { state: ParseState::new(syntax), stack: ScopeStack::new() }], classes: Classes::default(), }) } @@ -169,18 +159,14 @@ impl Highlighter { } /// How far the kept states reach, in lines. - pub fn reach(&self) -> usize { + #[cfg(test)] + fn reach(&self) -> usize { (self.checkpoints.len() - 1) * EVERY } /// The states kept up to `line`'s block, parsing at most `budget` lines; `true` once there. /// `line_of(i)` gives line `i` with its line ending. - pub fn extend( - &mut self, - line_of: impl Fn(usize) -> Option, - line: usize, - budget: usize, - ) -> bool { + pub fn extend(&mut self, line_of: impl Fn(usize) -> Option, line: usize, budget: usize) -> bool { let wanted = line / EVERY; let mut parsed = 0; while self.checkpoints.len() <= wanted { @@ -236,24 +222,23 @@ impl Highlighter { let mut coloured: Line = Vec::new(); let mut from_byte = 0; let mut from_char = 0; - let mut push = - |coloured: &mut Line, stack: &ScopeStack, to_byte: usize, classes: &mut Classes| { - let to_byte = to_byte.min(text.len()); - if to_byte <= from_byte { - return; - } - let to_char = from_char + text[from_byte..to_byte].chars().count(); - if let Some(token) = classes.of(stack) { - match coloured.last_mut() { - Some((range, last)) if *last == token && range.end == from_char => { - range.end = to_char; - } - _ => coloured.push((from_char..to_char, token)), + let mut push = |coloured: &mut Line, stack: &ScopeStack, to_byte: usize, classes: &mut Classes| { + let to_byte = to_byte.min(text.len()); + if to_byte <= from_byte { + return; + } + let to_char = from_char + text[from_byte..to_byte].chars().count(); + if let Some(token) = classes.of(stack) { + match coloured.last_mut() { + Some((range, last)) if *last == token && range.end == from_char => { + range.end = to_char; } + _ => coloured.push((from_char..to_char, token)), } - from_byte = to_byte; - from_char = to_char; - }; + } + from_byte = to_byte; + from_char = to_char; + }; for (at, op) in ops { push(&mut coloured, &point.stack, at, &mut self.classes); let _ = point.stack.apply(&op); @@ -271,9 +256,7 @@ pub fn highlight(text: &str, name: &str) -> Vec { }; let lines: Vec = text.split_inclusive('\n').map(str::to_owned).collect(); let count = lines.len(); - highlighter - .lines(|at| lines.get(at).cloned(), 0..count) - .unwrap_or_default() + highlighter.lines(|at| lines.get(at).cloned(), 0..count).unwrap_or_default() } #[cfg(test)] @@ -297,27 +280,11 @@ mod tests { #[test] fn typescript_reads_as_the_reference_s_classes() { warm(); - let found = tokens( - "// note\nconst port: number = 5432;\nlog(\"up\");\n", - "TypeScript", - ); - assert!( - found.contains(&("// note".into(), Token::Comment)), - "{found:?}" - ); - assert!( - found.contains(&("const".into(), Token::Keyword)), - "{found:?}" - ); - assert!( - found.contains(&("5432".into(), Token::Literal)), - "{found:?}" - ); - assert!( - found - .iter() - .any(|(text, token)| text.contains("up") && *token == Token::String) - ); + let found = tokens("// note\nconst port: number = 5432;\nlog(\"up\");\n", "TypeScript"); + assert!(found.contains(&("// note".into(), Token::Comment)), "{found:?}"); + assert!(found.contains(&("const".into(), Token::Keyword)), "{found:?}"); + assert!(found.contains(&("5432".into(), Token::Literal)), "{found:?}"); + assert!(found.iter().any(|(text, token)| text.contains("up") && *token == Token::String)); assert!(found.contains(&("log".into(), Token::Name)), "{found:?}"); } @@ -331,10 +298,7 @@ mod tests { .any(|(text, token)| text.contains("host") && *token == Token::Property), "{found:?}" ); - assert!( - found.contains(&("5432".into(), Token::Literal)), - "{found:?}" - ); + assert!(found.contains(&("5432".into(), Token::Literal)), "{found:?}"); } #[test] @@ -342,15 +306,9 @@ mod tests { warm(); assert!(has_syntax("Prisma")); let found = tokens("model User {\n id Int @id // key\n}\n", "Prisma"); - assert!( - found.contains(&("model".into(), Token::Keyword)), - "{found:?}" - ); + assert!(found.contains(&("model".into(), Token::Keyword)), "{found:?}"); assert!(found.contains(&("@id".into(), Token::Name)), "{found:?}"); - assert!( - found.contains(&("// key".into(), Token::Comment)), - "{found:?}" - ); + assert!(found.contains(&("// key".into(), Token::Comment)), "{found:?}"); } #[test] @@ -367,20 +325,13 @@ mod tests { let line_of = |at: usize| lines.get(at).cloned(); let mut highlighter = Highlighter::new("JavaScript").unwrap(); - assert!( - highlighter.lines(line_of, 600..610).is_none(), - "not reached yet" - ); + assert!(highlighter.lines(line_of, 600..610).is_none(), "not reached yet"); assert!(!highlighter.extend(line_of, 600, 200)); assert!(highlighter.extend(line_of, 600, 1000)); assert!(highlighter.reach() + EVERY > 600); let coloured = highlighter.lines(line_of, 600..610).unwrap(); assert_eq!(coloured.len(), 10); - assert!( - coloured[0] - .iter() - .any(|(_, token)| *token == Token::Keyword) - ); + assert!(coloured[0].iter().any(|(_, token)| *token == Token::Keyword)); highlighter.invalidate_from(300); assert_eq!(highlighter.reach(), 256); @@ -410,16 +361,10 @@ mod tests { warm(); let (mut ts, mut json) = (String::new(), String::new()); for n in 0..14_000 { - let _ = writeln!( - ts, - "export const f{n} = (a: number): string => `${{a}}` + \"x\"; // {n}" - ); + let _ = writeln!(ts, "export const f{n} = (a: number): string => `${{a}}` + \"x\"; // {n}"); } for n in 0..22_000 { - let _ = writeln!( - json, - " {{\"id\": {n}, \"name\": \"item {n}\", \"ok\": true}}," - ); + let _ = writeln!(json, " {{\"id\": {n}, \"name\": \"item {n}\", \"ok\": true}},"); } for (name, text) in [("TypeScript", ts), ("JSON", json)] { let text = &text[..text.len().min(1 << 20)]; @@ -430,10 +375,80 @@ mod tests { highlighter.lines(line_of, 0..60); let screen = started.elapsed(); highlighter.extend(line_of, lines.len(), usize::MAX); - println!( - "{name} 1 MB: first screen {screen:?}, whole {:?}", - started.elapsed() - ); + println!("{name} 1 MB: first screen {screen:?}, whole {:?}", started.elapsed()); + } + } + + #[test] + fn two_stretches_of_one_class_apart_are_two() { + warm(); + let lines = highlight("[1, 2]\n", "JSON"); + + let literals: Vec<_> = lines[0].iter().filter(|(_, token)| *token == Token::Literal).collect(); + assert_eq!(literals, [&(1..2, Token::Literal), &(4..5, Token::Literal)]); + } + + #[test] + fn two_classes_side_by_side_are_two_stretches() { + warm(); + let lines = highlight("x=\"a\"//b\n", "TypeScript"); + + let tokens: Vec = lines[0].iter().map(|(_, token)| *token).collect(); + assert!(tokens.ends_with(&[Token::String, Token::Comment]), "{:?}", lines[0]); + assert!(lines[0].windows(2).all(|pair| pair[0].0.end <= pair[1].0.start)); + } + + /// Read past the end of a block, its state is kept for the next. + #[test] + fn lines_read_past_a_block_keep_its_state_once() { + warm(); + let lines: Vec = (0..600).map(|n| format!("let a{n} = {n};\n")).collect(); + let line_of = |at: usize| lines.get(at).cloned(); + let mut highlighter = Highlighter::new("JavaScript").unwrap(); + + highlighter.lines(line_of, 0..EVERY - 1); + assert_eq!(highlighter.reach(), 0); + highlighter.lines(line_of, 0..EVERY * 2); + assert_eq!(highlighter.reach(), EVERY * 2); + highlighter.lines(line_of, 0..EVERY * 2); + assert_eq!(highlighter.reach(), EVERY * 2); + } + + /// As many lines as the budget, block by block; a text's end is an end. + #[test] + fn states_are_kept_within_a_budget() { + warm(); + let lines: Vec = (0..EVERY * 3).map(|_| "let a;\n".to_owned()).collect(); + let line_of = |at: usize| lines.get(at).cloned(); + let mut highlighter = Highlighter::new("JavaScript").unwrap(); + + assert!(!highlighter.extend(line_of, EVERY * 2, EVERY)); + assert_eq!(highlighter.reach(), EVERY); + assert!(highlighter.extend(line_of, EVERY * 2, EVERY)); + assert_eq!(highlighter.reach(), EVERY * 2); + assert!(highlighter.extend(line_of, EVERY * 50, usize::MAX)); + } + + /// A scope is read whole: `stringy` is no `string`. + #[test] + fn a_scope_gives_the_class_of_the_first_rule_it_falls_under() { + for (scope, token) in [ + ("comment.line", Some(Token::Comment)), + ("string", Some(Token::String)), + ("stringy.quoted", None), + ("constant.character.escape.js", Some(Token::String)), + ("constant.numeric", Some(Token::Literal)), + ("variable.function.js", Some(Token::Keyword)), + ("variable.other", Some(Token::Property)), + ("meta.block", None), + ] { + assert_eq!(class(Scope::new(scope).unwrap()), token, "{scope}"); } } + + #[test] + fn a_grammar_is_there_by_its_name() { + warm(); + assert!(is_ready() && has_syntax("Rust") && !has_syntax("rust")); + } } diff --git a/crates/text/src/indent.rs b/crates/text/src/indent.rs index c47ba68db..8b7d1de90 100644 --- a/crates/text/src/indent.rs +++ b/crates/text/src/indent.rs @@ -27,17 +27,11 @@ pub fn indent(text: &str, start: usize, end: usize, unit: &str) -> TextEdit { " ".repeat(width - column % width) }; let caret = start + insert.chars().count(); - return TextEdit { - from: start, - to: end, - insert, - selection_start: caret, - selection_end: caret, - }; + return TextEdit { from: start, to: end, insert, selection_start: caret, selection_end: caret }; } edit_lines(&chars, start, end, |line| LineChange { remove: 0, - add: if line.is_empty() { "" } else { unit }.to_owned(), + add: if matches!(line, [] | ['\r']) { "" } else { unit }.to_owned(), }) } @@ -45,23 +39,13 @@ pub fn indent(text: &str, start: usize, end: usize, unit: &str) -> TextEdit { /// no line had any. pub fn outdent(text: &str, start: usize, end: usize, unit: &str) -> Option { let chars: Vec = text.chars().collect(); - let width = if unit == "\t" { - TAB_WIDTH - } else { - unit.chars().count() - }; + let width = if unit == "\t" { TAB_WIDTH } else { unit.chars().count() }; let edit = edit_lines(&chars, start, end, |line| { if line.first() == Some(&'\t') { - return LineChange { - remove: 1, - add: String::new(), - }; + return LineChange { remove: 1, add: String::new() }; } let spaces = line.iter().take_while(|c| **c == ' ').count(); - LineChange { - remove: spaces.min(width), - add: String::new(), - } + LineChange { remove: spaces.min(width), add: String::new() } }); let before: String = chars[edit.from..edit.to].iter().collect(); (edit.insert != before).then_some(edit) @@ -98,25 +82,13 @@ struct LineChange { } fn line_start(chars: &[char], at: usize) -> usize { - chars[..at] - .iter() - .rposition(|c| *c == '\n') - .map_or(0, |newline| newline + 1) + chars[..at].iter().rposition(|c| *c == '\n').map_or(0, |newline| newline + 1) } /// A selection ending at the start of a line leaves that line alone, as in any code editor. -fn edit_lines( - chars: &[char], - start: usize, - end: usize, - change: impl Fn(&[char]) -> LineChange, -) -> TextEdit { +fn edit_lines(chars: &[char], start: usize, end: usize, change: impl Fn(&[char]) -> LineChange) -> TextEdit { let from = line_start(chars, start); - let last = if end > start && chars.get(end - 1) == Some(&'\n') { - end - 1 - } else { - end - }; + let last = if end > start && chars.get(end - 1) == Some(&'\n') { end - 1 } else { end }; let to = chars[last..] .iter() .position(|c| *c == '\n') @@ -131,11 +103,7 @@ fn edit_lines( let place = |at: usize| new_at + added + at.saturating_sub(old_at + remove); if (old_at..=old_at + line.len()).contains(&start) { // A selection from a line's start keeps the level it just gained. - selection_start = if start == old_at && start != end { - new_at - } else { - place(start) - }; + selection_start = if start == old_at && start != end { new_at } else { place(start) }; } if (old_at..=old_at + line.len()).contains(&end) { selection_end = place(end); @@ -149,13 +117,7 @@ fn edit_lines( if end > to { selection_end = end + insert.chars().count() - (to - from); } - TextEdit { - from, - to, - insert, - selection_start, - selection_end, - } + TextEdit { from, to, insert, selection_start, selection_end } } #[cfg(test)] @@ -198,10 +160,7 @@ mod tests { applied(&text, outdent(&text, start, end, unit)) } - #[expect( - clippy::unnecessary_wraps, - reason = "compared with what an edit answers" - )] + #[expect(clippy::unnecessary_wraps, reason = "compared with what an edit answers")] fn some(text: &str) -> Option { Some(text.to_owned()) } @@ -218,6 +177,7 @@ mod tests { assert_eq!(tab("a\n[b\nc]\nd", " "), some("a\n[ b\n c]\nd")); assert_eq!(tab("let [x] = 1", " "), some(" let [x] = 1")); assert_eq!(tab("[a\n\nb\n]c", " "), some("[ a\n\n b\n]c")); + assert_eq!(tab("[a\r\n\r\nb]", " "), some("[ a\r\n\r\n b]")); } #[test] @@ -235,14 +195,8 @@ mod tests { fn a_rewrite_replaces_only_what_differs() { let edit = rewrite("keep f(a,b) keep", "keep f(a, b) keep", 4); assert_eq!((edit.from, edit.to, edit.insert.as_str()), (9, 9, " ")); - assert_eq!( - applied("keep f(a,b) keep", Some(edit)), - some("keep[] f(a, b) keep") - ); - assert_eq!( - applied("a b", Some(rewrite("a b", "a b", 3))), - some("a b[]") - ); + assert_eq!(applied("keep f(a,b) keep", Some(edit)), some("keep[] f(a, b) keep")); + assert_eq!(applied("a b", Some(rewrite("a b", "a b", 3))), some("a b[]")); assert_eq!(applied("aa", Some(rewrite("aa", "aaa", 3))), some("aaa[]")); } @@ -250,4 +204,18 @@ mod tests { fn offsets_are_characters_not_bytes() { assert_eq!(tab("é[]", " "), some("é []")); } + + /// The caret at the start of a line is of that line, not of the one above. + #[test] + fn a_caret_at_a_line_s_start_is_of_that_line() { + assert_eq!(shift_tab(" a\n[] b", " "), some(" a\n[]b")); + assert_eq!(tab("a\n[]b", " "), some("a\n []b")); + } + + /// At a level already, Tab goes a whole one further. + #[test] + fn tab_at_a_level_goes_to_the_next() { + assert_eq!(tab(" []a", " "), some(" []a")); + assert_eq!(tab("[]", " "), some(" []")); + } } diff --git a/crates/text/src/search.rs b/crates/text/src/search.rs index dc5036880..21caf531a 100644 --- a/crates/text/src/search.rs +++ b/crates/text/src/search.rs @@ -4,7 +4,7 @@ use std::ops::Range; -use regex::{Regex, RegexBuilder}; +use regex::{Captures, Regex, RegexBuilder}; /// Past this many, the count stops: typing in the field stays smooth on a 2 MB snippet. pub const COUNT_CAP: usize = 1000; @@ -33,11 +33,7 @@ impl Query { if self.search.is_empty() { return None; } - let pattern = if self.regexp { - self.search.clone() - } else { - regex::escape(&self.search) - }; + let pattern = if self.regexp { self.search.clone() } else { regex::escape(&self.search) }; RegexBuilder::new(&pattern) .case_insensitive(!self.case_sensitive) .multi_line(true) @@ -50,8 +46,8 @@ impl Query { self.search.is_empty() || self.matcher().is_some() } - /// What replaces `found`: `$&` and `$1` name the match and its groups in a regular - /// expression, as they did in the reference; a text replaces as it is written. + /// What replaces `found`: in a regular expression, `$&` is the match, `$1` its first group + /// whatever follows it, `$$` a dollar, as in the reference; a text replaces as it is written. pub fn replacement(&self, found: &str) -> String { if !self.regexp { return self.replace.clone(); @@ -62,13 +58,38 @@ impl Query { let Some(captures) = matcher.captures(found) else { return self.replace.clone(); }; - let template = self.replace.replace("$&", "${0}"); - let mut out = String::new(); - captures.expand(&template, &mut out); - out + expanded(&self.replace, &captures) } } +/// ⚠️ Not the crate's own expansion, which reads `$1px` as a group named `1px`: nothing. +fn expanded(template: &str, captures: &Captures<'_>) -> String { + let mut out = String::new(); + let mut rest = template; + while let Some(at) = rest.find('$') { + out.push_str(&rest[..at]); + let after = &rest[at + 1..]; + let digits = after.len() - after.trim_start_matches(|c: char| c.is_ascii_digit()).len(); + // The longest number that is a group: `$12` with two groups is the first, then `2`. + let group = (1..=digits).rev().find_map(|length| { + let number: usize = after[..length].parse().ok()?; + (1..captures.len()).contains(&number).then_some((number, length)) + }); + let taken = if let Some((number, length)) = group { + out.push_str(captures.get(number).map_or("", |found| found.as_str())); + length + } else if after.starts_with('&') { + out.push_str(&captures[0]); + 1 + } else { + out.push('$'); + usize::from(after.starts_with('$')) + }; + rest = &after[taken..]; + } + out + rest +} + /// Every match of `query` in `text`, up to `cap`. pub fn find(text: &str, query: &Query, cap: usize) -> Vec> { let Some(matcher) = query.matcher() else { @@ -111,69 +132,106 @@ mod tests { use super::*; fn query(search: &str) -> Query { - Query { - search: search.into(), - ..Query::default() - } + Query { search: search.into(), ..Query::default() } + } + + fn pattern(search: &str) -> Query { + Query { regexp: true, ..query(search) } + } + + fn found(text: &str, query: &Query) -> Vec> { + find(text, query, COUNT_CAP) } #[test] fn a_text_is_found_ignoring_case_unless_asked() { - assert_eq!(find("Host host", &query("host"), COUNT_CAP), [0..4, 5..9]); - let exact = Query { - case_sensitive: true, - ..query("host") - }; - assert_eq!(find("Host host", &exact, COUNT_CAP), vec![5..9]); + let exact = Query { case_sensitive: true, ..query("été") }; + + assert_eq!(found("Été été", &query("été")), [0..3, 4..7]); + assert_eq!(found("Été été", &exact), vec![4..7]); } + /// An underscore and an accented letter are of a word. #[test] fn whole_words_skip_a_match_inside_a_word() { - let whole = Query { - whole_word: true, - ..query("id") - }; - assert_eq!( - find("id user_id idx (id)", &whole, COUNT_CAP), - [0..2, 16..18] - ); + let whole = Query { whole_word: true, ..query("id") }; + + assert_eq!(found("id user_id idx éid (id)", &whole), [0..2, 20..22]); } #[test] fn a_regular_expression_reads_its_metacharacters_and_a_text_does_not() { - let pattern = Query { - regexp: true, - ..query(r"\d+") - }; - assert_eq!(find("a 12 b 345", &pattern, COUNT_CAP), [2..4, 7..10]); - assert_eq!(find("a.b axb", &query("a.b"), COUNT_CAP), vec![0..3]); - assert!( - !Query { - regexp: true, - ..query("(") - } - .is_valid() - ); + assert_eq!(found("a 12 b 345", &pattern(r"\d+")), [2..4, 7..10]); + assert_eq!(found("a.b axb", &query("a.b")), vec![0..3]); } + /// A line each, as an editor reads them. #[test] - fn ranges_are_characters_and_the_cap_stops_the_count() { - assert_eq!(find("éé x", &query("x"), COUNT_CAP), vec![3..4]); - assert_eq!(find("aaaa", &query("a"), 2).len(), 2); + fn a_regular_expression_s_anchors_are_the_line_s() { + assert_eq!(found("ab\nab", &pattern("^a")), [0..1, 3..4]); + assert_eq!(found("ab\nab", &pattern("b$")), [1..2, 4..5]); } #[test] - fn a_replacement_names_the_groups_in_a_regular_expression_only() { - let swap = Query { - regexp: true, - replace: "$2=$1 ($&)".into(), - ..query(r"(\w+):(\w+)") - }; - assert_eq!(swap.replacement("port:5432"), "5432=port (port:5432)"); - let plain = Query { - replace: "$1".into(), - ..query("a") - }; - assert_eq!(plain.replacement("a"), "$1"); + fn a_match_of_nothing_is_none() { + assert!(found("ab", &pattern("x*")).is_empty()); + assert_eq!(found("xab", &pattern("x*")), vec![0..1]); + } + + #[test] + fn nothing_is_found_of_an_empty_search_or_a_pattern_that_does_not_read() { + assert!(found("ab", &query("")).is_empty()); + assert!(found("a(b", &pattern("(")).is_empty()); + assert!(query("").is_valid() && query("(").is_valid() && pattern("a").is_valid()); + assert!(!pattern("(").is_valid()); + } + + #[test] + fn ranges_are_characters_not_bytes() { + assert_eq!(found("éé x🦀 x", &query("x")), [3..4, 6..7]); + } + + #[test] + fn as_many_matches_as_asked_are_found() { + assert_eq!(find("aaaa", &query("a"), 2), [0..1, 1..2]); + assert_eq!(find("aa", &query("a"), 2).len(), 2); + } + + fn replaced(search: &str, replace: &str, found: &str) -> String { + Query { replace: replace.into(), ..pattern(search) }.replacement(found) + } + + /// `$1px` was read as a group named `1px`, and replaced by nothing (#1776). + #[test] + fn a_replacement_names_the_match_and_its_groups() { + for (template, expected) in [ + ("$2=$1 ($&)", "5432=port (port:5432)"), + ("$1px", "portpx"), + ("$1_$2", "port_5432"), + ("$12", "port2"), + ("$01", "port"), + ("$3 $0", "$3 $0"), + ("$$1 $total $", "$1 $total $"), + ("é$2é", "é5432é"), + ("", ""), + ] { + assert_eq!(replaced(r"(\w+):(\w+)", template, "port:5432"), expected, "{template}"); + } + } + + #[test] + fn a_group_that_took_no_part_is_empty() { + assert_eq!(replaced("a(b)?", "[$1]", "a"), "[]"); + } + + #[test] + fn a_replacement_is_as_written_where_no_group_can_be_read() { + assert_eq!(query_replacing("a", "$1$&").replacement("a"), "$1$&"); + assert_eq!(replaced("(", "$1", "a"), "$1"); + assert_eq!(replaced("(b)", "$1", "a"), "$1"); + } + + fn query_replacing(search: &str, replace: &str) -> Query { + Query { replace: replace.into(), ..query(search) } } } diff --git a/crates/text/src/shield.rs b/crates/text/src/shield.rs index d7d236a5e..fb2042a81 100644 --- a/crates/text/src/shield.rs +++ b/crates/text/src/shield.rs @@ -22,12 +22,7 @@ pub struct Shielded { swaps: Vec, } -impl Shielded { - /// What each `{{…}}` became, in order. - pub fn stand_ins(&self) -> impl Iterator { - self.swaps.iter().map(|swap| swap.stand_in.as_str()) - } -} +impl Shielded {} /// Every `{{…}}` becomes an identifier of its own length, which every language a formatter /// reads accepts where a value goes. `None` when no marker is free, which only a text written @@ -40,10 +35,7 @@ pub fn shield_fields(text: &str, cursor: usize) -> Option { let mut rest = 0; let len = |s: &str| s.chars().count(); while let Some(start) = text[rest..].find(OPEN).map(|at| rest + at) { - let Some(end) = text[start + OPEN.len()..] - .find(CLOSE) - .map(|at| start + OPEN.len() + at) - else { + let Some(end) = text[start + OPEN.len()..].find(CLOSE).map(|at| start + OPEN.len() + at) else { break; }; let original = &text[start..end + CLOSE.len()]; @@ -58,28 +50,16 @@ pub fn shield_fields(text: &str, cursor: usize) -> Option { }; } shielded.push_str(&stand_in); - swaps.push(Swap { - original: original.to_owned(), - stand_in, - }); + swaps.push(Swap { original: original.to_owned(), stand_in }); rest = start + original.len(); } shielded.push_str(&text[rest..]); - Some(Shielded { - text: shielded, - cursor: shielded_cursor, - marker, - swaps, - }) + Some(Shielded { text: shielded, cursor: shielded_cursor, marker, swaps }) } /// The fields back, in order. `None` when one is missing, moved past another or copied: the text /// is then not the one that was typed, and nothing of it may be applied. -pub fn unshield_fields( - formatted: &str, - cursor: usize, - shielded: &Shielded, -) -> Option<(String, usize)> { +pub fn unshield_fields(formatted: &str, cursor: usize, shielded: &Shielded) -> Option<(String, usize)> { let mut text = String::new(); let mut restored = cursor; let mut from = 0; @@ -118,6 +98,11 @@ fn stand_in_for(marker: &str, index: usize, length: usize) -> String { mod tests { use super::*; + /// What each `{{…}}` became, in order. + fn stand_ins(shielded: &Shielded) -> Vec<&str> { + shielded.swaps.iter().map(|swap| swap.stand_in.as_str()).collect() + } + #[test] fn every_field_becomes_an_identifier_of_its_own_length() { let text = "host = {{db_host}}; port = {{ port = 5432 }}"; @@ -125,15 +110,11 @@ mod tests { assert!(!shielded.text.contains("{{")); assert_eq!(shielded.text.len(), text.len()); - let originals: Vec<_> = shielded - .swaps - .iter() - .map(|swap| swap.original.as_str()) - .collect(); + let originals: Vec<_> = shielded.swaps.iter().map(|swap| swap.original.as_str()).collect(); assert_eq!(originals, ["{{db_host}}", "{{ port = 5432 }}"]); assert!( - shielded - .stand_ins() + stand_ins(&shielded) + .iter() .all(|stand_in| stand_in.chars().all(|c| c.is_ascii_alphanumeric())) ); } @@ -171,7 +152,7 @@ mod tests { #[test] fn the_fields_come_back_with_the_cursor() { let shielded = shield_fields("a({{x}},{{y}})", 0).unwrap(); - let ins: Vec<_> = shielded.stand_ins().collect(); + let ins: Vec<_> = stand_ins(&shielded); let formatted = format!("a(\n {},\n {},\n);\n", ins[0], ins[1]); let expected = "a(\n {{x}},\n {{y}},\n);\n"; @@ -183,12 +164,41 @@ mod tests { #[test] fn a_field_lost_copied_or_moved_is_refused() { let shielded = shield_fields("{{x}} {{y}}", 0).unwrap(); - let ins: Vec<_> = shielded.stand_ins().map(str::to_owned).collect(); - assert!(unshield_fields(&ins[0], 0, &shielded).is_none()); + let ins: Vec<_> = stand_ins(&shielded); + assert!(unshield_fields(ins[0], 0, &shielded).is_none()); assert!(unshield_fields(&format!("{} {}", ins[1], ins[0]), 0, &shielded).is_none()); let one = shield_fields("{{x}}", 0).unwrap(); - let stand_in = one.stand_ins().next().unwrap().to_owned(); + let stand_in = stand_ins(&one).remove(0); assert!(unshield_fields(&format!("{stand_in} {stand_in}"), 0, &one).is_none()); } + + /// At its edges a caret stays outside the field; inside, it goes to its start. + #[test] + fn a_caret_at_the_edge_of_a_field_stays_at_that_edge() { + let shielded = |cursor: usize| shield_fields("ab {{field}} cd", cursor).unwrap().cursor; + + assert_eq!([2, 3, 4, 11, 12, 13].map(shielded), [2, 3, 3, 3, 12, 13]); + } + + /// Two letters, one of each: one letter twice would be found inside itself. + #[test] + fn the_marker_is_two_letters_that_differ() { + for text in ["{{a}}", "qz {{a}}", "qz qj qk qv qw {{a}}"] { + let marker = shield_fields(text, 0).unwrap().marker; + let letters: Vec = marker.chars().collect(); + assert!(letters.len() == 2 && letters[0] != letters[1] && !text.contains(&marker), "{marker}"); + } + } + + /// Each field's own length, before and after the caret. + #[test] + fn the_caret_comes_back_past_fields_that_were_lengthened() { + let text = "{{}}-{{}} end"; + for cursor in [4, 5, 9, 13] { + let shielded = shield_fields(text, cursor).unwrap(); + let back = unshield_fields(&shielded.text, shielded.cursor, &shielded); + assert_eq!(back, Some((text.to_owned(), cursor)), "{cursor}"); + } + } } diff --git a/crates/text/src/words.rs b/crates/text/src/words.rs index 160248cb8..d2809cd86 100644 --- a/crates/text/src/words.rs +++ b/crates/text/src/words.rs @@ -21,11 +21,7 @@ pub fn count_words(markdown: &str) -> usize { /// What a word is made of, for every editor: 0 a space, 1 punctuation, 2 a word character /// (a letter, a digit, `_`). A run of one class is one word. pub(crate) fn class(c: char) -> u8 { - if c.is_alphanumeric() || c == '_' { - 2 - } else { - u8::from(!c.is_whitespace()) - } + if c.is_alphanumeric() || c == '_' { 2 } else { u8::from(!c.is_whitespace()) } } /// What a double click on the `char` at `at` takes: the run of word characters, punctuation or @@ -59,19 +55,10 @@ mod tests { #[test] fn counts_the_words_and_none_of_the_markdown_around_them() { - assert_eq!( - count_words("## Standup\n\n- **Ship** it and `tag`\n> quoted _here_"), - 7 - ); - assert_eq!( - count_words("See [the runbook](https://example.com/run-book)."), - 3 - ); + assert_eq!(count_words("## Standup\n\n- **Ship** it and `tag`\n> quoted _here_"), 7); + assert_eq!(count_words("See [the runbook](https://example.com/run-book)."), 3); assert_eq!(count_words("- [x] ship it\n- [ ] tag it\n indented"), 5); - assert_eq!( - count_words("| Host | Port |\n| --- | --- |\n| db | 5432 |"), - 4 - ); + assert_eq!(count_words("| Host | Port |\n| --- | --- |\n| db | 5432 |"), 4); } #[test] @@ -81,14 +68,8 @@ mod tests { fn word(text: &str, offset: usize) -> &str { let range = word_around(text, offset); - let start = text - .char_indices() - .nth(range.start) - .map_or(text.len(), |(at, _)| at); - let end = text - .char_indices() - .nth(range.end) - .map_or(text.len(), |(at, _)| at); + let start = text.char_indices().nth(range.start).map_or(text.len(), |(at, _)| at); + let end = text.char_indices().nth(range.end).map_or(text.len(), |(at, _)| at); &text[start..end] } @@ -115,4 +96,25 @@ mod tests { assert_eq!(count_words(""), 0); assert_eq!(count_words(" \n\n "), 0); } + + /// On a blank line there is nothing to take. + #[test] + fn a_double_click_past_a_line_takes_its_last_run_and_nothing_of_a_blank_one() { + for (text, at, taken) in [ + ("ab\n\ncd", 2, "ab"), + ("ab\n\ncd", 3, ""), + ("ab\n\ncd", 4, "cd"), + ("\n", 0, ""), + ("\n", 1, ""), + ("a \nb", 2, " "), + ] { + assert_eq!(word(text, at), taken, "{text:?} {at}"); + } + } + + #[test] + fn a_number_and_a_word_of_any_script_are_words() { + assert_eq!(count_words("3 été Привет 日本 a-b l'a 'x'"), 7); + assert_eq!(count_words("-- * __ !"), 0); + } } diff --git a/crates/ui/src/action.rs b/crates/ui/src/action.rs index 0f414212b..35c9f807e 100644 --- a/crates/ui/src/action.rs +++ b/crates/ui/src/action.rs @@ -52,13 +52,7 @@ pub enum GlobalAction { } impl GlobalAction { - pub const ALL: [Self; 5] = [ - Self::Capture, - Self::NewNote, - Self::Palette, - Self::PaletteHere, - Self::Quit, - ]; + pub const ALL: [Self; 5] = [Self::Capture, Self::NewNote, Self::Palette, Self::PaletteHere, Self::Quit]; /// The name a second launch of the `e2e` flavour hands over (`--action new-note`). pub fn name(self) -> &'static str { diff --git a/crates/ui/src/api/attachments.rs b/crates/ui/src/api/attachments.rs index cd9489c65..9d8ad1de7 100644 --- a/crates/ui/src/api/attachments.rs +++ b/crates/ui/src/api/attachments.rs @@ -24,15 +24,8 @@ pub fn attach_image( image: &ColorImage, ) -> Pending { let [width, height] = image.size; - let size = ( - u32::try_from(width).unwrap_or(u32::MAX), - u32::try_from(height).unwrap_or(u32::MAX), - ); - let rgba: Vec = image - .pixels - .iter() - .flat_map(egui::Color32::to_srgba_unmultiplied) - .collect(); + let size = (u32::try_from(width).unwrap_or(u32::MAX), u32::try_from(height).unwrap_or(u32::MAX)); + let rgba: Vec = image.pixels.iter().flat_map(egui::Color32::to_srgba_unmultiplied).collect(); backend.db(move |engine| attachments::attach_image(engine, note, &name, size, &rgba)) } diff --git a/crates/ui/src/api/board.rs b/crates/ui/src/api/board.rs index f03d4dace..822669a48 100644 --- a/crates/ui/src/api/board.rs +++ b/crates/ui/src/api/board.rs @@ -4,8 +4,7 @@ use engine::folders::{ self, board::{ - BoardArrangement, BoardQuery, BoardScope, BoardView, CardPlacement, PreviewLines, - ZonePlacement, + BoardArrangement, BoardQuery, BoardScope, BoardView, CardPlacement, PreviewLines, ZonePlacement, }, }; @@ -35,6 +34,5 @@ pub fn arrange( scope: BoardScope, lines: PreviewLines, ) -> Pending { - backend - .db(move |engine| folders::arrange_board(engine, &space_id, root_id.as_ref(), scope, lines)) + backend.db(move |engine| folders::arrange_board(engine, &space_id, root_id.as_ref(), scope, lines)) } diff --git a/crates/ui/src/api/folders.rs b/crates/ui/src/api/folders.rs index c51d68a49..b4487246f 100644 --- a/crates/ui/src/api/folders.rs +++ b/crates/ui/src/api/folders.rs @@ -21,11 +21,7 @@ pub fn create( parent_id: Option, name: String, ) -> Pending { - let draft = FolderDraft { - space_id, - name, - parent_id, - }; + let draft = FolderDraft { space_id, name, parent_id }; backend.db(move |engine| folders::create_folder(engine, &draft)) } @@ -71,9 +67,7 @@ pub fn move_into( folder: String, lines: PreviewLines, ) -> Pending { - backend.db(move |engine| { - folders::move_notes_into(engine, &ids, &folder, lines).map(Reversible::Move) - }) + backend.db(move |engine| folders::move_notes_into(engine, &ids, &folder, lines).map(Reversible::Move)) } pub fn file( @@ -82,7 +76,5 @@ pub fn file( folder: Option, lines: PreviewLines, ) -> Pending { - backend.db(move |engine| { - folders::file_notes(engine, &ids, folder.as_ref(), lines).map(Reversible::File) - }) + backend.db(move |engine| folders::file_notes(engine, &ids, folder.as_ref(), lines).map(Reversible::File)) } diff --git a/crates/ui/src/api/http.rs b/crates/ui/src/api/http.rs index 8d01a799d..a551e92e8 100644 --- a/crates/ui/src/api/http.rs +++ b/crates/ui/src/api/http.rs @@ -9,8 +9,8 @@ use engine::http::{ history::{HistoryDay, HistoryDraft, HistoryEntry}, model::{ ContainerSettings, HeaderFault, HttpContents, HttpItem, HttpMethod, HttpPlace, HttpRequest, - HttpRequestDraft, HttpRequestPatch, HttpTree, KeyValue, NewPlace, RequestBody, - RequestDocument, RequestKind, + HttpRequestDraft, HttpRequestPatch, HttpTree, KeyValue, NewPlace, RequestBody, RequestDocument, + RequestKind, }, query::{QuerySide, SyncedQuery}, send::{Exchange, ImpliedHeader, NoteText, SendRequest, SentResponse}, @@ -51,11 +51,7 @@ pub fn run_order(backend: &Backend, item: HttpItem) -> Pending, -) -> Pending<()> { +pub fn save_run_order(backend: &Backend, item: HttpItem, order: Vec) -> Pending<()> { backend.db(move |engine| http::save_http_run_order(engine, &item, order)) } @@ -87,11 +83,7 @@ pub fn requests(backend: &Backend, ids: Vec) -> Pending } /// The draft written whole: what Rust kept comes back. -pub fn save_request( - backend: &Backend, - id: String, - patch: HttpRequestPatch, -) -> Pending { +pub fn save_request(backend: &Backend, id: String, patch: HttpRequestPatch) -> Pending { backend.db(move |engine| http::save_http_request(engine, &id, &patch)) } @@ -129,8 +121,7 @@ pub fn create_request( method: HttpMethod::Get, document: RequestDocument::default(), }; - backend - .db(move |engine| http::create_http_request(engine, &draft).map(|created| Some(created.id))) + backend.db(move |engine| http::create_http_request(engine, &draft).map(|created| Some(created.id))) } pub fn rename(backend: &Backend, item: HttpItem, name: String) -> Pending { @@ -186,13 +177,8 @@ pub fn looks_secret(path: &str) -> bool { } /// What a request placed there inherits, and from where. -pub fn inherited( - backend: &Backend, - collection_id: String, - folder_id: Option, -) -> Pending { - backend - .db(move |engine| http::inherited_http_settings(engine, &collection_id, folder_id.as_ref())) +pub fn inherited(backend: &Backend, collection_id: String, folder_id: Option) -> Pending { + backend.db(move |engine| http::inherited_http_settings(engine, &collection_id, folder_id.as_ref())) } /// Each write of the environments' page answers the set to show once written, if another. @@ -200,11 +186,7 @@ pub fn create_environment(backend: &Backend, name: String) -> Pending Pending> { +pub fn save_environment(backend: &Backend, id: String, patch: EnvironmentPatch) -> Pending> { backend.db(move |engine| { http::save_http_environment(engine, &id, &patch)?; Ok(None) @@ -218,16 +200,8 @@ pub fn save_globals(backend: &Backend, rows: Vec) -> Pending Pending> { - backend.db(move |engine| { - Ok(Some( - http::duplicate_http_environment(engine, &id, &name)?.id, - )) - }) +pub fn duplicate_environment(backend: &Backend, id: String, name: String) -> Pending> { + backend.db(move |engine| Ok(Some(http::duplicate_http_environment(engine, &id, &name)?.id))) } pub fn delete_environment(backend: &Backend, id: String) -> Pending> { @@ -267,11 +241,7 @@ pub fn settings(backend: &Backend, item: HttpItem) -> Pending backend.db(move |engine| http::http_settings(engine, &item)) } -pub fn save_settings( - backend: &Backend, - item: HttpItem, - settings: ContainerSettings, -) -> Pending<()> { +pub fn save_settings(backend: &Backend, item: HttpItem, settings: ContainerSettings) -> Pending<()> { backend.db(move |engine| http::save_http_settings(engine, &item, settings)) } @@ -417,11 +387,7 @@ pub fn response_image(backend: &Backend, id: String) -> Pending> } /// What a body implies, whether a JSON one reads, whether its method seldom carries one. -pub fn describe_body( - backend: &Backend, - body: RequestBody, - method: HttpMethod, -) -> Pending { +pub fn describe_body(backend: &Backend, body: RequestBody, method: HttpMethod) -> Pending { backend.compute(move |_| http::describe_http_body(&body, method)) } @@ -431,10 +397,7 @@ pub fn describe_graphql(backend: &Backend, document: GraphqlDocument) -> Pending } /// The variables with a `null` for each one the operation declares and they lack. -pub fn add_graphql_variables( - backend: &Backend, - document: GraphqlDocument, -) -> Pending> { +pub fn add_graphql_variables(backend: &Backend, document: GraphqlDocument) -> Pending> { backend.compute(move |_| http::add_graphql_variables(&document).map(Some)) } diff --git a/crates/ui/src/api/libraries.rs b/crates/ui/src/api/libraries.rs index e9b52d26f..21b0d2550 100644 --- a/crates/ui/src/api/libraries.rs +++ b/crates/ui/src/api/libraries.rs @@ -25,6 +25,14 @@ pub fn rename(backend: &Backend, id: String, name: String) -> Pending<()> { backend.db(move |engine| libraries::rename_library(engine, &id, &name)) } +/// The notes the core holds in the clear, wiped: the application is leaving. +pub fn wipe_index(backend: &Backend) -> Pending<()> { + backend.db(|engine| { + engine.wipe_index(); + Ok(()) + }) +} + pub fn delete(backend: &Backend, id: String) -> Pending<()> { backend.db(move |engine| libraries::delete_library(engine, &id)) } diff --git a/crates/ui/src/api/notes.rs b/crates/ui/src/api/notes.rs index d1721e240..51d109bde 100644 --- a/crates/ui/src/api/notes.rs +++ b/crates/ui/src/api/notes.rs @@ -33,25 +33,18 @@ pub fn picture_drawing( ) -> Pending { backend.compute(move |_| { let fonts = crate::theme::fonts::for_drawings(); - let taken = drawing::Drawing::read(&content) - .and_then(|scene| drawing::pictures(&scene, &palette, &fonts)); + let taken = + drawing::Drawing::read(&content).and_then(|scene| drawing::pictures(&scene, &palette, &fonts)); let uri = engine::notes::drawing::uri_of; Ok(engine::notes::drawing::DrawingPictures { - thumbnail: taken - .as_ref() - .map_or_else(String::new, |it| uri(&it.thumbnail)), - picture: taken - .as_ref() - .map_or_else(String::new, |it| uri(&it.picture)), + thumbnail: taken.as_ref().map_or_else(String::new, |it| uri(&it.thumbnail)), + picture: taken.as_ref().map_or_else(String::new, |it| uri(&it.picture)), }) }) } /// The draft on screen cut into slides, with the map of its headings. -pub fn present_note( - backend: &Backend, - markdown: String, -) -> Pending { +pub fn present_note(backend: &Backend, markdown: String) -> Pending { backend.compute(move |_| engine::notes::present_note(&markdown)) } @@ -71,12 +64,7 @@ pub fn export_drawing( export: crate::notes::DrawingExport, ) -> Pending { backend.compute(move |_| { - let crate::notes::DrawingExport { - name, - content, - palette, - format, - } = export; + let crate::notes::DrawingExport { name, content, palette, format } = export; let name = format!("{name}.{}", format.extension()); let Some(path) = dialog.save(&name) else { return Ok(Exported::Cancelled); @@ -87,16 +75,13 @@ pub fn export_drawing( let Some(bytes) = written else { return Ok(Exported::Cancelled); }; - let shown = path.file_name().map_or_else( - || path.display().to_string(), - |name| name.to_string_lossy().into_owned(), - ); - Ok( - match engine::tools::write_file(&path.to_string_lossy(), &bytes) { - Ok(()) => Exported::Saved(shown), - Err(_) => Exported::Unwritable, - }, - ) + let shown = path + .file_name() + .map_or_else(|| path.display().to_string(), |name| name.to_string_lossy().into_owned()); + Ok(match engine::tools::write_file(&path.to_string_lossy(), &bytes) { + Ok(()) => Exported::Saved(shown), + Err(_) => Exported::Unwritable, + }) }) } @@ -148,18 +133,10 @@ pub fn normalize_tag(tag: &str) -> Option<&str> { } /// Into another kind; the undo writes back the body the core answers it had. -pub fn convert( - backend: &Backend, - id: String, - into: engine::notes::kind::NoteKind, -) -> Pending { +pub fn convert(backend: &Backend, id: String, into: engine::notes::kind::NoteKind) -> Pending { backend.db(move |engine| { let converted = notes::convert_note(engine, &id, into)?; - Ok(Reversible::Convert { - id, - into, - previous: converted.previous, - }) + Ok(Reversible::Convert { id, into, previous: converted.previous }) }) } @@ -176,10 +153,7 @@ pub fn field_ranges(content: &str) -> Vec> { } chars.push(content.chars().count()); let at = |unit: u32| chars.get(unit as usize).copied().unwrap_or(chars.len()); - spans - .into_iter() - .map(|span| at(span.from)..at(span.to)) - .collect() + spans.into_iter().map(|span| at(span.from)..at(span.to)).collect() } /// The bodies kept beside a note, newest first: instants and sizes, never the bodies. @@ -187,10 +161,7 @@ pub fn list_drawings(backend: &Backend) -> Pending Pending> { +pub fn list_revisions(backend: &Backend, id: String) -> Pending> { backend.db(move |engine| notes::list_revisions(engine, &id)) } @@ -236,9 +207,8 @@ pub fn create(backend: &Backend, draft: NoteDraft) -> Pending { } pub fn pin(backend: &Backend, ids: Vec, pinned: bool) -> Pending { - backend.db(move |engine| { - notes::set_pinned(engine, &ids, pinned).map(|ids| Reversible::Pin { ids, pinned }) - }) + backend + .db(move |engine| notes::set_pinned(engine, &ids, pinned).map(|ids| Reversible::Pin { ids, pinned })) } /// Triaging is not editing: `updated_at` stays where it was. diff --git a/crates/ui/src/api/preferences.rs b/crates/ui/src/api/preferences.rs index b785d4e56..1d423eb09 100644 --- a/crates/ui/src/api/preferences.rs +++ b/crates/ui/src/api/preferences.rs @@ -78,8 +78,7 @@ mod tests { let _ = log::set_logger(&HEARD); log::set_max_level(log::LevelFilter::Warn); let (backend, _profile) = testing::unlocked(); - let directory = - engine::db::run_here(backend.engine(), libraries::open_library_directory).unwrap(); + let directory = engine::db::run_here(backend.engine(), libraries::open_library_directory).unwrap(); // A folder where the file goes: no write can take its place. let taken = directory.join(layout::PREFERENCES); std::fs::create_dir_all(taken.join("inside")).unwrap(); @@ -89,9 +88,6 @@ mod tests { assert!(written.poll().unwrap().is_err()); let heard = HEARD.0.lock().unwrap(); - assert!( - heard.iter().any(|line| line.contains("preferences")), - "{heard:?}" - ); + assert!(heard.iter().any(|line| line.contains("preferences")), "{heard:?}"); } } diff --git a/crates/ui/src/api/tools.rs b/crates/ui/src/api/tools.rs index e1e856748..6030e44d2 100644 --- a/crates/ui/src/api/tools.rs +++ b/crates/ui/src/api/tools.rs @@ -135,10 +135,7 @@ pub fn estimate_transfer(backend: &Backend, request: TransferRequest) -> Pending backend.compute(move |_| Ok(transfer::estimate(&request))) } -pub fn describe_permissions( - backend: &Backend, - request: PermissionsRequest, -) -> Pending { +pub fn describe_permissions(backend: &Backend, request: PermissionsRequest) -> Pending { backend.compute(move |_| Ok(permissions::describe(&request))) } @@ -172,10 +169,7 @@ pub fn generate_json(backend: &Backend, request: GenerateRequest) -> Pending Pending> { +pub fn generate_identifiers(backend: &Backend, request: IdentifiersRequest) -> Pending> { backend.compute(move |_| tools::generate_identifiers(&request)) } diff --git a/crates/ui/src/api/transfer.rs b/crates/ui/src/api/transfer.rs index c78b521aa..cdc468930 100644 --- a/crates/ui/src/api/transfer.rs +++ b/crates/ui/src/api/transfer.rs @@ -14,10 +14,7 @@ use crate::backend::{Backend, Pending}; /// `json` stays on the way in: an export written before the archive is still importable. const READABLE: [&str; 2] = ["devnotes", "json"]; -pub fn pick_bundle( - backend: &Backend, - dialog: Arc, -) -> Pending> { +pub fn pick_bundle(backend: &Backend, dialog: Arc) -> Pending> { backend.compute(move |_| Ok(dialog.open_of(&READABLE))) } @@ -46,11 +43,7 @@ pub fn is_protected(backend: &Backend, path: String) -> Pending { backend.compute(move |_| transfer::export_is_protected(&path)) } -pub fn import( - backend: &Backend, - path: String, - passphrase: Option, -) -> Pending { +pub fn import(backend: &Backend, path: String, passphrase: Option) -> Pending { backend.spawn(move |engine| transfer::import_notes(engine, path, passphrase)) } diff --git a/crates/ui/src/api/undo.rs b/crates/ui/src/api/undo.rs index 6100883e1..f94f4491c 100644 --- a/crates/ui/src/api/undo.rs +++ b/crates/ui/src/api/undo.rs @@ -77,16 +77,12 @@ pub fn revert(backend: &Backend, action: Reversible, lines: PreviewLines) -> Pen } Reversible::Priority(previous) => notes::restore_priorities(engine, &previous), Reversible::File(previous) => folders::file_notes_back(engine, &previous, lines), - Reversible::Arrangement { - root_id, previous, .. - } => { + Reversible::Arrangement { root_id, previous, .. } => { let count = previous.zones.len() + previous.cards.len(); folders::save_board_layout(engine, root_id.as_ref(), &previous.zones, &previous.cards) .map(|()| self::count(count)) } - Reversible::FolderMove { was, .. } => { - folders::move_folder_back(engine, &was).map(u32::from) - } + Reversible::FolderMove { was, .. } => folders::move_folder_back(engine, &was).map(u32::from), Reversible::Convert { id, previous, .. } => { let patch = notes::model::NotePatch { kind: Some(previous.kind), diff --git a/crates/ui/src/api/vault.rs b/crates/ui/src/api/vault.rs index 2e83d3d2c..ef817a7d2 100644 --- a/crates/ui/src/api/vault.rs +++ b/crates/ui/src/api/vault.rs @@ -66,10 +66,7 @@ mod tests { use super::*; use crate::testing; - fn settled( - backend: &Backend, - mut pending: Pending, - ) -> Result { + fn settled(backend: &Backend, mut pending: Pending) -> Result { backend.settle(); pending.poll().expect("answered once settled") } @@ -78,20 +75,14 @@ mod tests { fn a_created_library_is_open() { let (backend, _profile) = testing::unlocked(); - assert_eq!( - settled(&backend, state(&backend)).unwrap(), - VaultState::Unlocked - ); + assert_eq!(settled(&backend, state(&backend)).unwrap(), VaultState::Unlocked); } #[test] fn a_library_reopens_with_its_phrase_and_only_with_it() { let profile = testing::locked(); let backend = testing::backend_on(profile.path()); - assert_eq!( - settled(&backend, state(&backend)).unwrap(), - VaultState::Locked - ); + assert_eq!(settled(&backend, state(&backend)).unwrap(), VaultState::Locked); let wrong = Zeroizing::new("not the phrase at all".to_string()); let refused = settled(&backend, unlock(&backend, wrong)).unwrap_err(); @@ -99,9 +90,6 @@ mod tests { let right = Zeroizing::new(testing::PASSPHRASE.to_string()); settled(&backend, unlock(&backend, right)).unwrap(); - assert_eq!( - settled(&backend, state(&backend)).unwrap(), - VaultState::Unlocked - ); + assert_eq!(settled(&backend, state(&backend)).unwrap(), VaultState::Unlocked); } } diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs index be911dd42..21afb20dc 100644 --- a/crates/ui/src/app.rs +++ b/crates/ui/src/app.rs @@ -94,8 +94,7 @@ impl DevNotesApp { startup.waker.fill(&cc.egui_ctx); cc.egui_ctx.set_fonts(theme::fonts::definitions()); // Like the reference's WebView: Ctrl+plus is not a zoom. - cc.egui_ctx - .options_mut(|options| options.zoom_with_keyboard = false); + cc.egui_ctx.options_mut(|options| options.zoom_with_keyboard = false); let mut state = AppState::new(startup.preferences, startup.reduced_motion); state.global_keys = GlobalKeys::with(startup.desktop.shortcuts); state.autostart = AutostartState::with(startup.desktop.autostart); @@ -155,9 +154,7 @@ impl DevNotesApp { } if let Some(inner) = viewport.inner_rect { // Native Wayland names no place: nothing reads it back there either. - let place = viewport - .outer_rect - .map_or(egui::Pos2::ZERO, |outer| outer.min); + let place = viewport.outer_rect.map_or(egui::Pos2::ZERO, |outer| outer.min); self.geometry = Some(Geometry { x: place.x, y: place.y, @@ -187,11 +184,8 @@ fn in_front(ctx: &egui::Context) -> bool { impl DevNotesApp { /// Read before the window is brought back: afterwards it is always in front. fn asked_from_outside(&mut self, action: GlobalAction, ctx: &egui::Context) { - let action = if action == GlobalAction::Palette && in_front(ctx) { - GlobalAction::PaletteHere - } else { - action - }; + let action = + if action == GlobalAction::Palette && in_front(ctx) { GlobalAction::PaletteHere } else { action }; reveal(ctx); self.state.apply(Action::Global(action), ctx, &self.backend); } @@ -212,9 +206,9 @@ impl DevNotesApp { } match GlobalAction::named(name) { // What a desktop's own shortcut runs is a global key pressed: the window comes back. - Some( - action @ (GlobalAction::Palette | GlobalAction::Capture | GlobalAction::NewNote), - ) => self.asked_from_outside(action, ctx), + Some(action @ (GlobalAction::Palette | GlobalAction::Capture | GlobalAction::NewNote)) => { + self.asked_from_outside(action, ctx); + } Some(action) => self.state.apply(Action::Global(action), ctx, &self.backend), None => log::warn!("A second launch asked for an unknown action"), } @@ -227,8 +221,7 @@ impl DevNotesApp { tray::Asked::Capture => self.asked_from_outside(GlobalAction::Capture, ctx), tray::Asked::Palette => self.asked_from_outside(GlobalAction::Palette, ctx), tray::Asked::Quit => { - self.state - .apply(Action::Global(GlobalAction::Quit), ctx, &self.backend); + self.state.apply(Action::Global(GlobalAction::Quit), ctx, &self.backend); } } } @@ -247,8 +240,7 @@ impl DevNotesApp { fn keep_the_tray_in_the_language(&mut self) { if self.tray_language != self.state.language { self.tray_language = self.state.language; - self.tray - .set_labels(&crate::services::tray::labels(self.tray_language)); + self.tray.set_labels(&crate::services::tray::labels(self.tray_language)); } } @@ -291,11 +283,7 @@ impl DevNotesApp { /// On the way down only: a window still minimised while it comes back stays. fn follow_the_minimize(&mut self, viewport: &egui::ViewportInfo, ctx: &egui::Context) { let minimized = viewport.minimized == Some(true); - if minimized - && !self.was_minimized - && self.state.settings.minimize_to_tray - && self.tray.exists() - { + if minimized && !self.was_minimized && self.state.settings.minimize_to_tray && self.tray.exists() { put_away(ctx); } self.was_minimized = minimized; @@ -350,11 +338,9 @@ impl eframe::App for DevNotesApp { self.state.update(ctx, &self.backend); self.keep_the_tray_in_the_language(); let listening = self.state.titlebar_view.listens_for_a_global_key(); - self.state.global_keys.update( - &self.state.settings.bindings, - listening, - &mut self.state.errors, - ); + self.state + .global_keys + .update(&self.state.settings.bindings, listening, &mut self.state.errors); let viewport = ctx.input(|input| input.viewport().clone()); self.remember(&viewport); self.follow_the_minimize(&viewport, ctx); @@ -446,6 +432,7 @@ impl eframe::App for DevNotesApp { fn on_exit(&mut self) { self.state.http.leaving(&self.backend); drop(api::attachments::sweep_copies(&self.backend)); + drop(api::libraries::wipe_index(&self.backend)); if !self.backend.drain(EXIT_LIMIT) { log::warn!("The exit did not wait any longer for the database to finish"); } @@ -503,6 +490,8 @@ mod global_key_tests; #[cfg(test)] mod palette_copy_tests; +#[cfg(test)] +mod preferences_tests; #[cfg(test)] mod tests { @@ -524,9 +513,7 @@ mod tests { (inbox, waker, receiver): (Inbox, Waker, Receiver), ) -> Startup { Startup { - paths: Paths { - profile: directory.to_path_buf(), - }, + paths: Paths { profile: directory.to_path_buf() }, window_file: directory.join("window.json"), geometry: None, reduced_motion: false, @@ -555,8 +542,7 @@ mod tests { } fn remove(&self) { - self.removed - .store(true, std::sync::atomic::Ordering::Relaxed); + self.removed.store(true, std::sync::atomic::Ordering::Relaxed); } } @@ -611,9 +597,7 @@ mod tests { let mut harness = open_library(directory.path()); let ctx = harness.ctx.clone(); - harness - .state_mut() - .asked_by_tray(tray::Asked::Palette, &ctx); + harness.state_mut().asked_by_tray(tray::Asked::Palette, &ctx); settle(&mut harness); assert!(harness.state().state().palette.is_open()); @@ -629,23 +613,29 @@ mod tests { }; harness.step(); - assert!( - fake.labels.lock().unwrap().is_empty(), - "built with its menu" - ); + assert!(fake.labels.lock().unwrap().is_empty(), "built with its menu"); harness.state_mut().state.language = other; harness.step(); harness.step(); - assert_eq!( - *fake.labels.lock().unwrap(), - [crate::services::tray::labels(other)] - ); + assert_eq!(*fake.labels.lock().unwrap(), [crate::services::tray::labels(other)]); eframe::App::on_exit(harness.state_mut()); assert!(!fake.exists()); } + /// The notes are in the clear in the index for as long as the library is open, and no longer. + #[test] + fn the_exit_wipes_the_index_once_everything_is_written() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = open_library(directory.path()); + assert!(harness.state().backend().engine().indexed() > 0, "the samples"); + + eframe::App::on_exit(harness.state_mut()); + + assert_eq!(harness.state().backend().engine().indexed(), 0); + } + fn visible_requests(harness: &Harness<'_, DevNotesApp>) -> usize { harness .output() @@ -659,8 +649,7 @@ mod tests { #[test] fn the_window_is_shown_once_its_first_frame_is_ready() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); // The harness runs its first frames while it is built: the request is behind us. assert!(harness.state().shown); @@ -704,8 +693,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let copies = left_in_the_plain_copies(directory.path()); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); settle(&mut harness); assert!(!copies.exists(), "before anything is unlocked"); @@ -728,14 +716,10 @@ mod tests { #[test] fn the_engine_starts_on_a_profile_with_no_library_yet() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); harness.step(); - let state = engine::db::run_here( - harness.state().backend().engine(), - engine::vault::vault_state, - ); + let state = engine::db::run_here(harness.state().backend().engine(), engine::vault::vault_state); assert_eq!(state.unwrap(), engine::vault::VaultState::Absent); } @@ -743,26 +727,16 @@ mod tests { #[test] fn a_maximised_window_keeps_the_size_it_had_before() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); let placed = egui::ViewportInfo { - outer_rect: Some(egui::Rect::from_min_size( - egui::pos2(10.0, 20.0), - egui::vec2(820.0, 640.0), - )), - inner_rect: Some(egui::Rect::from_min_size( - egui::pos2(10.0, 50.0), - egui::vec2(800.0, 600.0), - )), + outer_rect: Some(egui::Rect::from_min_size(egui::pos2(10.0, 20.0), egui::vec2(820.0, 640.0))), + inner_rect: Some(egui::Rect::from_min_size(egui::pos2(10.0, 50.0), egui::vec2(800.0, 600.0))), ..Default::default() }; let app = harness.state_mut(); app.remember(&placed); - app.remember(&egui::ViewportInfo { - maximized: Some(true), - ..placed.clone() - }); + app.remember(&egui::ViewportInfo { maximized: Some(true), ..placed.clone() }); let geometry = app.geometry.unwrap(); assert!(geometry.maximized); @@ -772,25 +746,19 @@ mod tests { pub(super) fn present(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> bool { use egui_kittest::kittest::Queryable; - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } pub(super) fn click(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) { use egui_kittest::kittest::Queryable; - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); settle(harness); } pub(super) fn type_into(harness: &mut Harness<'_, DevNotesApp>, author_id: &str, words: &str) { use egui_kittest::kittest::Queryable; click(harness, author_id); - harness - .get_by(|node| node.author_id() == Some(author_id)) - .type_text(words); + harness.get_by(|node| node.author_id() == Some(author_id)).type_text(words); settle(harness); } @@ -861,10 +829,7 @@ mod tests { node.author_id() == Some("status-toast") && node.label().is_some_and(|said| said.contains("c.pdf")) }); - assert!( - stacked.iter().all(|toast| toast.top() >= name.rect().top()), - "the latest is on top" - ); + assert!(stacked.iter().all(|toast| toast.top() >= name.rect().top()), "the latest is on top"); let crosses = harness.query_all_by(|node| node.author_id() == Some("status-dismiss")); crosses.last().unwrap().click(); @@ -878,10 +843,7 @@ mod tests { let mut harness = open_library(directory.path()); let before = top_of(&harness, "search-input"); let state = &mut harness.state_mut().state; - let failed = [ - i18n::keys::errors::ATTACHMENTS_LOAD_FAILED, - i18n::keys::errors::NOTE_SAVE_FAILED, - ]; + let failed = [i18n::keys::errors::ATTACHMENTS_LOAD_FAILED, i18n::keys::errors::NOTE_SAVE_FAILED]; for key in [failed[0], failed[1], failed[0]] { state.errors.notify(i18n::Message::new(key)); } @@ -918,10 +880,8 @@ mod tests { let mut harness = open_library(directory.path()); harness.set_size(egui::vec2(700.0, 620.0)); let now = harness.ctx.input(|input| input.time); - let pinned = crate::api::undo::Reversible::Pin { - ids: vec!["a".to_owned(), "b".to_owned()], - pinned: true, - }; + let pinned = + crate::api::undo::Reversible::Pin { ids: vec!["a".to_owned(), "b".to_owned()], pinned: true }; harness.state_mut().state.undo.record(pinned, now); let said = i18n::Message::new(i18n::keys::attachments::SAVED); harness.state_mut().state.status.report(said); @@ -944,11 +904,7 @@ mod tests { .set_missing_glyph_policy(egui::epaint::text::MissingGlyphPolicy::Tofu); settle(&mut harness); type_into(&mut harness, "vault-passphrase", crate::testing::PASSPHRASE); - type_into( - &mut harness, - "vault-confirmation", - crate::testing::PASSPHRASE, - ); + type_into(&mut harness, "vault-confirmation", crate::testing::PASSPHRASE); click(&mut harness, "vault-submit"); settle(&mut harness); assert!(harness.state().state().gate.is_open()); @@ -958,8 +914,7 @@ mod tests { #[test] fn the_areas_are_offered_only_once_the_library_is_open() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); settle(&mut harness); assert!(present(&harness, "theme-toggle")); @@ -968,9 +923,7 @@ mod tests { pub(super) fn count(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> usize { use egui_kittest::kittest::Queryable; - harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .count() + harness.query_all_by(|node| node.author_id() == Some(author_id)).count() } fn seeded_mark(harness: &Harness<'_, DevNotesApp>) -> Option { @@ -1042,8 +995,7 @@ mod tests { #[test] fn the_file_menu_is_offered_with_the_library_and_quits_on_the_second_click() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); settle(&mut harness); assert!(!present(&harness, "file-menu")); @@ -1056,16 +1008,12 @@ mod tests { /// The colour `words` were painted in by the last frame. fn ink_of(harness: &Harness<'_, DevNotesApp>, words: &str) -> Option { - harness - .output() - .shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == words => { - Some(text.galley.job.sections[0].format.color) - } - _ => None, - }) + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == words => { + Some(text.galley.job.sections[0].format.color) + } + _ => None, + }) } #[test] @@ -1109,21 +1057,18 @@ mod tests { let said = i18n::Message::new(i18n::keys::settings::COPIED); app.state.settings.copy_confirmation = false; - app.state - .copy_out(&ctx, &app.backend, "echo quiet".to_owned(), said.clone()); + app.state.copy_out(&ctx, &app.backend, "echo quiet".to_owned(), said.clone()); assert!(app.state.status.latest().is_none()); app.state.settings.copy_confirmation = true; - app.state - .copy_out(&ctx, &app.backend, "echo said".to_owned(), said); + app.state.copy_out(&ctx, &app.backend, "echo said".to_owned(), said); assert!(app.state.status.latest().is_some()); } #[test] fn the_about_menu_stays_at_the_gate() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); settle(&mut harness); assert!(!present(&harness, "file-menu")); @@ -1166,8 +1111,7 @@ mod tests { #[test] fn the_toggle_switches_to_the_other_theme() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); settle(&mut harness); let before = harness.ctx.theme(); @@ -1179,16 +1123,13 @@ mod tests { #[test] fn a_banner_stays_until_it_is_dismissed() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); let state = &mut harness.state_mut().state; state.errors.report( i18n::keys::errors::ATTACHMENTS_LOAD_FAILED, &engine::error::AppError::from(engine::error::StorageError::Locked), ); - state - .status - .report(i18n::Message::new(i18n::keys::attachments::SAVED)); + state.status.report(i18n::Message::new(i18n::keys::attachments::SAVED)); settle(&mut harness); assert!(present(&harness, "error-banner")); assert!(present(&harness, "status-toast")); diff --git a/crates/ui/src/app/about_link_tests.rs b/crates/ui/src/app/about_link_tests.rs index 52a73f310..2a8714fa1 100644 --- a/crates/ui/src/app/about_link_tests.rs +++ b/crates/ui/src/app/about_link_tests.rs @@ -28,10 +28,7 @@ fn the_repository_opens_in_the_browser_from_the_about_card() { click(&mut harness, "about-about"); click(&mut harness, "about-repository"); - assert_eq!( - *opened.0.lock().unwrap(), - [PathBuf::from(METADATA.repository)] - ); + assert_eq!(*opened.0.lock().unwrap(), [PathBuf::from(METADATA.repository)]); assert!(METADATA.repository.starts_with("https://")); } diff --git a/crates/ui/src/app/area_switch_tests.rs b/crates/ui/src/app/area_switch_tests.rs index 5ee6ab415..1178aeb90 100644 --- a/crates/ui/src/app/area_switch_tests.rs +++ b/crates/ui/src/app/area_switch_tests.rs @@ -5,9 +5,7 @@ use egui_kittest::kittest::Queryable; use super::tests::{click, open_library}; fn switches(harness: &egui_kittest::Harness<'_, super::DevNotesApp>) -> usize { - harness - .query_all_by(|node| node.author_id() == Some("area-switch")) - .count() + harness.query_all_by(|node| node.author_id() == Some("area-switch")).count() } fn top(harness: &egui_kittest::Harness<'_, super::DevNotesApp>) -> f32 { @@ -44,17 +42,10 @@ fn each_area_is_reached_from_the_switch_of_its_rail() { } /// Where the three buttons are drawn, the area `area` on screen. -fn places( - harness: &mut egui_kittest::Harness<'_, super::DevNotesApp>, - area: &str, -) -> Vec { +fn places(harness: &mut egui_kittest::Harness<'_, super::DevNotesApp>, area: &str) -> Vec { click(harness, area); ["area-option-notes", "area-option-tools", "area-option-http"] - .map(|author_id| { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() - }) + .map(|author_id| harness.get_by(|node| node.author_id() == Some(author_id)).rect()) .to_vec() } @@ -81,11 +72,7 @@ fn halves( ids: [&str; 2], ) -> [egui::Rect; 2] { click(harness, area); - ids.map(|author_id| { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() - }) + ids.map(|author_id| harness.get_by(|node| node.author_id() == Some(author_id)).rect()) } #[test] @@ -93,22 +80,11 @@ fn new_request_has_the_shape_of_new_note() { let directory = tempfile::tempdir().unwrap(); let mut harness = open_library(directory.path()); - let note = halves( - &mut harness, - "area-option-notes", - ["new-note", "new-note-kind"], - ); - let request = halves( - &mut harness, - "area-option-http", - ["http-tab-new", "http-tab-new-kind"], - ); + let note = halves(&mut harness, "area-option-notes", ["new-note", "new-note-kind"]); + let request = halves(&mut harness, "area-option-http", ["http-tab-new", "http-tab-new-kind"]); for [main, more] in [note, request] { - assert!( - (main.right() - more.left()).abs() < 0.1, - "{main:?} {more:?}" - ); + assert!((main.right() - more.left()).abs() < 0.1, "{main:?} {more:?}"); assert!((main.height() - more.height()).abs() < 0.1); } assert!((note[0].height() - request[0].height()).abs() < 0.1); diff --git a/crates/ui/src/app/captures.rs b/crates/ui/src/app/captures.rs index 288a1413e..c163b92c2 100644 --- a/crates/ui/src/app/captures.rs +++ b/crates/ui/src/app/captures.rs @@ -41,17 +41,13 @@ fn settle(harness: &mut Harness<'_, DevNotesApp>) { } fn click(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); settle(harness); } fn type_into(harness: &mut Harness<'_, DevNotesApp>, author_id: &str, words: &str) { click(harness, author_id); - harness - .get_by(|node| node.author_id() == Some(author_id)) - .type_text(words); + harness.get_by(|node| node.author_id() == Some(author_id)).type_text(words); settle(harness); } @@ -83,14 +79,10 @@ fn shoot(harness: &mut Harness<'_, DevNotesApp>, name: &str, pointer_gone: bool) harness.event(egui::Event::PointerGone); } settle(harness); - let image = harness - .render() - .expect("a software adapter draws the window"); + let image = harness.render().expect("a software adapter draws the window"); if let Some(directory) = &directory { std::fs::create_dir_all(directory).unwrap(); - image - .save(Path::new(directory).join(format!("{name}-{theme}.png"))) - .unwrap(); + image.save(Path::new(directory).join(format!("{name}-{theme}.png"))).unwrap(); } // By its action, not its button: a click would close what the capture shows. let other = match harness.ctx.theme() { @@ -190,9 +182,8 @@ fn the_title_bar_and_the_banners_over_an_open_library() { capture(&mut harness, "file-menu"); click(&mut harness, "file-quit"); capture(&mut harness, "file-menu-quit-asks"); - harness.state_mut().state.dialog = std::sync::Arc::new(platform::dialog::Fixed( - profile.path().join("library.devnotes"), - )); + harness.state_mut().state.dialog = + std::sync::Arc::new(platform::dialog::Fixed(profile.path().join("library.devnotes"))); click(&mut harness, "file-option-exportAll"); settle(&mut harness); capture(&mut harness, "passphrase-prompt"); @@ -235,9 +226,7 @@ fn the_title_bar_and_the_banners_over_an_open_library() { i18n::keys::errors::ATTACHMENTS_LOAD_FAILED, &engine::error::AppError::from(engine::error::StorageError::Locked), ); - state - .status - .report(i18n::Message::new(i18n::keys::settings::COPIED)); + state.status.report(i18n::Message::new(i18n::keys::settings::COPIED)); settle(&mut harness); capture(&mut harness, "banners-http"); } @@ -277,31 +266,12 @@ fn http_area(profile: &Path) -> Harness<'static, DevNotesApp> { let backend = harness.state().backend(); let api = crate::http::tests::collection(backend, "API Paiements"); let auth = crate::http::tests::folder(backend, &api, "Auth"); - let methods = [ - ("Login", HttpMethod::Post), - ("Session", HttpMethod::Get), - ("Logout", HttpMethod::Delete), - ]; + let methods = [("Login", HttpMethod::Post), ("Session", HttpMethod::Get), ("Logout", HttpMethod::Delete)]; for (name, method) in methods { - crate::http::tests::request( - backend, - (&api, Some(&auth)), - name, - (RequestKind::Http, method), - ); + crate::http::tests::request(backend, (&api, Some(&auth)), name, (RequestKind::Http, method)); } - crate::http::tests::request( - backend, - (&api, None), - "Factures", - (RequestKind::Graphql, HttpMethod::Post), - ); - crate::http::tests::request( - backend, - (&api, None), - "Flux", - (RequestKind::Websocket, HttpMethod::Get), - ); + crate::http::tests::request(backend, (&api, None), "Factures", (RequestKind::Graphql, HttpMethod::Post)); + crate::http::tests::request(backend, (&api, None), "Flux", (RequestKind::Websocket, HttpMethod::Get)); // The tree is read when the area is first shown. click(&mut harness, "area-option-http"); harness @@ -322,19 +292,14 @@ fn the_http_request_editor() { let key = app.state.http.tabs().active_key().unwrap().to_owned(); app.state.http.tabs_mut().edit(&key, |draft| { use crate::state::http::tabs::DraftEdit; - draft.apply(DraftEdit::Url( - "{{base}}/sessions?user={{user}}&remember=true".to_owned(), - )); + draft.apply(DraftEdit::Url("{{base}}/sessions?user={{user}}&remember=true".to_owned())); let header = |key: &str, value: &str| engine::http::model::KeyValue { enabled: true, key: key.to_owned(), value: value.to_owned(), description: String::new(), }; - draft.apply(DraftEdit::Headers(vec![ - header("Accept", "application/json"), - header("X Trace", "on"), - ])); + draft.apply(DraftEdit::Headers(vec![header("Accept", "application/json"), header("X Trace", "on")])); }); settle(&mut harness); capture(&mut harness, "http-request-params"); @@ -348,19 +313,12 @@ fn the_http_request_editor() { app.state.http.tabs_mut().edit(&key, |draft| { use engine::http::environments::{FilledBy, Variable, VariableKind}; draft.apply(crate::state::http::tabs::DraftEdit::Variables(vec![ - Variable { - name: "user".to_owned(), - value: "ada".to_owned(), - ..Variable::default() - }, + Variable { name: "user".to_owned(), value: "ada".to_owned(), ..Variable::default() }, Variable { name: "token".to_owned(), value: "eyJ.a.b".to_owned(), kind: VariableKind::Secret, - filled_by: Some(FilledBy { - request_id: None, - name: "Login".to_owned(), - }), + filled_by: Some(FilledBy { request_id: None, name: "Login".to_owned() }), ..Variable::default() }, ])); @@ -377,11 +335,9 @@ fn the_http_request_editor() { click(&mut harness, "http-section-body"); let app = harness.state_mut(); app.state.http.tabs_mut().edit(&key, |draft| { - draft.apply(crate::state::http::tabs::DraftEdit::Body( - engine::http::model::RequestBody::Json { - text: "{\n \"login\": \"ada\",\n \"remember\": true\n}".to_owned(), - }, - )); + draft.apply(crate::state::http::tabs::DraftEdit::Body(engine::http::model::RequestBody::Json { + text: "{\n \"login\": \"ada\",\n \"remember\": true\n}".to_owned(), + })); }); settle(&mut harness); capture(&mut harness, "http-request-body"); @@ -391,21 +347,17 @@ fn the_http_request_editor() { harness .get_by(|node| { node.author_id() == Some("http-node-name") - && node - .label() - .is_some_and(|label| label.ends_with("Factures")) + && node.label().is_some_and(|label| label.ends_with("Factures")) }) .click(); settle(&mut harness); let app = harness.state_mut(); let key = app.state.http.tabs().active_key().unwrap().to_owned(); app.state.http.tabs_mut().edit(&key, |draft| { - draft.apply(crate::state::http::tabs::DraftEdit::Graphql( - engine::http::graphql::GraphqlDocument { - query: "query Facture($id: ID!) {\n facture(id: $id) {\n total\n".to_owned(), - ..Default::default() - }, - )); + draft.apply(crate::state::http::tabs::DraftEdit::Graphql(engine::http::graphql::GraphqlDocument { + query: "query Facture($id: ID!) {\n facture(id: $id) {\n total\n".to_owned(), + ..Default::default() + })); }); settle(&mut harness); capture(&mut harness, "http-request-graphql"); @@ -449,22 +401,12 @@ fn the_http_socket() { url: "wss://api.example.com/Flux".to_owned(), protocol: Some("chat".to_owned()), }, - SocketEvent::Sent { - text: "{\"subscribe\":\"prix\"}".to_owned(), - size: 21, - }, - SocketEvent::Received { - text: "{\"prix\":42}".to_owned(), - size: 10, - binary: false, - cut: false, - }, + SocketEvent::Sent { text: "{\"subscribe\":\"prix\"}".to_owned(), size: 21 }, + SocketEvent::Received { text: "{\"prix\":42}".to_owned(), size: 10, binary: false, cut: false }, ] { - app.state.http.receive_socket(WebsocketEvent { - id: format!("{key}#1"), - at, - event, - }); + app.state + .http + .receive_socket(WebsocketEvent { id: format!("{key}#1"), at, event }); } settle(&mut harness); capture(&mut harness, "http-socket"); @@ -477,9 +419,7 @@ fn the_http_dialogs() { harness .get_by(|node| { node.author_id() == Some("http-node-menu") - && node - .label() - .is_some_and(|label| label.ends_with("API Paiements")) + && node.label().is_some_and(|label| label.ends_with("API Paiements")) }) .click(); settle(&mut harness); @@ -533,12 +473,7 @@ fn the_http_runner() { let backend = harness.state().backend(); let local = crate::http::tests::collection(backend, "Local"); for name in ["Login", "Commandes"] { - crate::http::tests::request( - backend, - (&local, None), - name, - (RequestKind::Http, HttpMethod::Get), - ); + crate::http::tests::request(backend, (&local, None), name, (RequestKind::Http, HttpMethod::Get)); } click(&mut harness, "area-option-http"); harness @@ -577,17 +512,9 @@ fn the_http_runner() { response: None, }; let steps = [ - RunStep::Ended { - result: Box::new(result("Login", 200, true)), - }, - RunStep::Ended { - result: Box::new(result("Commandes", 404, false)), - }, - RunStep::Finished { - cancelled: false, - millis: 1_200, - capped: false, - }, + RunStep::Ended { result: Box::new(result("Login", 200, true)) }, + RunStep::Ended { result: Box::new(result("Commandes", 404, false)) }, + RunStep::Finished { cancelled: false, millis: 1_200, capped: false }, ]; for step in steps { let id = "1".to_owned(); @@ -609,12 +536,8 @@ fn the_http_response() { settle(&mut harness); let backend = harness.state().backend(); let local = crate::http::tests::collection(backend, "Local"); - let ping = crate::http::tests::request( - backend, - (&local, None), - "Ping", - (RequestKind::Http, HttpMethod::Get), - ); + let ping = + crate::http::tests::request(backend, (&local, None), "Ping", (RequestKind::Http, HttpMethod::Get)); click(&mut harness, "area-option-http"); harness .get_by(|node| { @@ -625,9 +548,7 @@ fn the_http_response() { settle(&mut harness); let app = harness.state_mut(); app.state.http.tabs_mut().edit(&ping.id, |draft| { - draft.apply(crate::state::http::tabs::DraftEdit::Url(format!( - "http://127.0.0.1:{port}/json" - ))); + draft.apply(crate::state::http::tabs::DraftEdit::Url(format!("http://127.0.0.1:{port}/json"))); }); settle(&mut harness); click(&mut harness, "http-send"); @@ -701,9 +622,7 @@ fn the_http_area() { harness .get_by(|node| { node.author_id() == Some("http-node-menu") - && node - .label() - .is_some_and(|label| label.ends_with("API Paiements")) + && node.label().is_some_and(|label| label.ends_with("API Paiements")) }) .click(); settle(&mut harness); @@ -731,9 +650,7 @@ fn the_http_area() { harness .get_by(|node| { node.author_id() == Some("http-tab-close") - && node - .label() - .is_some_and(|label| label.ends_with("Flux live")) + && node.label().is_some_and(|label| label.ends_with("Flux live")) }) .click(); settle(&mut harness); @@ -785,10 +702,7 @@ fn the_tools() { let open = crate::action::Action::Tools(crate::tools::Action::Open(tool.id)); app.state.apply(open, &ctx, &app.backend); settle(&mut harness); - if harness - .query_by(|node| node.author_id() == Some("tool-sample")) - .is_some() - { + if harness.query_by(|node| node.author_id() == Some("tool-sample")).is_some() { click(&mut harness, "tool-sample"); } // Past the debounce: the bench's clock moves as frames do. @@ -817,8 +731,7 @@ fn the_canvas_of_an_open_library() { harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("psql prod") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("psql prod") }) .hover(); settle(&mut harness); @@ -853,8 +766,7 @@ fn the_canvas_of_an_open_library() { harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("psql prod") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("psql prod") }) .click(); settle(&mut harness); @@ -868,10 +780,7 @@ fn the_canvas_of_an_open_library() { click(&mut harness, "editor-close"); drawing_editor(&mut harness); - harness.key_press_modifiers( - egui::Modifiers::COMMAND | egui::Modifiers::ALT, - egui::Key::P, - ); + harness.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::P); settle(&mut harness); capture(&mut harness, "palette-recent"); harness @@ -925,8 +834,7 @@ fn the_editor_beside_the_cards() { settle(&mut harness); harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("psql prod") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("psql prod") }) .click(); settle(&mut harness); @@ -1000,20 +908,10 @@ fn the_board_of_the_samples() { .expect("a filed card") .rect() .center(); - let held = drag_to( - &mut harness, - card, - egui::PointerButton::Primary, - egui::vec2(520.0, 40.0), - ); + let held = drag_to(&mut harness, card, egui::PointerButton::Primary, egui::vec2(520.0, 40.0)); holding(&mut harness, "board-dragging"); release(&mut harness, held, egui::PointerButton::Primary); - let band = drag_to( - &mut harness, - card, - egui::PointerButton::Secondary, - egui::vec2(300.0, 260.0), - ); + let band = drag_to(&mut harness, card, egui::PointerButton::Secondary, egui::vec2(300.0, 260.0)); holding(&mut harness, "board-band"); release(&mut harness, band, egui::PointerButton::Secondary); } @@ -1025,12 +923,8 @@ fn drag_to( button: egui::PointerButton, by: egui::Vec2, ) -> egui::Pos2 { - let press = |pos, pressed| egui::Event::PointerButton { - pos, - button, - pressed, - modifiers: egui::Modifiers::NONE, - }; + let press = + |pos, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }; harness.event(egui::Event::PointerMoved(from)); harness.step(); harness.event(press(from, true)); @@ -1054,14 +948,10 @@ fn release(harness: &mut Harness<'_, DevNotesApp>, at: egui::Pos2, button: egui: /// The window as it stands, the pointer still held: a gesture under way, in one theme. fn holding(harness: &mut Harness<'_, DevNotesApp>, name: &str) { - let image = harness - .render() - .expect("a software adapter draws the window"); + let image = harness.render().expect("a software adapter draws the window"); if let Some(directory) = std::env::var_os("DEVNOTES_CAPTURES") { std::fs::create_dir_all(&directory).unwrap(); - image - .save(Path::new(&directory).join(format!("{name}.png"))) - .unwrap(); + image.save(Path::new(&directory).join(format!("{name}.png"))).unwrap(); } } @@ -1074,9 +964,7 @@ fn drawing_editor(harness: &mut Harness<'_, DevNotesApp>) { .click(); settle(harness); capture(harness, "editor-drawing"); - let stage = harness - .get_by(|node| node.author_id() == Some("drawing-stage")) - .rect(); + let stage = harness.get_by(|node| node.author_id() == Some("drawing-stage")).rect(); let shape = stage.min + egui::vec2(170.0, 90.0); harness.event(egui::Event::PointerMoved(shape)); harness.run_steps(1); @@ -1125,27 +1013,9 @@ fn kinds(backend: &crate::backend::Backend) -> Vec { Vec::new(), vec![("milk", true), ("bread", false), ("eggs", false)], ), - ( - "Budget", - NoteKind::Calc, - "loyer = 800 €\ncharges = 120,5 €\ntotal", - Vec::new(), - Vec::new(), - ), - ( - "Sketch", - NoteKind::Drawing, - scene.as_str(), - Vec::new(), - Vec::new(), - ), - ( - "", - NoteKind::Snippet, - "curl -s https://example.test/health", - Vec::new(), - Vec::new(), - ), + ("Budget", NoteKind::Calc, "loyer = 800 €\ncharges = 120,5 €\ntotal", Vec::new(), Vec::new()), + ("Sketch", NoteKind::Drawing, scene.as_str(), Vec::new(), Vec::new()), + ("", NoteKind::Snippet, "curl -s https://example.test/health", Vec::new(), Vec::new()), ]; let mut ids = Vec::new(); for (title, kind, content, tags, items) in shapes { @@ -1159,10 +1029,7 @@ fn kinds(backend: &crate::backend::Backend) -> Vec { items: Some( items .into_iter() - .map(|(text, done)| ChecklistItem { - text: text.to_string(), - done, - }) + .map(|(text, done)| ChecklistItem { text: text.to_string(), done }) .collect(), ), pinned: Some(title == "psql prod"), @@ -1206,31 +1073,22 @@ fn the_editor_header_under_the_pointer() { let _ = kinds(&harness.state().backend); harness.state_mut().state.revision.bump(); settle(&mut harness); - harness - .ctx - .all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + harness.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("psql prod") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("psql prod") }) .click(); settle(&mut harness); for icon in ["editor-fullscreen", "editor-close"] { - harness - .get_by(|node| node.author_id() == Some(icon)) - .hover(); + harness.get_by(|node| node.author_id() == Some(icon)).hover(); for _ in 0..10 { harness.step(); } - let image = harness - .render() - .expect("a software adapter draws the window"); + let image = harness.render().expect("a software adapter draws the window"); if let Some(directory) = std::env::var_os("DEVNOTES_CAPTURES") { std::fs::create_dir_all(&directory).unwrap(); - image - .save(Path::new(&directory).join(format!("hover-{icon}.png"))) - .unwrap(); + image.save(Path::new(&directory).join(format!("hover-{icon}.png"))).unwrap(); } } } @@ -1247,9 +1105,7 @@ fn the_editor_header_of_a_full_note_when_narrow() { click(&mut harness, "vault-submit"); settle(&mut harness); let backend = &harness.state().backend; - let id = crate::testing::note(backend, "Rotation of the staging certificate") - .id - .clone(); + let id = crate::testing::note(backend, "Rotation of the staging certificate").id.clone(); let note = id.clone(); engine::db::run_here(backend.engine(), move |engine| { let space = engine::notes::get_note(engine, ¬e)?.space_id.clone(); @@ -1270,13 +1126,7 @@ fn the_editor_header_of_a_full_note_when_narrow() { let at = chrono::DateTime::parse_from_rfc3339("2026-12-24T22:00:00Z") .unwrap() .with_timezone(&chrono::Utc); - let tags = [ - "infrastructure", - "certificates", - "staging", - "openssl", - "yearly-rotation-runbook", - ]; + let tags = ["infrastructure", "certificates", "staging", "openssl", "yearly-rotation-runbook"]; engine::notes::update_note( engine, ¬e, @@ -1289,9 +1139,7 @@ fn the_editor_header_of_a_full_note_when_narrow() { ) }) .unwrap(); - let file = profile - .path() - .join("the-whole-chain-of-the-staging-certificate-2026.pem"); + let file = profile.path().join("the-whole-chain-of-the-staging-certificate-2026.pem"); std::fs::write(&file, b"-----BEGIN CERTIFICATE-----").unwrap(); harness.state_mut().state.revision.bump(); harness.state_mut().state.editor.open(id); @@ -1323,9 +1171,7 @@ fn the_slides_of_a_presentation() { let body = format!( "## A short slide\n\nOne line of text.\n\n## A list\n\n- prepare the backup\n- switch the DNS\n- watch the logs\n\n## A short code\n\n```rust\nlet x = 1;\nlet y = 2;\n```\n\n## A long code\n\n```rust\n{long}\n```\n" ); - let id = crate::testing::note(&harness.state().backend, "Switch over") - .id - .clone(); + let id = crate::testing::note(&harness.state().backend, "Switch over").id.clone(); let patch = engine::notes::model::NotePatch { kind: Some(engine::notes::kind::NoteKind::Note), content: Some(body), @@ -1333,10 +1179,7 @@ fn the_slides_of_a_presentation() { }; let engine = harness.state().backend.engine().clone(); let note = id.clone(); - engine::db::run_here(&engine, move |engine| { - engine::notes::update_note(engine, ¬e, &patch) - }) - .unwrap(); + engine::db::run_here(&engine, move |engine| engine::notes::update_note(engine, ¬e, &patch)).unwrap(); harness.state_mut().state.revision.bump(); harness.state_mut().state.editor.open(id); settle(&mut harness); @@ -1355,19 +1198,16 @@ fn the_slides_of_a_presentation() { #[test] fn the_format_button_and_its_settings() { use engine::notes::language::Language; - for (name, language, code) in [ - ("ts", Language::Ts, "const a = {b:1}"), - ("sql", Language::Sql, "SELECT 1;"), - ] { + for (name, language, code) in + [("ts", Language::Ts, "const a = {b:1}"), ("sql", Language::Sql, "SELECT 1;")] + { let profile = tempfile::tempdir().unwrap(); let mut harness = launch_at(profile.path(), egui::vec2(1440.0, 900.0)); type_into(&mut harness, "vault-passphrase", PASSPHRASE); type_into(&mut harness, "vault-confirmation", PASSPHRASE); click(&mut harness, "vault-submit"); settle(&mut harness); - let id = crate::testing::note(&harness.state().backend, "Invoices") - .id - .clone(); + let id = crate::testing::note(&harness.state().backend, "Invoices").id.clone(); let patch = engine::notes::model::NotePatch { content: Some(code.to_owned()), language: Some(language), @@ -1375,10 +1215,8 @@ fn the_format_button_and_its_settings() { }; let engine = harness.state().backend.engine().clone(); let note = id.clone(); - engine::db::run_here(&engine, move |engine| { - engine::notes::update_note(engine, ¬e, &patch) - }) - .unwrap(); + engine::db::run_here(&engine, move |engine| engine::notes::update_note(engine, ¬e, &patch)) + .unwrap(); harness.state_mut().state.revision.bump(); harness.state_mut().state.editor.open(id); settle(&mut harness); @@ -1405,9 +1243,7 @@ fn with_a_drawing(profile: &std::path::Path, scene: &str) -> Harness<'static, De type_into(&mut harness, "vault-confirmation", PASSPHRASE); click(&mut harness, "vault-submit"); settle(&mut harness); - let id = crate::testing::note(&harness.state().backend, "Architecture") - .id - .clone(); + let id = crate::testing::note(&harness.state().backend, "Architecture").id.clone(); let patch = engine::notes::model::NotePatch { kind: Some(engine::notes::kind::NoteKind::Drawing), content: Some(scene.to_owned()), @@ -1415,10 +1251,7 @@ fn with_a_drawing(profile: &std::path::Path, scene: &str) -> Harness<'static, De }; let engine = harness.state().backend.engine().clone(); let note = id.clone(); - engine::db::run_here(&engine, move |engine| { - engine::notes::update_note(engine, ¬e, &patch) - }) - .unwrap(); + engine::db::run_here(&engine, move |engine| engine::notes::update_note(engine, ¬e, &patch)).unwrap(); harness.state_mut().state.revision.bump(); harness.state_mut().state.editor.open(id); settle(&mut harness); @@ -1443,9 +1276,7 @@ fn an_arrow_near_the_points_of_a_shape() { ]}}"#; let mut harness = with_a_drawing(profile.path(), scene); click(&mut harness, "drawing-tool-arrow"); - let stage = harness - .get_by(|node| node.author_id() == Some("drawing-stage")) - .rect(); + let stage = harness.get_by(|node| node.author_id() == Some("drawing-stage")).rect(); harness.drag_at(stage.min + egui::vec2(192.0, 165.0)); harness.run_steps(2); harness.hover_at(stage.min + egui::vec2(332.0, 246.0)); @@ -1469,15 +1300,9 @@ fn the_http_request_in_a_narrow_window() { let key = app.state.http.tabs().active_key().unwrap().to_owned(); app.state.http.tabs_mut().edit(&key, |draft| { use crate::state::http::tabs::DraftEdit; - draft.apply(DraftEdit::Url( - "{{base}}/sessions?user={{user}}&remember=true".to_owned(), - )); + draft.apply(DraftEdit::Url("{{base}}/sessions?user={{user}}&remember=true".to_owned())); }); - for size in [ - egui::vec2(640.0, 480.0), - egui::vec2(720.0, 480.0), - egui::vec2(800.0, 600.0), - ] { + for size in [egui::vec2(640.0, 480.0), egui::vec2(720.0, 480.0), egui::vec2(800.0, 600.0)] { harness.set_size(size); settle(&mut harness); capture(&mut harness, &format!("http-request-{}", size.x)); @@ -1509,10 +1334,7 @@ fn a_selection_and_a_report_at_three_widths() { } harness.set_size(egui::vec2(640.0, 681.0)); settle(&mut harness); - if harness - .query_by(|node| node.author_id() == Some("selection-more")) - .is_some() - { + if harness.query_by(|node| node.author_id() == Some("selection-more")).is_some() { click(&mut harness, "selection-more"); settle(&mut harness); capture(&mut harness, "selection-more-640"); @@ -1549,10 +1371,7 @@ fn the_tag_manager_with_two_hundred_tags() { tags: Some(tags.to_vec()), ..engine::notes::model::NotePatch::default() }; - engine::db::run_here(&engine, move |engine| { - engine::notes::update_note(engine, &id, &patch) - }) - .unwrap(); + engine::db::run_here(&engine, move |engine| engine::notes::update_note(engine, &id, &patch)).unwrap(); } harness.state_mut().state.revision.bump(); settle(&mut harness); @@ -1574,10 +1393,7 @@ fn the_folders_four_levels_deep() { let backend = &harness.state().backend; engine::db::run_here(backend.engine(), |engine| { let folders = engine::folders::list_folders(engine, None)?; - let snippets = folders - .iter() - .find(|folder| folder.name == "Snippets") - .unwrap(); + let snippets = folders.iter().find(|folder| folder.name == "Snippets").unwrap(); let mut parent = snippets.id.clone(); for name in ["Requêtes SQL", "Exploitation", "Lecture seule", "Rapports"] { let draft = FolderDraft { @@ -1615,8 +1431,7 @@ fn the_dropdowns_at_their_width() { click(&mut harness, "sort-trigger"); harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("psql prod") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("psql prod") }) .click(); settle(&mut harness); @@ -1678,14 +1493,11 @@ fn a_long_note_with_code_scrolled_in_the_panel() { settle(&mut harness); harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some("Requêtes du lundi") + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("Requêtes du lundi") }) .click(); settle(&mut harness); - let body = harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .rect(); + let body = harness.get_by(|node| node.author_id() == Some("editor-rich")).rect(); harness.event(egui::Event::PointerMoved(body.center())); for _ in 0..6 { harness.event(egui::Event::MouseWheel { @@ -1734,9 +1546,7 @@ fn a_variable_pointed_at() { let key = app.state.http.tabs().active_key().unwrap().to_owned(); app.state.http.tabs_mut().edit(&key, |draft| { use crate::state::http::tabs::DraftEdit; - draft.apply(DraftEdit::Url( - "{{base}}/sessions/{{token}}?user={{user}}".to_owned(), - )); + draft.apply(DraftEdit::Url("{{base}}/sessions/{{token}}?user={{user}}".to_owned())); }); settle(&mut harness); for (at, name) in ["base", "token", "user"].into_iter().enumerate() { @@ -1749,9 +1559,7 @@ fn a_variable_pointed_at() { for _ in 0..60 { harness.step(); } - let image = harness - .render() - .expect("a software adapter draws the window"); + let image = harness.render().expect("a software adapter draws the window"); if let Some(directory) = std::env::var_os("DEVNOTES_CAPTURES") { std::fs::create_dir_all(&directory).unwrap(); let file = format!("variable-{name}.png"); @@ -1799,9 +1607,7 @@ fn an_http_tab_dragged_along_the_strip() { }); harness.step(); for step in 1..=10_u8 { - harness.event(egui::Event::PointerMoved( - from + (to - from) * (f32::from(step) / 10.0), - )); + harness.event(egui::Event::PointerMoved(from + (to - from) * (f32::from(step) / 10.0))); harness.step(); } capture_holding(&mut harness, "http-tab-dragging"); @@ -1835,9 +1641,7 @@ fn a_folder_dropped_onto_another_space() { type_into(&mut harness, "vault-confirmation", PASSPHRASE); click(&mut harness, "vault-submit"); settle(&mut harness); - let draft = engine::spaces::model::SpaceDraft { - name: "Archives".into(), - }; + let draft = engine::spaces::model::SpaceDraft { name: "Archives".into() }; engine::db::run_here(harness.state().backend().engine(), move |engine| { engine::spaces::create_space(engine, &draft) }) @@ -1846,9 +1650,7 @@ fn a_folder_dropped_onto_another_space() { settle(&mut harness); let at = |harness: &Harness<'_, DevNotesApp>, author_id: &str, name: &str| { harness - .get_by(|node| { - node.author_id() == Some(author_id) && node.label().as_deref() == Some(name) - }) + .get_by(|node| node.author_id() == Some(author_id) && node.label().as_deref() == Some(name)) .rect() .center() }; @@ -1885,24 +1687,15 @@ fn a_drawing_in_a_note() { click(&mut harness, "vault-submit"); settle(&mut harness); let id = |harness: &Harness<'_, DevNotesApp>, title| { - crate::testing::note(&harness.state().backend, title) - .id - .clone() + crate::testing::note(&harness.state().backend, title).id.clone() }; let scene = id(&harness, "Architecture"); let note = id(&harness, "Bienvenue dans DevNotes"); let rewrite = |harness: &mut Harness<'_, DevNotesApp>, id: &str, kind, content: String| { - let patch = NotePatch { - kind: Some(kind), - content: Some(content), - ..NotePatch::default() - }; + let patch = NotePatch { kind: Some(kind), content: Some(content), ..NotePatch::default() }; let engine = harness.state().backend.engine().clone(); let id = id.to_owned(); - engine::db::run_here(&engine, move |engine| { - engine::notes::update_note(engine, &id, &patch) - }) - .unwrap(); + engine::db::run_here(&engine, move |engine| engine::notes::update_note(engine, &id, &patch)).unwrap(); harness.state_mut().state.revision.bump(); }; let shapes = r#"{"version":1,"scene":{"objects":[ @@ -1938,20 +1731,12 @@ fn a_note_moved_among_many_folders() { click(&mut harness, "vault-submit"); settle(&mut harness); let engine = harness.state().backend.engine().clone(); - let space = crate::testing::note(&harness.state().backend, "Architecture") - .space_id - .clone(); + let space = crate::testing::note(&harness.state().backend, "Architecture").space_id.clone(); let make = |name: String, parent: Option| { - let draft = FolderDraft { - space_id: space.clone(), - parent_id: parent, - name, - }; - engine::db::run_here(&engine, move |engine| { - engine::folders::create_folder(engine, &draft) - }) - .unwrap() - .id + let draft = FolderDraft { space_id: space.clone(), parent_id: parent, name }; + engine::db::run_here(&engine, move |engine| engine::folders::create_folder(engine, &draft)) + .unwrap() + .id }; for project in 1..=14 { let name = format!("Projet {project:02} — migration de la base clients"); @@ -1970,10 +1755,7 @@ fn a_note_moved_among_many_folders() { settle(&mut harness); click(&mut harness, "note-card-menu"); capture(&mut harness, "note-menu"); - if harness - .query_by(|node| node.author_id() == Some("note-card-move")) - .is_some() - { + if harness.query_by(|node| node.author_id() == Some("note-card-move")).is_some() { click(&mut harness, "note-card-move"); capture(&mut harness, "note-move"); } @@ -1988,15 +1770,12 @@ fn reports_in_the_corner() { type_into(&mut harness, "vault-confirmation", PASSPHRASE); click(&mut harness, "vault-submit"); settle(&mut harness); - let id = crate::testing::note(&harness.state().backend, "Architecture") - .id - .clone(); + let id = crate::testing::note(&harness.state().backend, "Architecture").id.clone(); harness.state_mut().state.revision.bump(); harness.state_mut().state.editor.open(id); settle(&mut harness); let status = &mut harness.state_mut().state.status; - status - .report(i18n::Message::new(i18n::keys::notes::COPIED_NOTE).with("title", "Connexion psql")); + status.report(i18n::Message::new(i18n::keys::notes::COPIED_NOTE).with("title", "Connexion psql")); let path = r"C:\Utilisateurs\moi\Documents\captures\schéma-de-la-base.pdf"; status.report(i18n::Message::new(i18n::keys::attachments::SAVED).with("path", path)); status.report( @@ -2024,11 +1803,7 @@ fn an_empty_folder_opened() { let backend = &harness.state().backend; engine::db::run_here(backend.engine(), |engine| { let space = engine::spaces::list_spaces(engine)?.remove(0); - let draft = FolderDraft { - space_id: space.id, - name: "Brouillons".to_owned(), - parent_id: None, - }; + let draft = FolderDraft { space_id: space.id, name: "Brouillons".to_owned(), parent_id: None }; engine::folders::create_folder(engine, &draft) }) .unwrap(); @@ -2036,8 +1811,7 @@ fn an_empty_folder_opened() { settle(&mut harness); harness .get_by(|node| { - node.author_id() == Some("folder-option") - && node.label().as_deref() == Some("Brouillons") + node.author_id() == Some("folder-option") && node.label().as_deref() == Some("Brouillons") }) .click(); settle(&mut harness); @@ -2056,13 +1830,8 @@ fn a_wrapped_list_selected_whole() { settle(&mut harness); let backend = &harness.state().backend; let space = crate::testing::note(backend, "seed").space_id.clone(); - let long = - "Une tâche assez longue pour tenir sur plusieurs lignes de la Note ouverte. ".repeat(3); - let content = format!( - "- {}\n- Relire la procédure\n- {}", - long.trim_end(), - long.trim_end() - ); + let long = "Une tâche assez longue pour tenir sur plusieurs lignes de la Note ouverte. ".repeat(3); + let content = format!("- {}\n- Relire la procédure\n- {}", long.trim_end(), long.trim_end()); engine::db::run_here(backend.engine(), move |engine| { let draft = engine::notes::model::NoteDraft { kind: NoteKind::Note, @@ -2086,9 +1855,7 @@ fn a_wrapped_list_selected_whole() { harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); settle(&mut harness); capture(&mut harness, "note-list-selected"); - harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .click_secondary(); + harness.get_by(|node| node.author_id() == Some("editor-rich")).click_secondary(); settle(&mut harness); capture(&mut harness, "note-menu"); } @@ -2130,8 +1897,7 @@ fn deleting_a_space_and_a_folder() { let options = |harness: &mut Harness<'static, DevNotesApp>, author_id: &str, name: &str| { harness .get_by(|node| { - node.author_id() == Some(author_id) - && node.label().is_some_and(|label| label.ends_with(name)) + node.author_id() == Some(author_id) && node.label().is_some_and(|label| label.ends_with(name)) }) .click(); settle(harness); diff --git a/crates/ui/src/app/docs_tests.rs b/crates/ui/src/app/docs_tests.rs index 13aa183f2..2409097b8 100644 --- a/crates/ui/src/app/docs_tests.rs +++ b/crates/ui/src/app/docs_tests.rs @@ -28,17 +28,13 @@ fn title(harness: &Harness<'_, DevNotesApp>) -> String { fn search(harness: &mut Harness<'_, DevNotesApp>, words: &str) { click(harness, "docs-search"); - harness - .get_by(|node| node.author_id() == Some("docs-search")) - .type_text(words); + harness.get_by(|node| node.author_id() == Some("docs-search")).type_text(words); settle(harness); } /// Scrolled to, then clicked: what is out of sight is under the window's edge, or past it. fn reach(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .scroll_to_me(); + harness.get_by(|node| node.author_id() == Some(author_id)).scroll_to_me(); settle(harness); click(harness, author_id); } @@ -149,10 +145,7 @@ fn an_address_elsewhere_opens_the_browser() { assert_eq!( *opened.0.lock().unwrap(), - [ - PathBuf::from("https://devnotes.fr/en/docs"), - PathBuf::from("https://devnotes.fr/en/download"), - ] + [PathBuf::from("https://devnotes.fr/en/docs"), PathBuf::from("https://devnotes.fr/en/download"),] ); } diff --git a/crates/ui/src/app/gate_update_tests.rs b/crates/ui/src/app/gate_update_tests.rs index 33f84884c..69d8ce8c1 100644 --- a/crates/ui/src/app/gate_update_tests.rs +++ b/crates/ui/src/app/gate_update_tests.rs @@ -44,10 +44,7 @@ fn an_update_found_at_the_gate_is_said_on_the_card_and_the_field_keeps_the_keys( let mut harness = at_the_gate(directory.path(), FakeUpdater::offering("0.26.0")); assert!(!harness.state().state().gate.is_open()); - assert!( - !present(&harness, "update-prompt"), - "no dialog over the field" - ); + assert!(!present(&harness, "update-prompt"), "no dialog over the field"); assert!(present(&harness, "gate-update")); assert_eq!(focused(&harness).as_deref(), Some("vault-passphrase")); @@ -57,10 +54,7 @@ fn an_update_found_at_the_gate_is_said_on_the_card_and_the_field_keeps_the_keys( harness.key_press(egui::Key::Enter); settle(&mut harness); - assert!( - harness.state().state().gate.is_open(), - "Enter still unlocks" - ); + assert!(harness.state().state().gate.is_open(), "Enter still unlocks"); assert!(!present(&harness, "update-prompt"), "nor once unlocked"); click(&mut harness, "about-open"); let entry = harness.get_by(|node| node.author_id() == Some("about-check-updates")); @@ -77,10 +71,7 @@ fn install_now_from_the_gate_downloads_the_update() { click(&mut harness, "gate-update-install"); settle(&mut harness); - assert!( - harness.state().state().quitting, - "downloaded, it leaves for the installer" - ); + assert!(harness.state().state().quitting, "downloaded, it leaves for the installer"); eframe::App::on_exit(harness.state_mut()); assert!(*fake.relaunched.lock().unwrap()); } diff --git a/crates/ui/src/app/global_key_tests.rs b/crates/ui/src/app/global_key_tests.rs index 314dabea2..d053e4b06 100644 --- a/crates/ui/src/app/global_key_tests.rs +++ b/crates/ui/src/app/global_key_tests.rs @@ -98,9 +98,8 @@ fn an_empty_clipboard_captures_nothing() { #[test] fn before_a_library_is_open_nothing_is_captured() { let directory = tempfile::tempdir().unwrap(); - let mut harness = Harness::new_eframe(|cc| { - DevNotesApp::new(cc, super::tests::startup(directory.path())).unwrap() - }); + let mut harness = + Harness::new_eframe(|cc| DevNotesApp::new(cc, super::tests::startup(directory.path())).unwrap()); capture(&mut harness, "A sentence."); diff --git a/crates/ui/src/app/library_panel_tests.rs b/crates/ui/src/app/library_panel_tests.rs index 40082d887..4b5217e4b 100644 --- a/crates/ui/src/app/library_panel_tests.rs +++ b/crates/ui/src/app/library_panel_tests.rs @@ -74,11 +74,7 @@ fn a_library_is_renamed_where_it_is_listed() { assert!(!present(&harness, "library-rename")); let libraries = harness.state().state().libraries.libraries(); - assert!( - libraries[0].name.contains("Maison"), - "{}", - libraries[0].name - ); + assert!(libraries[0].name.contains("Maison"), "{}", libraries[0].name); } #[test] @@ -136,8 +132,5 @@ fn a_switch_asks_about_a_request_left_unsaved_and_cancelling_stays() { click(&mut harness, "http-leave-discard"); settle(&mut harness); assert!(present(&harness, "vault-passphrase")); - assert!( - !present(&harness, "vault-confirmation"), - "it has its phrase" - ); + assert!(!present(&harness, "vault-confirmation"), "it has its phrase"); } diff --git a/crates/ui/src/app/modal_tests.rs b/crates/ui/src/app/modal_tests.rs index 2154f7828..cec84c68d 100644 --- a/crates/ui/src/app/modal_tests.rs +++ b/crates/ui/src/app/modal_tests.rs @@ -14,12 +14,7 @@ fn an_unsaved_request(directory: &std::path::Path) -> Harness<'static, DevNotesA let mut harness = open_library(directory); let backend = harness.state().backend(); let api = crate::http::tests::collection(backend, "API"); - crate::http::tests::request( - backend, - (&api, None), - "Login", - (RequestKind::Http, HttpMethod::Get), - ); + crate::http::tests::request(backend, (&api, None), "Login", (RequestKind::Http, HttpMethod::Get)); click(&mut harness, "area-option-http"); harness .get_by(|node| { @@ -73,9 +68,7 @@ fn escape_closes_the_trash_and_gives_the_focus_back_to_its_button() { let directory = tempfile::tempdir().unwrap(); let mut harness = open_library(directory.path()); // From the keyboard: the one for whom the focus coming back matters. - harness - .get_by(|node| node.author_id() == Some("trash-open")) - .focus(); + harness.get_by(|node| node.author_id() == Some("trash-open")).focus(); settle(&mut harness); harness.key_press(Key::Enter); settle(&mut harness); @@ -94,9 +87,7 @@ fn escape_closes_the_trash_and_gives_the_focus_back_to_its_button() { fn a_greyed_file_entry_says_what_it_waits_for() { let directory = tempfile::tempdir().unwrap(); let mut harness = open_library(directory.path()); - harness - .ctx - .all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + harness.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); click(&mut harness, "file-menu"); harness .get_by(|node| node.author_id() == Some("file-option-exportSelection")) @@ -105,11 +96,7 @@ fn a_greyed_file_entry_says_what_it_waits_for() { harness.step(); } - let waiting = i18n::translate( - harness.state().state.language, - i18n::keys::file::NEEDS_SELECTION, - &[], - ); + let waiting = i18n::translate(harness.state().state.language, i18n::keys::file::NEEDS_SELECTION, &[]); assert!( harness .query_by(|node| { @@ -154,9 +141,5 @@ fn ctrl_b_in_a_note_writes_bold_and_leaves_the_rail() { harness.key_press_modifiers(Modifiers::COMMAND, Key::B); settle(&mut harness); - assert_eq!( - harness.state().state.settings.rail_shown, - rail, - "the rail moved" - ); + assert_eq!(harness.state().state.settings.rail_shown, rail, "the rail moved"); } diff --git a/crates/ui/src/app/palette_copy_tests.rs b/crates/ui/src/app/palette_copy_tests.rs index 971b74fba..a82239cac 100644 --- a/crates/ui/src/app/palette_copy_tests.rs +++ b/crates/ui/src/app/palette_copy_tests.rs @@ -18,10 +18,7 @@ impl platform::notify::Notifier for Toasts { } } -fn copied_from_the_palette( - harness: &mut Harness<'_, DevNotesApp>, - from_elsewhere: bool, -) -> Arc { +fn copied_from_the_palette(harness: &mut Harness<'_, DevNotesApp>, from_elsewhere: bool) -> Arc { let toasts = Arc::new(Toasts::default()); let ctx = harness.ctx.clone(); let app = harness.state_mut(); @@ -29,8 +26,7 @@ fn copied_from_the_palette( app.state.palette.open(&app.backend, from_elsewhere); app.state.palette.copying(); let said = i18n::Message::new(i18n::keys::settings::COPIED); - app.state - .copy_out(&ctx, &app.backend, "echo copied".to_owned(), said); + app.state.copy_out(&ctx, &app.backend, "echo copied".to_owned(), said); harness.step(); toasts } diff --git a/crates/ui/src/app/perf.rs b/crates/ui/src/app/perf.rs index b93ae23cc..015a6bfb5 100644 --- a/crates/ui/src/app/perf.rs +++ b/crates/ui/src/app/perf.rs @@ -100,10 +100,7 @@ fn resident() -> f64 { .args(["-NoProfile", "-Command", &script]) .output() .unwrap(); - let bytes: f64 = String::from_utf8_lossy(&output.stdout) - .trim() - .parse() - .unwrap(); + let bytes: f64 = String::from_utf8_lossy(&output.stdout).trim().parse().unwrap(); bytes / 1_048_576.0 } @@ -155,10 +152,7 @@ fn frame(window: &mut Window) -> Duration { } fn has(window: &Window, author_id: &str) -> bool { - window - .query_all_by(|node| node.author_id() == Some(author_id)) - .next() - .is_some() + window.query_all_by(|node| node.author_id() == Some(author_id)).next().is_some() } /// Frames until `holds`, however long the core takes: what it took since `started`. @@ -171,9 +165,7 @@ fn until(window: &mut Window, started: Instant, holds: impl Fn(&Window) -> bool) } fn click(window: &mut Window, author_id: &str) { - window - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + window.get_by(|node| node.author_id() == Some(author_id)).click(); } fn act(window: &mut Window, action: Action) { @@ -192,20 +184,9 @@ fn unlock(window: &mut Window) { settle(window); let started = Instant::now(); click(window, "vault-submit"); - once( - "unlock → past the gate", - until(window, started, |w| has(w, "area-notes")), - ); - once( - "unlock → first cards", - until(window, started, |w| has(w, "note-card-open")), - ); - once( - "unlock → index whole", - until(window, started, |w| { - w.state().state.gate.index == IndexFill::Ready - }), - ); + once("unlock → past the gate", until(window, started, |w| has(w, "area-notes"))); + once("unlock → first cards", until(window, started, |w| has(w, "note-card-open"))); + once("unlock → index whole", until(window, started, |w| w.state().state.gate.index == IndexFill::Ready)); settle(window); } @@ -285,9 +266,7 @@ fn typing_in_search(window: &mut Window) { /// The click that opens the card titled `title`, and when it ended. fn press_card(window: &mut Window, title: &str) -> Instant { let rect = window - .get_by(|node| { - node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title) - }) + .get_by(|node| node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title)) .rect(); let pos = rect.min + vec2(60.0, 14.0); window.event(Event::PointerMoved(pos)); @@ -328,17 +307,12 @@ fn open_ten_notes(window: &mut Window) { /// `lines` of Rust, a snippet of its own, opened and typed into, then thrown away. fn large_snippet(window: &mut Window, title: &str, lines: usize) { let engine = window.state().backend().engine(); - let space_id = run_here(engine, engine::spaces::list_spaces).unwrap()[0] - .id - .clone(); + let space_id = run_here(engine, engine::spaces::list_spaces).unwrap()[0].id.clone(); let line = " let étape = migration::run(&mut connection)?; // déploiement du service\n"; let mut draft = crate::testing::snippet(space_id, title.to_owned()); draft.language = engine::notes::language::Language::Rs; draft.content = line.repeat(lines); - let made = run_here(engine, move |engine| { - engine::notes::create_note(engine, draft) - }) - .unwrap(); + let made = run_here(engine, move |engine| engine::notes::create_note(engine, draft)).unwrap(); let ctx = window.ctx.clone(); let app = window.state_mut(); app.state.notes_query.type_search(&ctx, title.to_owned()); @@ -350,10 +324,7 @@ fn large_snippet(window: &mut Window, title: &str, lines: usize) { let drawn = until(window, started, |w| has(w, "editor-body")); once(&format!("{title}: body drawn"), drawn); settle(window); - once( - &format!("{title}: coloured, window at rest"), - started.elapsed(), - ); + once(&format!("{title}: coloured, window at rest"), started.elapsed()); click(window, "editor-body"); settle(window); let mut typed = Samples::default(); @@ -364,18 +335,13 @@ fn large_snippet(window: &mut Window, title: &str, lines: usize) { typed.report(&format!("{title}: a key typed")); close_editor(window); let id = made.id.clone(); - let kept = run_here(window.state().backend().engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap(); - assert_eq!( - kept.content.len(), - made.content.len() + 60, - "every key landed" - ); + let kept = + run_here(window.state().backend().engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap(); + assert_eq!(kept.content.len(), made.content.len() + 60, "every key landed"); window.state_mut().state.notes_query.clear_search(); run_here(window.state().backend().engine(), |engine| { - engine::notes::delete_note(engine, &made.id) + engine::notes::delete_notes(engine, std::slice::from_ref(&made.id)) }) .unwrap(); settle(window); @@ -388,10 +354,7 @@ fn board(window: &mut Window) { .into_iter() .find(|space| space.name == "Espace 0") .expect("the reference's first space"); - act( - window, - Action::Notes(crate::notes::Action::ChooseSpace(Some(space.id))), - ); + act(window, Action::Notes(crate::notes::Action::ChooseSpace(Some(space.id)))); let started = Instant::now(); click(window, "view-board"); window.step(); @@ -408,10 +371,7 @@ fn board(window: &mut Window) { eprintln!("TRACE board after {:?}", card_titles(window).first()); click(window, "view-list"); settle(window); - act( - window, - Action::Notes(crate::notes::Action::ChooseSpace(None)), - ); + act(window, Action::Notes(crate::notes::Action::ChooseSpace(None))); } fn engine_time(window: &Window, job: impl FnOnce(&engine::Engine) -> T) -> Duration { @@ -423,10 +383,7 @@ fn engine_time(window: &Window, job: impl FnOnce(&engine::Engine) -> T) -> Du fn http(window: &mut Window) { let started = Instant::now(); click(window, "area-option-http"); - once( - "HTTP rail loaded", - until(window, started, |w| has(w, "http-node-name")), - ); + once("HTTP rail loaded", until(window, started, |w| has(w, "http-node-name"))); settle(window); assert_eq!(window.state().state.settings.area, Area::Http); let mut unfolded = Samples::default(); @@ -445,10 +402,7 @@ fn http(window: &mut Window) { .filter_map(|n| n.accesskit_node().label()) .collect::>() }; - eprintln!( - "TRACE rows before {:?}", - rows(window).iter().take(3).collect::>() - ); + eprintln!("TRACE rows before {:?}", rows(window).iter().take(3).collect::>()); wheel(window, pos2(120.0, 500.0), 300).report("HTTP rail scrolled"); eprintln!( "TRACE rows after {} {:?}", @@ -457,16 +411,16 @@ fn http(window: &mut Window) { ); let mut found = Samples::default(); for term in ["états", "Lister", "ressources 19", "zzzz", "GET"] { - found.0.push(engine_time(window, |engine| { - engine::http::search_http_requests(engine, term) - })); + found + .0 + .push(engine_time(window, |engine| engine::http::search_http_requests(engine, term))); } found.report("requests searched"); let mut history = Samples::default(); for _ in 0..5 { - history.0.push(engine_time(window, |engine| { - engine::http::http_history(engine, -120) - })); + history + .0 + .push(engine_time(window, |engine| engine::http::http_history(engine, -120))); } history.report("HTTP history, first page"); click(window, "area-option-notes"); diff --git a/crates/ui/src/app/preferences_tests.rs b/crates/ui/src/app/preferences_tests.rs new file mode 100644 index 000000000..55062dfc6 --- /dev/null +++ b/crates/ui/src/app/preferences_tests.rs @@ -0,0 +1,340 @@ +//! The preferences over the whole window: what waits for « Apply », what is shown at once, and +//! the pages that ask something of the core. + +use egui::{Event, Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::DevNotesApp; +use super::tests::{click as click_at, count, open_library, present, settle, type_into}; +use crate::services::settings::Settings; +use crate::testing::PASSPHRASE; + +const NEXT: &str = "another horse battery staple"; + +fn preferences(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let mut harness = open_library(directory); + open(&mut harness); + harness +} + +fn open(harness: &mut Harness<'_, DevNotesApp>) { + click(harness, "file-menu"); + click(harness, "file-preferences"); +} + +fn page(directory: &std::path::Path, id: &str) -> Harness<'static, DevNotesApp> { + let mut harness = preferences(directory); + click(&mut harness, &format!("settings-page-{id}")); + harness +} + +/// Brought in view first: a click below the page is one on what is behind it. +fn click(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) { + harness.get_by(|node| node.author_id() == Some(author_id)).scroll_to_me(); + settle(harness); + click_at(harness, author_id); +} + +fn settings<'a>(harness: &'a Harness<'_, DevNotesApp>) -> &'a Settings { + &harness.state().state().settings +} + +fn said(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> String { + let node = harness.get_by(|node| node.author_id() == Some(author_id)); + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() +} + +// What waits + +#[test] +fn what_is_changed_waits_for_apply() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + let before = settings(&harness).clone(); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "setting-copy-confirmation"); + assert_eq!(settings(&harness), &before); + + click(&mut harness, "settings-apply"); + assert!(settings(&harness).code_wrap && !settings(&harness).copy_confirmation); + assert!(present(&harness, "settings-dialog"), "it stays open"); + harness.key_press(Key::Escape); + settle(&mut harness); + assert!(!present(&harness, "settings-dialog"), "nothing is left to ask about"); +} + +#[test] +fn applied_and_closed_they_are_kept_for_the_next_launch() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "settings-close"); + assert!(!present(&harness, "settings-dialog")); + + let written = + crate::services::preferences::Preferences::read(&directory.path().join(engine::layout::PREFERENCES)); + assert!(Settings::read(&written).code_wrap); +} + +#[test] +fn cancelled_they_change_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + let before = settings(&harness).clone(); + click(&mut harness, "setting-code-wrap"); + click(&mut harness, "settings-cancel"); + if present(&harness, "settings-discard") { + click(&mut harness, "settings-discard"); + } + + assert!(!present(&harness, "settings-dialog")); + assert_eq!(settings(&harness), &before); + open(&mut harness); + assert!(!present(&harness, "settings-unapplied")); +} + +/// Escape makes no click: with work in hand it asks before it drops it. +#[test] +fn escape_asks_before_it_drops_what_was_changed() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + click(&mut harness, "setting-code-wrap"); + harness.key_press(Key::Escape); + settle(&mut harness); + assert!(present(&harness, "settings-dialog") && present(&harness, "settings-discard")); + + click(&mut harness, "settings-discard"); + assert!(!present(&harness, "settings-dialog")); + assert!(!settings(&harness).code_wrap); +} + +#[test] +fn escape_closes_them_with_nothing_changed() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = preferences(directory.path()); + harness.key_press(Key::Escape); + settle(&mut harness); + + assert!(!present(&harness, "settings-dialog")); +} + +#[test] +fn a_version_skipped_can_be_told_again() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = open_library(directory.path()); + "9.9.9".clone_into(&mut harness.state_mut().state.settings.skipped_update); + open(&mut harness); + assert!(said(&harness, "setting-skipped-update").contains("9.9.9")); + + click(&mut harness, "setting-forget-skipped"); + click(&mut harness, "settings-close"); + assert_eq!(settings(&harness).skipped_update, ""); +} + +// The keys + +fn listening(directory: &std::path::Path, action: &str) -> Harness<'static, DevNotesApp> { + let mut harness = page(directory, "shortcuts"); + click(&mut harness, &format!("shortcut-field-{action}")); + harness +} + +fn press(harness: &mut Harness<'_, DevNotesApp>, modifiers: Modifiers, key: Key) { + harness.event(Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers }); + settle(harness); +} + +#[test] +fn a_key_pressed_in_its_field_is_the_action_s_once_applied() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::COMMAND, Key::J); + click(&mut harness, "settings-apply"); + + let pin = crate::services::shortcuts::ACTIONS[9]; + assert_eq!(settings(&harness).bindings.of(pin), "Ctrl+J"); + click(&mut harness, "shortcut-reset-canvas.pin"); + click(&mut harness, "settings-apply"); + assert!(settings(&harness).bindings.is_default(pin)); +} + +#[test] +fn a_key_another_action_has_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::NONE, Key::C); + + assert!(present(&harness, "shortcut-error-canvas.pin")); + assert!(!present(&harness, "settings-unapplied")); +} + +#[test] +fn a_key_the_navigation_keeps_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "canvas.pin"); + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + + assert!(present(&harness, "shortcut-error-canvas.pin")); +} + +#[test] +fn a_global_key_without_a_modifier_is_refused_and_says_so() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = listening(directory.path(), "palette"); + press(&mut harness, Modifiers::NONE, Key::J); + + assert!(present(&harness, "shortcut-error-palette")); +} + +/// A file edited by hand: no field could have refused it. +#[test] +fn two_actions_on_one_key_are_said() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = open_library(directory.path()); + let pin = crate::services::shortcuts::ACTIONS[9]; + harness.state_mut().state.settings.bindings.set(pin, "C".to_owned()); + open(&mut harness); + click(&mut harness, "settings-page-shortcuts"); + + assert!(present(&harness, "shortcut-conflict")); +} + +// The passphrase + +fn change(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let mut harness = page(directory, "security"); + click(&mut harness, "setting-change-passphrase"); + harness +} + +fn fields(harness: &mut Harness<'_, DevNotesApp>, current: &str, next: &str, confirmation: &str) { + for (id, words) in [ + ("change-passphrase-current", current), + ("change-passphrase-next", next), + ("change-passphrase-confirmation", confirmation), + ] { + type_into(harness, id, words); + } +} + +#[test] +fn the_passphrase_is_changed_and_the_dialog_closes() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, PASSPHRASE, NEXT, NEXT); + click(&mut harness, "change-passphrase-submit"); + + assert!(!present(&harness, "change-passphrase-current")); + assert!(harness.state().state().status.latest().is_some()); + assert!(harness.state().state().errors.notice().is_none()); +} + +#[test] +fn a_wrong_passphrase_is_refused_there_and_typing_withdraws_it() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, "not the phrase", NEXT, NEXT); + click(&mut harness, "change-passphrase-submit"); + assert!(present(&harness, "change-passphrase-current")); + assert!(harness.state().state().security.refused()); + + type_into(&mut harness, "change-passphrase-current", "x"); + assert!(!harness.state().state().security.refused()); +} + +#[test] +fn a_new_phrase_too_short_or_mistyped_cannot_be_sent() { + for (next, confirmation) in [("too short", "too short"), (NEXT, "another horse battery")] { + let directory = tempfile::tempdir().unwrap(); + let mut harness = change(directory.path()); + fields(&mut harness, PASSPHRASE, next, confirmation); + click(&mut harness, "change-passphrase-submit"); + assert!(present(&harness, "change-passphrase-current"), "{next}"); + assert!(!harness.state().state().security.is_changing()); + assert!(harness.state().state().status.latest().is_none()); + } +} + +// The copies + +#[test] +fn a_library_just_made_has_no_copy_yet_or_lists_them() { + let directory = tempfile::tempdir().unwrap(); + let harness = page(directory.path(), "backups"); + let copies = harness.state().state().backups.copies().len(); + + assert_eq!(present(&harness, "backup-empty"), copies == 0); + assert_eq!(count(&harness, "backup-row"), copies); +} + +// The variables + +#[test] +fn a_variable_added_is_proposed_once_applied() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = page(directory.path(), "variables"); + click(&mut harness, "variable-add"); + assert_eq!(count(&harness, "variable-row"), 1); + type_into(&mut harness, "variable-name", "host"); + type_into(&mut harness, "variable-value", "prod"); + click(&mut harness, "settings-apply"); + + let kept = harness.state().state().security.variables().unwrap(); + assert_eq!((kept[0].name.as_str(), kept[0].value.as_str()), ("host", "prod")); + click(&mut harness, "variable-remove"); + assert_eq!(count(&harness, "variable-row"), 0); + click(&mut harness, "settings-apply"); + assert!(harness.state().state().security.variables().unwrap().is_empty()); +} + +/// The library left and opened again: its launch copy is taken then, and listed on its page. +fn copies(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { + let first = open_library(directory); + crate::testing::close_library(first.state().backend()); + drop(first); + let startup = super::tests::startup(directory); + let mut harness = Harness::builder() + .with_size(egui::vec2(1_100.0, 720.0)) + .build_eframe(|cc| DevNotesApp::new(cc, startup).unwrap()); + harness + .ctx + .set_missing_glyph_policy(egui::epaint::text::MissingGlyphPolicy::Tofu); + settle(&mut harness); + type_into(&mut harness, "vault-passphrase", PASSPHRASE); + harness.key_press(Key::Enter); + settle(&mut harness); + harness.set_size(egui::vec2(1_300.0, 2_400.0)); + settle(&mut harness); + open(&mut harness); + click(&mut harness, "settings-page-backups"); + harness +} + +#[test] +fn a_copy_put_back_is_asked_first_and_can_be_let_be() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = copies(directory.path()); + assert_eq!(count(&harness, "backup-row"), 1); + let said = said(&harness, "backup-detail"); + assert!(said.contains(" · "), "its date and its size: {said}"); + + click(&mut harness, "backup-restore"); + assert!(present(&harness, "backup-confirm") && !present(&harness, "backup-restore")); + click(&mut harness, "backup-cancel"); + assert!(present(&harness, "backup-restore") && !present(&harness, "backup-confirm")); +} + +/// The library closes under it: the copy's own phrase is asked for. +#[test] +fn a_copy_put_back_closes_the_library_and_asks_for_its_phrase() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = copies(directory.path()); + click(&mut harness, "backup-restore"); + click(&mut harness, "backup-confirm-restore"); + settle(&mut harness); + + assert!(present(&harness, "vault-passphrase")); + assert!(!harness.state().state().gate.is_open()); +} diff --git a/crates/ui/src/app/prompt_tests.rs b/crates/ui/src/app/prompt_tests.rs index 2bda35701..cb5ef5a63 100644 --- a/crates/ui/src/app/prompt_tests.rs +++ b/crates/ui/src/app/prompt_tests.rs @@ -57,3 +57,37 @@ fn a_phrase_typed_does_not_outlive_an_export_in_the_clear() { export(&mut harness); assert!(!can_submit(&harness), "the fields start empty"); } + +/// Nothing is written with a phrase typed two ways, and the prompt says why. +#[test] +fn two_phrases_that_differ_cannot_be_sent() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + type_into(&mut harness, "passphrase-prompt-confirmation", "x"); + + assert!(!can_submit(&harness)); + assert!(present(&harness, "passphrase-prompt-problem")); +} + +#[test] +fn escape_cancels_the_prompt_and_writes_nothing() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + + assert!(!present(&harness, "passphrase-prompt")); + assert!(!directory.path().join("library.devnotes").exists()); +} + +#[test] +fn an_export_is_written_under_the_phrase_and_said() { + let directory = tempfile::tempdir().unwrap(); + let mut harness = asking(directory.path()); + click(&mut harness, "passphrase-prompt-submit"); + settle(&mut harness); + + let said = harness.state().state.status.latest().unwrap().1.key; + assert!(said.path().starts_with("file.exportedProtected"), "{}", said.path()); + assert!(directory.path().join("library.devnotes").exists()); +} diff --git a/crates/ui/src/app/rail_toggle_tests.rs b/crates/ui/src/app/rail_toggle_tests.rs index 7f55e9b0c..978cb84b9 100644 --- a/crates/ui/src/app/rail_toggle_tests.rs +++ b/crates/ui/src/app/rail_toggle_tests.rs @@ -10,9 +10,7 @@ use super::tests::{click, open_library, settle}; /// The toggle's box, found by its address, in the window's points. fn toggle(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } /// Every place the toggle is drawn, at the density chosen: where it stood, page by page. @@ -49,16 +47,8 @@ fn the_sidebar_toggle_stands_at_one_place_in_every_area_at_both_densities() { let mut harness = open_library(directory.path()); let backend = harness.state().backend(); let local = crate::http::tests::collection(backend, "Local"); - crate::http::tests::request( - backend, - (&local, None), - "Login", - (RequestKind::Http, HttpMethod::Get), - ); - for density in [ - crate::theme::Density::Comfortable, - crate::theme::Density::Compact, - ] { + crate::http::tests::request(backend, (&local, None), "Login", (RequestKind::Http, HttpMethod::Get)); + for density in [crate::theme::Density::Comfortable, crate::theme::Density::Compact] { let ctx = harness.ctx.clone(); let app = harness.state_mut(); app.state.settings.density = density; @@ -68,8 +58,7 @@ fn the_sidebar_toggle_stands_at_one_place_in_every_area_at_both_densities() { let (_, first) = seen[0]; for (page, rect) in &seen { assert!( - (rect.min - first.min).length() < 0.5 - && (rect.size() - first.size()).length() < 0.5, + (rect.min - first.min).length() < 0.5 && (rect.size() - first.size()).length() < 0.5, "{density:?}: {page} at {rect:?}, the notes at {first:?}\n{seen:?}" ); } @@ -82,24 +71,15 @@ fn the_environment_picker_ends_at_the_margin_of_the_request_line() { let mut harness = open_library(directory.path()); let backend = harness.state().backend(); let local = crate::http::tests::collection(backend, "Local"); - crate::http::tests::request( - backend, - (&local, None), - "Login", - (RequestKind::Http, HttpMethod::Post), - ); + crate::http::tests::request(backend, (&local, None), "Login", (RequestKind::Http, HttpMethod::Post)); click(&mut harness, "area-option-http"); harness .get_by(|node| { - node.author_id() == Some("http-node-name") - && node.label().as_deref() == Some("POST Login") + node.author_id() == Some("http-node-name") && node.label().as_deref() == Some("POST Login") }) .click(); let margin = harness.ctx.content_rect().right() - crate::theme::tokens::BAR_INSET; - for density in [ - crate::theme::Density::Comfortable, - crate::theme::Density::Compact, - ] { + for density in [crate::theme::Density::Comfortable, crate::theme::Density::Compact] { let ctx = harness.ctx.clone(); let app = harness.state_mut(); app.state.settings.density = density; diff --git a/crates/ui/src/app/screens.rs b/crates/ui/src/app/screens.rs index 8919ea64f..fc308e428 100644 --- a/crates/ui/src/app/screens.rs +++ b/crates/ui/src/app/screens.rs @@ -85,9 +85,7 @@ fn wait(window: &mut Window) { } fn click(window: &mut Window, author_id: &str) { - window - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + window.get_by(|node| node.author_id() == Some(author_id)).click(); settle(window); } @@ -100,9 +98,7 @@ fn click_named(window: &mut Window, author_id: &str, name: &str) { fn type_into(window: &mut Window, author_id: &str, words: &str) { click(window, author_id); - window - .get_by(|node| node.author_id() == Some(author_id)) - .type_text(words); + window.get_by(|node| node.author_id() == Some(author_id)).type_text(words); settle(window); } @@ -120,9 +116,7 @@ fn area(window: &mut Window, area: Area) { /// By the card's head: its middle may be a task, which a click would tick. fn card(window: &mut Window, title: &str) { let rect = window - .get_by(|node| { - node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title) - }) + .get_by(|node| node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title)) .rect(); let pos = rect.min + egui::vec2(60.0, 14.0); window.event(egui::Event::PointerMoved(pos)); @@ -141,9 +135,7 @@ fn card(window: &mut Window, title: &str) { fn hover_card(window: &mut Window, title: &str) { window - .get_by(|node| { - node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title) - }) + .get_by(|node| node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title)) .hover(); settle(window); } @@ -152,9 +144,7 @@ fn hover_card(window: &mut Window, title: &str) { fn tick(window: &mut Window, title: &str) { hover_card(window, title); let open = window - .get_by(|node| { - node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title) - }) + .get_by(|node| node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title)) .rect(); window .get_all_by(|node| node.author_id() == Some("note-card-check")) @@ -171,19 +161,10 @@ fn seed(window: &Window) { let scene = String::new(); engine::db::run_here(backend.engine(), move |engine| { let home = engine::spaces::list_spaces(engine)?.remove(0).id; - let work = engine::spaces::create_space( - engine, - &SpaceDraft { - name: "Projets".to_string(), - }, - )?; + let work = engine::spaces::create_space(engine, &SpaceDraft { name: "Projets".to_string() })?; let ops = engine::folders::create_folder( engine, - &FolderDraft { - space_id: work.id.clone(), - name: "Exploitation".to_string(), - parent_id: None, - }, + &FolderDraft { space_id: work.id.clone(), name: "Exploitation".to_string(), parent_id: None }, )?; let releases = engine::folders::create_folder( engine, @@ -231,10 +212,7 @@ fn seed(window: &Window) { ..draft(&home, NOTE, NoteKind::Note, NOTE_BODY) }, )?; - let item = |text: &str, done| ChecklistItem { - text: text.to_string(), - done, - }; + let item = |text: &str, done| ChecklistItem { text: text.to_string(), done }; engine::notes::create_note( engine, NoteDraft { @@ -269,38 +247,23 @@ fn seed(window: &Window) { engine, NoteDraft { folder_id: Some(releases.id.clone()), - ..draft( - &work.id, - "Notes de version 2.4", - NoteKind::Note, - "## 2.4\n\n- Export CSV", - ) + ..draft(&work.id, "Notes de version 2.4", NoteKind::Note, "## 2.4\n\n- Export CSV") }, )?; - let trashed = engine::notes::create_note( - engine, - draft(&home, TRASHED, NoteKind::Snippet, "obsolète"), - )?; + let trashed = + engine::notes::create_note(engine, draft(&home, TRASHED, NoteKind::Snippet, "obsolète"))?; engine::notes::update_note( engine, &snippet.id, &NotePatch { - content: Some(format!( - "{}\nkubectl get pods -n {{{{namespace}}}}", - snippet.content - )), + content: Some(format!("{}\nkubectl get pods -n {{{{namespace}}}}", snippet.content)), ..NotePatch::default() }, )?; - engine::notes::delete_note(engine, &trashed.id)?; + engine::notes::delete_notes(engine, std::slice::from_ref(&trashed.id))?; let api = engine::http::create_http_collection(engine, "API Facturation")?; - let auth = engine::http::create_http_folder( - engine, - &api.id, - None, - "Authentification", - )?; + let auth = engine::http::create_http_folder(engine, &api.id, None, "Authentification")?; let request = |folder_id: Option, name: &str, method| HttpRequestDraft { collection_id: api.id.clone(), folder_id, @@ -308,10 +271,7 @@ fn seed(window: &Window) { kind: RequestKind::Http, method, document: RequestDocument { - url: format!( - "https://api.exemple.fr/{}", - name.to_lowercase().replace(' ', "-") - ), + url: format!("https://api.exemple.fr/{}", name.to_lowercase().replace(' ', "-")), ..RequestDocument::default() }, }; @@ -319,10 +279,7 @@ fn seed(window: &Window) { engine, &request(Some(auth.id.clone()), "Connexion", HttpMethod::Post), )?; - engine::http::create_http_request( - engine, - &request(None, "Lister les factures", HttpMethod::Get), - )?; + engine::http::create_http_request(engine, &request(None, "Lister les factures", HttpMethod::Get))?; engine::http::create_http_environment(engine, "Recette")?; Ok::<_, engine::error::AppError>(()) }) @@ -354,9 +311,7 @@ fn draw(window: &mut Window, directory: &Path, name: &str, appearance: Appearanc // kittest draws its pointer, and where a click left it. window.event(egui::Event::PointerGone); settle(window); - let image = window - .render() - .expect("a software adapter draws the window"); + let image = window.render().expect("a software adapter draws the window"); image.save(directory.join(format!("{name}.png"))).unwrap(); } @@ -389,18 +344,8 @@ fn both_themes(profile: &Path, directory: &Path, screens: &[(&str, Reach)]) { let profile = copy_of(profile); let mut window = unlocked(profile.path(), DEFAULT_SIZE, false); reach(&mut window); - draw( - &mut window, - directory, - &format!("{id}--dark"), - Appearance::Dark, - ); - draw( - &mut window, - directory, - &format!("{id}--light"), - Appearance::Light, - ); + draw(&mut window, directory, &format!("{id}--dark"), Appearance::Dark); + draw(&mut window, directory, &format!("{id}--light"), Appearance::Light); crate::testing::close_library(window.state().backend()); } } @@ -471,10 +416,7 @@ const NOTES: [(&str, Reach); 14] = [ const EDITORS: [(&str, Reach); 9] = [ ("notes-palette", |window| { - window.key_press_modifiers( - egui::Modifiers::COMMAND | egui::Modifiers::ALT, - egui::Key::P, - ); + window.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::P); settle(window); }), ("editor-snippet", |window| card(window, SNIPPET)), @@ -613,14 +555,8 @@ fn the_tools() { let mut window = unlocked(profile, DEFAULT_SIZE, false); area(&mut window, Area::Tools); for tool in &crate::tools::catalogue::TOOLS { - act( - &mut window, - Action::Tools(crate::tools::Action::Open(tool.id)), - ); - if window - .query_by(|node| node.author_id() == Some("tool-sample")) - .is_some() - { + act(&mut window, Action::Tools(crate::tools::Action::Open(tool.id))); + if window.query_by(|node| node.author_id() == Some("tool-sample")).is_some() { click(&mut window, "tool-sample"); } wait(&mut window); @@ -659,10 +595,7 @@ fn the_sizes_and_the_density() { .iter() .copied() .filter(|(id, _)| *id != "editor-note") - .chain([( - "editor-checklist", - (|window| card(window, CHECKLIST)) as Reach, - )]); + .chain([("editor-checklist", (|window| card(window, CHECKLIST)) as Reach)]); for (id, reach) in compact { let profile = copy_of(profile); let mut window = unlocked(profile.path(), DEFAULT_SIZE, true); diff --git a/crates/ui/src/app/titlebar_tests.rs b/crates/ui/src/app/titlebar_tests.rs index 2ebee84c7..8234eb6e4 100644 --- a/crates/ui/src/app/titlebar_tests.rs +++ b/crates/ui/src/app/titlebar_tests.rs @@ -14,7 +14,9 @@ const SIZE: egui::Vec2 = egui::vec2(1100.0, 720.0); const EMPTY: Pos2 = pos2(700.0, 19.0); fn window(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { - let startup = startup(directory); + let mut startup = startup(directory); + // Its controls are named in the language on screen, the machine's otherwise. + startup.preferences.set("devnotes.locale", "en"); // A frame a sixtieth of a second, as on screen: two clicks a step apart are one double click. let mut harness = Harness::builder() .with_size(SIZE) @@ -25,9 +27,7 @@ fn window(directory: &std::path::Path) -> Harness<'static, DevNotesApp> { } fn rect_of(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } fn label_of(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> String { @@ -64,12 +64,7 @@ fn click_at(harness: &mut Harness<'_, DevNotesApp>, author_id: &str) -> Vec) { - harness - .input_mut() - .viewports - .entry(ViewportId::ROOT) - .or_default() - .maximized = Some(true); + harness.input_mut().viewports.entry(ViewportId::ROOT).or_default().maximized = Some(true); settle(harness); } @@ -172,12 +167,7 @@ fn a_press_on_an_edge_resizes_from_it_unless_the_window_fills_the_screen() { maximized(&mut harness); pointer(&mut harness, pos2(1.0, 360.0), &[]); let asked = pointer(&mut harness, pos2(1.0, 360.0), &[true]); - assert!( - !asked - .iter() - .any(|command| matches!(command, Command::BeginResize(_))), - "{asked:?}" - ); + assert!(!asked.iter().any(|command| matches!(command, Command::BeginResize(_))), "{asked:?}"); } /// As the system's frame: a dialog open does not hold the window. diff --git a/crates/ui/src/app/update_prompt_tests.rs b/crates/ui/src/app/update_prompt_tests.rs index 793340d93..114a5fd4a 100644 --- a/crates/ui/src/app/update_prompt_tests.rs +++ b/crates/ui/src/app/update_prompt_tests.rs @@ -84,10 +84,7 @@ fn installing_leaves_first_and_cannot_be_dismissed() { settle(&mut harness); assert!(harness.state().state().quitting); - assert!( - !*fake.relaunched.lock().unwrap(), - "after the exit, not before" - ); + assert!(!*fake.relaunched.lock().unwrap(), "after the exit, not before"); assert!(present(&harness, "update-status")); assert!(!present(&harness, "update-later")); harness.key_press(egui::Key::Escape); @@ -131,9 +128,7 @@ fn launched(directory: &std::path::Path, fake: Arc) -> Harness<'sta } fn rect(harness: &Harness<'_, DevNotesApp>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } #[test] @@ -142,10 +137,7 @@ fn the_menu_says_nothing_of_a_check_it_did_not_ask_and_forgets_one_it_did() { let mut harness = launched(directory.path(), Arc::new(FakeUpdater::default())); click(&mut harness, "about-open"); - assert!( - !present(&harness, "about-check-status"), - "nothing was asked" - ); + assert!(!present(&harness, "about-check-status"), "nothing was asked"); click(&mut harness, "about-check-updates"); settle(&mut harness); @@ -154,10 +146,7 @@ fn the_menu_says_nothing_of_a_check_it_did_not_ask_and_forgets_one_it_did() { harness.key_press(egui::Key::Escape); settle(&mut harness); click(&mut harness, "about-open"); - assert!( - !present(&harness, "about-check-status"), - "what was found then is not said again" - ); + assert!(!present(&harness, "about-check-status"), "what was found then is not said again"); } #[test] @@ -170,10 +159,7 @@ fn an_update_known_is_named_by_its_entry_drawn_clear_of_the_next() { let entry = harness.get_by(|node| node.author_id() == Some("about-check-updates")); let label = entry.accesskit_node().label().unwrap_or_default(); assert!(label.contains("0.26.0"), "{label}"); - let (entry, next) = ( - rect(&harness, "about-check-updates"), - rect(&harness, "about-whats-new"), - ); + let (entry, next) = (rect(&harness, "about-check-updates"), rect(&harness, "about-whats-new")); // The separator between them is 7 points tall. assert!(next.top() >= entry.bottom() + 6.0, "{entry:?} {next:?}"); diff --git a/crates/ui/src/app/window_tests.rs b/crates/ui/src/app/window_tests.rs index ab06c0635..d443ef49e 100644 --- a/crates/ui/src/app/window_tests.rs +++ b/crates/ui/src/app/window_tests.rs @@ -16,11 +16,7 @@ fn press_the_close_button(harness: &mut Harness<'_, DevNotesApp>) { } fn viewport<'a>(harness: &'a mut Harness<'_, DevNotesApp>) -> &'a mut ViewportInfo { - harness - .input_mut() - .viewports - .entry(ViewportId::ROOT) - .or_default() + harness.input_mut().viewports.entry(ViewportId::ROOT).or_default() } fn hidden_and_held(commands: &[Command]) -> bool { @@ -54,8 +50,7 @@ fn with_the_preference_off_the_close_button_ends_the_application() { #[test] fn without_a_tray_the_close_button_hides_the_window_all_the_same() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); press_the_close_button(&mut harness); @@ -65,8 +60,7 @@ fn without_a_tray_the_close_button_hides_the_window_all_the_same() { #[test] fn without_a_tray_and_with_the_preference_off_the_close_button_ends_the_application() { let directory = tempfile::tempdir().unwrap(); - let mut harness = - Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); + let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup(directory.path())).unwrap()); harness.state_mut().state.settings.close_to_tray = false; press_the_close_button(&mut harness); @@ -85,9 +79,7 @@ fn a_second_launch_s_palette_brings_the_hidden_window_back() { let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup).unwrap()); press_the_close_button(&mut harness); - posted.post(Input::Instance(platform::instance::Message::Action( - "palette".to_owned(), - ))); + posted.post(Input::Instance(platform::instance::Message::Action("palette".to_owned()))); harness.step(); assert!(commands(&harness).contains(&Command::Visible(true))); @@ -168,19 +160,12 @@ fn a_full_screen_is_not_the_size_to_reopen_at() { let directory = tempfile::tempdir().unwrap(); let (mut harness, _, _) = with_a_tray(directory.path()); let rect = |width| egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 600.0)); - let placed = ViewportInfo { - outer_rect: Some(rect(800.0)), - inner_rect: Some(rect(800.0)), - ..Default::default() - }; + let placed = + ViewportInfo { outer_rect: Some(rect(800.0)), inner_rect: Some(rect(800.0)), ..Default::default() }; let app = harness.state_mut(); app.remember(&placed); - app.remember(&ViewportInfo { - fullscreen: Some(true), - inner_rect: Some(rect(1_920.0)), - ..placed - }); + app.remember(&ViewportInfo { fullscreen: Some(true), inner_rect: Some(rect(1_920.0)), ..placed }); assert!((app.geometry.unwrap().width - 800.0).abs() < f32::EPSILON); } @@ -190,25 +175,16 @@ fn a_full_screen_is_not_the_size_to_reopen_at() { fn closed_maximised_it_asks_to_be_maximised_once_shown() { let directory = tempfile::tempdir().unwrap(); let mut startup = startup(directory.path()); - startup.geometry = Some(platform::window::Geometry { - x: 0.0, - y: 0.0, - width: 800.0, - height: 600.0, - maximized: true, - }); + startup.geometry = + Some(platform::window::Geometry { x: 0.0, y: 0.0, width: 800.0, height: 600.0, maximized: true }); let mut harness = Harness::new_eframe(|cc| DevNotesApp::new(cc, startup).unwrap()); // The first frame again: the harness draws it while it is built, its commands behind us. harness.state_mut().shown = false; harness.step(); let commands = commands(&harness); - let shown = commands - .iter() - .position(|asked| *asked == Command::Visible(true)); - let maximized = commands - .iter() - .position(|asked| *asked == Command::Maximized(true)); + let shown = commands.iter().position(|asked| *asked == Command::Visible(true)); + let maximized = commands.iter().position(|asked| *asked == Command::Maximized(true)); assert!(shown.is_some() && maximized > shown, "{commands:?}"); } @@ -219,10 +195,7 @@ fn a_window_that_names_no_place_keeps_its_size() { let app = harness.state_mut(); app.remember(&ViewportInfo { - inner_rect: Some(egui::Rect::from_min_size( - egui::Pos2::ZERO, - egui::vec2(800.0, 600.0), - )), + inner_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))), ..Default::default() }); diff --git a/crates/ui/src/backend.rs b/crates/ui/src/backend.rs index d3623f5da..4c93bd95a 100644 --- a/crates/ui/src/backend.rs +++ b/crates/ui/src/backend.rs @@ -54,12 +54,7 @@ impl Backend { .enable_all() .build()?; let engine = Arc::new(Engine::new(paths, events, runtime.handle().clone())); - Ok(Self { - engine, - runtime, - waker, - in_flight: Arc::default(), - }) + Ok(Self { engine, runtime, waker, in_flight: Arc::default() }) } pub fn engine(&self) -> &Arc { @@ -74,8 +69,7 @@ impl Backend { let (pending, answer) = self.pending(); // Queued here, on the caller's thread: a task would reach the queue in its own time. let answered = engine::db::submit(&self.engine, timed(job)); - self.runtime - .spawn(async move { answer.send(answered.await) }); + self.runtime.spawn(async move { answer.send(answered.await) }); pending } @@ -114,13 +108,7 @@ impl Backend { waker: self.waker.clone(), in_flight: Arc::clone(&self.in_flight), }; - ( - Pending { - receiver, - answered: false, - }, - answer, - ) + (Pending { receiver, answered: false }, answer) } /// The one wait the UI thread is allowed (D19): at the exit, the window already gone, until @@ -128,19 +116,14 @@ impl Backend { /// `false` when it had not finished. pub fn drain(&self, limit: std::time::Duration) -> bool { let done = engine::db::submit(&self.engine, |_| Ok(())); - self.runtime - .block_on(async { tokio::time::timeout(limit, done).await }) - .is_ok() + self.runtime.block_on(async { tokio::time::timeout(limit, done).await }).is_ok() } /// Work the core goes on with after answering — the index filling behind an unlock — /// counted until it ends like an answer, so that waiting for the core waits for it too. pub fn background(&self) -> Background { self.in_flight.add(); - Background { - waker: self.waker.clone(), - in_flight: Arc::clone(&self.in_flight), - } + Background { waker: self.waker.clone(), in_flight: Arc::clone(&self.in_flight) } } /// Tests only: waits until everything launched has answered or ended. A condition, never a @@ -153,9 +136,7 @@ impl Backend { /// Tests only: how many jobs were ever launched, answered or not. #[cfg(test)] pub fn launched(&self) -> usize { - self.in_flight - .launched - .load(std::sync::atomic::Ordering::SeqCst) + self.in_flight.launched.load(std::sync::atomic::Ordering::SeqCst) } } @@ -245,8 +226,7 @@ struct InFlight { impl InFlight { fn add(&self) { - self.launched - .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + self.launched.fetch_add(1, std::sync::atomic::Ordering::SeqCst); if let Ok(mut count) = self.count.lock() { *count += 1; } @@ -338,4 +318,79 @@ mod tests { drop(pendings); assert_eq!(*order.lock().unwrap(), (0..20).collect::>()); } + + #[test] + fn a_job_that_fails_is_its_error_whatever_the_queue() { + let (backend, _profile) = testing::backend(); + let failed = || AppError::from(StorageError::WrongPassphrase); + + let mut answers = [ + backend.db(move |_| Err::<(), _>(failed())), + backend.compute(move |_| Err(failed())), + backend.spawn(move |_| async move { Err(failed()) }), + ]; + backend.settle(); + for answer in &mut answers { + assert_eq!(answer.poll().unwrap().unwrap_err().code, ErrorCode::WrongPassphrase); + } + } + + #[test] + fn work_begun_behind_an_answer_is_waited_for_until_it_ends() { + let (backend, _profile) = testing::backend(); + let launched = backend.launched(); + let background = backend.background(); + assert_eq!(backend.launched(), launched + 1); + let ended = Arc::new(Mutex::new(false)); + let flag = Arc::clone(&ended); + let _begun = backend.spawn(move |_| async move { + background.run(async move { + for _ in 0..1_000 { + tokio::task::yield_now().await; + } + *flag.lock().unwrap() = true; + }); + Ok(()) + }); + + backend.settle(); + assert!(*ended.lock().unwrap()); + } + + /// Never begun, it still lets go: nothing would be waited for for good. + #[test] + fn work_never_begun_lets_go_and_wakes_the_window() { + let (backend, _profile) = testing::backend(); + let ctx = egui::Context::default(); + backend.waker.fill(&ctx); + + drop(backend.background()); + backend.settle(); + assert!(ctx.has_requested_repaint()); + } + + #[test] + fn an_answer_not_there_yet_is_nothing() { + let (backend, _profile) = testing::backend(); + + let (mut pending, answer) = backend.pending::(); + assert!(pending.poll().is_none()); + answer.send(Ok(7)); + assert_eq!(pending.poll().unwrap().unwrap(), 7); + assert!(pending.poll().is_none()); + } + + #[test] + fn the_exit_does_not_wait_past_its_limit() { + let (backend, _profile) = testing::backend(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let _busy = backend.db(move |_| { + let _ = held.recv(); + Ok(()) + }); + + assert!(!backend.drain(std::time::Duration::ZERO)); + drop(release); + backend.settle(); + } } diff --git a/crates/ui/src/banners/toasts.rs b/crates/ui/src/banners/toasts.rs index 9901e9968..feaecdb53 100644 --- a/crates/ui/src/banners/toasts.rs +++ b/crates/ui/src/banners/toasts.rs @@ -8,8 +8,8 @@ use std::time::Duration; use crate::theme::tokens::{font, gap, radius}; use egui::accesskit::Live; use egui::{ - Align2, Color32, Context, CornerRadius, Id, Order, Rect, Role, Sense, Stroke, StrokeKind, Ui, - Vec2, WidgetInfo, pos2, vec2, + Align2, Color32, Context, CornerRadius, Id, Order, Rect, Role, Sense, Stroke, StrokeKind, Ui, Vec2, + WidgetInfo, pos2, vec2, }; use i18n::{Language, keys}; @@ -93,9 +93,7 @@ fn lifted(ctx: &Context) -> f32 { }); let corner = ctx.content_rect().right() - FROM_EDGE - WIDTH; match bar { - Some(bar) if bar.right() + gap::CONTROLS > corner => { - FROM_EDGE + bar.height() + gap::CONTROLS - } + Some(bar) if bar.right() + gap::CONTROLS > corner => FROM_EDGE + bar.height() + gap::CONTROLS, _ => FROM_EDGE, } } @@ -105,17 +103,13 @@ fn lifted(ctx: &Context) -> f32 { fn timed_out(ui: &Ui, said: u64, pointed: bool) -> bool { let now = ui.input(|input| input.time); let since = Id::unique("status-toast-since").with(said); - let started: f64 = ui - .data(|data| data.get_temp(since)) - .filter(|_| !pointed) - .unwrap_or(now); + let started: f64 = ui.data(|data| data.get_temp(since)).filter(|_| !pointed).unwrap_or(now); ui.data_mut(|data| data.insert_temp(since, started)); let left = f64::from(motion::REPORT) - (now - started); if left <= 0.0 { return true; } - ui.ctx() - .request_repaint_after(Duration::from_secs_f64(left)); + ui.ctx().request_repaint_after(Duration::from_secs_f64(left)); false } @@ -124,46 +118,30 @@ fn toast(ui: &mut Ui, words: &str, kind: Kind, language: Language) -> bool { let p = palette(ui.ctx()); let left = gap::SNUG + EDGE + gap::INSET + GLYPH + gap::INSET; let room = WIDTH - left - gap::SNUG - CLOSE - gap::CONTROLS; - let galley = ui.painter().layout( - words.to_owned(), - egui::FontId::proportional(font::BODY), - p.text_0, - room, - ); + let galley = + ui.painter() + .layout(words.to_owned(), egui::FontId::proportional(font::BODY), p.text_0, room); let height = (galley.size().y + 2.0 * gap::INSET).max(CLOSE + 2.0 * gap::SNUG); let (card, response) = ui.allocate_exact_size(vec2(WIDTH, height), Sense::hover()); let corner = CornerRadius::same(radius::CARD); ui.painter().add(p.shadow_overlay.as_shape(card, corner)); - ui.painter().rect( - card, - corner, - p.bg_1, - Stroke::new(1.0, p.line), - StrokeKind::Inside, - ); - let edge = Rect::from_min_size( - card.min + vec2(gap::SNUG, gap::SNUG), - vec2(EDGE, height - 2.0 * gap::SNUG), - ); ui.painter() - .rect_filled(edge, CornerRadius::same(radius::MARK), kind.hue); + .rect(card, corner, p.bg_1, Stroke::new(1.0, p.line), StrokeKind::Inside); + let edge = + Rect::from_min_size(card.min + vec2(gap::SNUG, gap::SNUG), vec2(EDGE, height - 2.0 * gap::SNUG)); + ui.painter().rect_filled(edge, CornerRadius::same(radius::MARK), kind.hue); response.widget_info(|| WidgetInfo::labeled(Role::Status, true, words)); widgets::address(ui, &response, kind.author_id); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_live(kind.live)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_live(kind.live)); let top = card.center().y - galley.size().y / 2.0; // On the first line, where the words begin. - let line = galley - .rows - .first() - .map_or(galley.size().y, |row| row.height()); + let line = galley.rows.first().map_or(galley.size().y, |row| row.height()); let glyph = Rect::from_center_size( pos2(edge.right() + gap::INSET + GLYPH / 2.0, top + line / 2.0), Vec2::splat(GLYPH), ); icons::paint(ui, glyph, kind.icon, kind.hue); - ui.painter() - .galley(pos2(card.left() + left, top), galley, p.text_0); + ui.painter().galley(pos2(card.left() + left, top), galley, p.text_0); let cross = Rect::from_min_size( pos2(card.right() - gap::SNUG - CLOSE, card.top() + gap::SNUG), Vec2::splat(CLOSE), diff --git a/crates/ui/src/banners/update_prompt.rs b/crates/ui/src/banners/update_prompt.rs index 09ec4a357..23945dcfd 100644 --- a/crates/ui/src/banners/update_prompt.rs +++ b/crates/ui/src/banners/update_prompt.rs @@ -43,25 +43,14 @@ pub(crate) fn id() -> Id { Id::unique("update-prompt") } -pub(crate) fn show( - ctx: &egui::Context, - state: &AppState, - view: &mut UpdateView, - actions: &mut Actions, -) { +pub(crate) fn show(ctx: &egui::Context, state: &AppState, view: &mut UpdateView, actions: &mut Actions) { let Some(update) = state.updates.offered().filter(|_| state.gate.is_open()) else { return; }; let cross = i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]); - let shown = widgets::dialog( - ctx, - &state.dialogs, - (id(), (&cross, "update-cross")), - WIDTH, - |ui| { - body(ui, state, update, view, actions); - }, - ); + let shown = widgets::dialog(ctx, &state.dialogs, (id(), (&cross, "update-cross")), WIDTH, |ui| { + body(ui, state, update, view, actions); + }); let busy = state.updates.is_busy(); if shown.is_some_and(|shown| shown.should_close()) && !busy { let skip = view.skip; @@ -135,10 +124,7 @@ fn body( { ask(Ask::Install); } - if Button::new(&tr(keys::update::LATER), "update-later") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::update::LATER), "update-later").show(ui).clicked() { ask(Ask::Later { skip }); } }); @@ -149,9 +135,9 @@ fn progress(ui: &mut Ui, state: &AppState) { let p = palette(ui.ctx()); let percent = state.updates.progress(); let said = match (state.updates.status(), percent) { - (Status::Installed, _) => Message::new(keys::update::RESTARTING) - .with("app", METADATA.name) - .text(language), + (Status::Installed, _) => { + Message::new(keys::update::RESTARTING).with("app", METADATA.name).text(language) + } (_, Some(percent)) => Message::new(keys::update::DOWNLOADING_PERCENT) .with("percent", percent) .text(language), @@ -161,8 +147,7 @@ fn progress(ui: &mut Ui, state: &AppState) { widgets::address(ui, &status, "update-status"); #[expect(clippy::cast_precision_loss, reason = "a percent")] let done = percent.map_or(0.0, |percent| percent as f32 / 100.0); - let (rect, _) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), 6.0), egui::Sense::hover()); + let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 6.0), egui::Sense::hover()); let corner = egui::CornerRadius::same(radius::TAG); ui.painter().rect_filled(rect, corner, p.bg_3); let filled = egui::Rect::from_min_size(rect.min, Vec2::new(rect.width() * done, rect.height())); diff --git a/crates/ui/src/gate/draw.rs b/crates/ui/src/gate/draw.rs index 9bd8a1e07..997a37fff 100644 --- a/crates/ui/src/gate/draw.rs +++ b/crates/ui/src/gate/draw.rs @@ -35,9 +35,7 @@ pub fn show( let height_id = ui.scope_id().with("gate-height"); let height: f32 = ui.data(|data| data.get_temp(height_id)).unwrap_or(0.0); let width = 420.0_f32.min(ui.available_width() - 2.0 * crate::theme::spacing(ui.ctx()).canvas); - ui.add_space( - ((ui.available_height() - height) / 2.0).max(crate::theme::spacing(ui.ctx()).canvas), - ); + ui.add_space(((ui.available_height() - height) / 2.0).max(crate::theme::spacing(ui.ctx()).canvas)); ui.vertical_centered(|ui| { let shown = egui::Frame::new() .fill(p.bg_2) @@ -89,9 +87,9 @@ pub fn show( fn update_line(ui: &mut Ui, offer: &Offer<'_>, language: Language) -> bool { let p = palette(ui.ctx()); let said = match (offer.status, offer.percent) { - (Status::Installed, _) => Message::new(keys::update::RESTARTING) - .with("app", METADATA.name) - .text(language), + (Status::Installed, _) => { + Message::new(keys::update::RESTARTING).with("app", METADATA.name).text(language) + } (Status::Installing, Some(percent)) => Message::new(keys::update::DOWNLOADING_PERCENT) .with("percent", percent) .text(language), @@ -102,8 +100,7 @@ fn update_line(ui: &mut Ui, offer: &Offer<'_>, language: Language) -> bool { .text(language), }; let top = ui.cursor().top(); - ui.painter() - .hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); ui.add_space(gap::TIGHT); // A row of the button's height: `horizontal` centres on egui's smaller default. let row = Vec2::new(ui.available_width(), widgets::MIN_TARGET + gap::TIGHT); @@ -126,13 +123,7 @@ fn update_line(ui: &mut Ui, offer: &Offer<'_>, language: Language) -> bool { } /// Which library the panel is about, above what it asks: several can be asked for here. -fn library( - ui: &mut Ui, - gate: &Gate, - view: &mut GateView, - language: Language, - actions: &mut Vec, -) { +fn library(ui: &mut Ui, gate: &Gate, view: &mut GateView, language: Language, actions: &mut Vec) { let Some(registry) = gate.registry() else { return; }; @@ -141,13 +132,11 @@ fn library( let names: Vec = registry .libraries .iter() - .map(|entry| { - if entry.name.trim().is_empty() { - unnamed.clone() - } else { - entry.name.trim().to_string() - } - }) + .map( + |entry| { + if entry.name.trim().is_empty() { unnamed.clone() } else { entry.name.trim().to_string() } + }, + ) .collect(); let open = registry .open @@ -157,17 +146,12 @@ fn library( return; }; let row = ui.horizontal(|ui| { - ui.label(small( - &i18n::translate(language, keys::vault::LIBRARY, &[]), - p.text_2, - )); + ui.label(small(&i18n::translate(language, keys::vault::LIBRARY, &[]), p.text_2)); if names.len() > 1 { - let options: Vec<(usize, &str)> = - names.iter().map(String::as_str).enumerate().collect(); + let options: Vec<(usize, &str)> = names.iter().map(String::as_str).enumerate().collect(); let mut chosen = open; let label = i18n::translate(language, keys::vault::SWITCH_LIBRARY, &[]); - let response = - ChoiceMenu::new(&label, "vault-library-switch", &options).show(ui, &mut chosen); + let response = ChoiceMenu::new(&label, "vault-library-switch", &options).show(ui, &mut chosen); if response.changed() { view.switch_to = Some(chosen); actions.push(Action::SwitchLibrary); @@ -183,40 +167,16 @@ fn library( }); widgets::address(ui, &row.response, "vault-library"); let line = ui.max_rect().x_range(); - ui.painter().hline( - line, - row.response.rect.bottom() + 6.0, - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .hline(line, row.response.rect.bottom() + 6.0, Stroke::new(1.0, p.line_soft)); } -fn form( - ui: &mut Ui, - gate: &Gate, - view: &mut GateView, - language: Language, - actions: &mut Vec, -) { +fn form(ui: &mut Ui, gate: &Gate, view: &mut GateView, language: Language, actions: &mut Vec) { let p = palette(ui.ctx()); let tr = |key: Key| i18n::translate(language, key, &[]); let creating = gate.is_creating(); - title( - ui, - &tr(if creating { - keys::vault::CREATE_TITLE - } else { - keys::vault::UNLOCK_TITLE - }), - ); - lead( - ui, - &tr(if creating { - keys::vault::CREATE_LEAD - } else { - keys::vault::UNLOCK_LEAD - }), - p.text_2, - ); + title(ui, &tr(if creating { keys::vault::CREATE_TITLE } else { keys::vault::UNLOCK_TITLE })); + lead(ui, &tr(if creating { keys::vault::CREATE_LEAD } else { keys::vault::UNLOCK_LEAD }), p.text_2); if creating { lead(ui, &tr(keys::vault::NO_RECOVERY), p.amber_text); } @@ -249,16 +209,9 @@ fn form( actions.push(Action::Submit); } if creating { - let hint = i18n::translate( - language, - keys::vault::TOO_SHORT, - &[("length", MINIMUM_LENGTH.into())], - ); - let colour = if gate.too_short(view) { - p.red - } else { - p.text_2 - }; + let hint = + i18n::translate(language, keys::vault::TOO_SHORT, &[("length", MINIMUM_LENGTH.into())]); + let colour = if gate.too_short(view) { p.red } else { p.text_2 }; let shown = ui.label(small(&hint, colour)); widgets::address(ui, &shown, "vault-minimum"); } @@ -269,11 +222,10 @@ fn form( ui.spacing_mut().item_spacing.y = gap::SNUG; let name = tr(keys::vault::CONFIRMATION); ui.label(small(&name, p.text_2)); - let (_, typed) = - PassphraseField::new(&mut view.confirmation, &name, "vault-confirmation") - .revealed(view.revealed) - .enabled(!gate.is_working()) - .show(ui); + let (_, typed) = PassphraseField::new(&mut view.confirmation, &name, "vault-confirmation") + .revealed(view.revealed) + .enabled(!gate.is_working()) + .show(ui); if typed.submitted { actions.push(Action::Submit); } @@ -284,13 +236,7 @@ fn form( } /// The problem of the moment, the button, and the way out for a phrase forgotten. -fn submit( - ui: &mut Ui, - gate: &Gate, - view: &GateView, - language: Language, - actions: &mut Vec, -) { +fn submit(ui: &mut Ui, gate: &Gate, view: &GateView, language: Language, actions: &mut Vec) { let p = palette(ui.ctx()); let tr = |key: Key| i18n::translate(language, key, &[]); let creating = gate.is_creating(); @@ -302,9 +248,7 @@ fn submit( } else { None }; - let said = problem - .map(|message| message.text(language)) - .unwrap_or_default(); + let said = problem.map(|message| message.text(language)).unwrap_or_default(); let shown = ui.add_sized( Vec2::new(ui.available_width(), 17.0), egui::Label::new(RichText::new(said).size(font::LABEL).color(p.red)), @@ -354,20 +298,12 @@ fn set_aside( actions: &mut Vec, ) { let p = palette(ui.ctx()); - let panel = if heading == keys::vault::DAMAGED_TITLE { - "vault-damaged" - } else { - "vault-key-missing" - }; + let panel = if heading == keys::vault::DAMAGED_TITLE { "vault-damaged" } else { "vault-key-missing" }; let response = title(ui, &tr(heading)); widgets::address(ui, &response, panel); lead(ui, &tr(said), p.text_2); lead(ui, &tr(note), p.amber_text); - let label = if gate.is_working() { - keys::vault::WORKING - } else { - keys::vault::DAMAGED_ACTION - }; + let label = if gate.is_working() { keys::vault::WORKING } else { keys::vault::DAMAGED_ACTION }; if Button::new(&tr(label), "vault-set-aside") .kind(Kind::Filled) .large() @@ -393,11 +329,7 @@ fn archive(ui: &mut Ui, gate: &Gate, tr: &dyn Fn(Key) -> String, actions: &mut V { actions.push(Action::KeepTrying); } - let label = if gate.is_working() { - keys::vault::WORKING - } else { - keys::vault::FORGOTTEN_ACTION - }; + let label = if gate.is_working() { keys::vault::WORKING } else { keys::vault::FORGOTTEN_ACTION }; // Red text and a hairline, never the amber fill: this one loses the notes. if Button::new(&tr(label), "vault-archive-confirm") .kind(Kind::Destructive) diff --git a/crates/ui/src/gate/mod.rs b/crates/ui/src/gate/mod.rs index 20de3b5d8..e59812d9e 100644 --- a/crates/ui/src/gate/mod.rs +++ b/crates/ui/src/gate/mod.rs @@ -114,15 +114,11 @@ impl Gate { /// The floor holds only when a phrase is chosen, never when one is given back. pub fn too_short(&self, view: &GateView) -> bool { - self.is_creating() - && !view.passphrase.is_empty() - && length(&view.passphrase) < MINIMUM_LENGTH + self.is_creating() && !view.passphrase.is_empty() && length(&view.passphrase) < MINIMUM_LENGTH } pub fn mismatched(&self, view: &GateView) -> bool { - self.is_creating() - && !view.confirmation.is_empty() - && *view.confirmation != *view.passphrase + self.is_creating() && !view.confirmation.is_empty() && *view.confirmation != *view.passphrase } pub fn can_submit(&self, view: &GateView) -> bool { @@ -130,8 +126,7 @@ impl Gate { return false; } !self.is_creating() - || (length(&view.passphrase) >= MINIMUM_LENGTH - && *view.confirmation == *view.passphrase) + || (length(&view.passphrase) >= MINIMUM_LENGTH && *view.confirmation == *view.passphrase) } /// The answers that arrived. `true` when a library was just opened, or another chosen: the @@ -280,16 +275,10 @@ impl Gate { } Action::KeepTrying => self.confirming_archive = false, Action::Archive => { - self.work = Some(Work::Moving( - api::vault::archive(backend), - keys::vault::ARCHIVED, - )); + self.work = Some(Work::Moving(api::vault::archive(backend), keys::vault::ARCHIVED)); } Action::SetAside => { - self.work = Some(Work::Moving( - api::vault::set_aside(backend), - keys::vault::SET_ASIDE, - )); + self.work = Some(Work::Moving(api::vault::set_aside(backend), keys::vault::SET_ASIDE)); } Action::SwitchLibrary => { let id = view diff --git a/crates/ui/src/gate/passphrase.rs b/crates/ui/src/gate/passphrase.rs index ea3b331d8..7607d6da3 100644 --- a/crates/ui/src/gate/passphrase.rs +++ b/crates/ui/src/gate/passphrase.rs @@ -4,8 +4,7 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - CornerRadius, Event, FontFamily, Key, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, - WidgetInfo, + CornerRadius, Event, FontFamily, Key, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, }; use zeroize::Zeroizing; @@ -32,14 +31,7 @@ pub struct Typed { impl<'a> PassphraseField<'a> { pub fn new(value: &'a mut Zeroizing, name: &'a str, author_id: &'a str) -> Self { - Self { - value, - name, - author_id, - revealed: false, - invalid: false, - enabled: true, - } + Self { value, name, author_id, revealed: false, invalid: false, enabled: true } } #[must_use] @@ -67,11 +59,7 @@ impl<'a> PassphraseField<'a> { let response = widgets::interact( ui, Vec2::new(ui.available_width(), height), - if self.enabled { - Sense::click() - } else { - Sense::hover() - }, + if self.enabled { Sense::click() } else { Sense::hover() }, self.author_id, || WidgetInfo::labeled(Role::PasswordInput, true, name), CornerRadius::same(radius::MENU), @@ -97,25 +85,13 @@ impl<'a> PassphraseField<'a> { StrokeKind::Inside, ); let count = self.value.chars().count(); - let shown: Zeroizing = if self.revealed { - self.value.clone() - } else { - Zeroizing::new("•".repeat(count)) - }; - let galley = widgets::text( - ui, - &shown, - font::SUBTITLE, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let shown: Zeroizing = + if self.revealed { self.value.clone() } else { Zeroizing::new("•".repeat(count)) }; + let galley = widgets::text(ui, &shown, font::SUBTITLE, 400.0, FontFamily::Proportional, p.text_0); let inner = response.rect - gap::margin(gap::INSET, gap::CONTROLS); let at = egui::pos2(inner.left(), inner.center().y - galley.size().y / 2.0); let caret_x = at.x + galley.size().x + 1.0; - ui.painter() - .with_clip_rect(inner) - .galley(at, galley, p.text_0); + ui.painter().with_clip_rect(inner).galley(at, galley, p.text_0); if response.has_focus() { ui.painter().vline( caret_x, @@ -134,24 +110,14 @@ fn edit(ui: &Ui, value: &mut Zeroizing) -> Typed { ui.input_mut(|input| { input.events.retain(|event| { match event { - Event::Text(text) - | Event::Paste(text) - | Event::Ime(egui::ImeEvent::Commit(text)) => { + Event::Text(text) | Event::Paste(text) | Event::Ime(egui::ImeEvent::Commit(text)) => { value.push_str(text); typed.changed = true; } - Event::Key { - key: Key::Backspace, - pressed: true, - .. - } => { + Event::Key { key: Key::Backspace, pressed: true, .. } => { typed.changed |= value.pop().is_some(); } - Event::Key { - key: Key::Enter, - pressed: true, - .. - } => typed.submitted = true, + Event::Key { key: Key::Enter, pressed: true, .. } => typed.submitted = true, _ => return true, } false @@ -181,8 +147,7 @@ mod tests { fn form() -> egui_kittest::Harness<'static, Form> { crate::testing::harness().build_ui_state( |ui, form: &mut Form| { - let (_, typed) = - PassphraseField::new(&mut form.phrase, "Phrase", "phrase").show(ui); + let (_, typed) = PassphraseField::new(&mut form.phrase, "Phrase", "phrase").show(ui); form.submitted |= typed.submitted; }, Form::default(), @@ -193,9 +158,7 @@ mod tests { fn typed_letters_go_to_the_secret_and_nowhere_else() { let mut harness = form(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("phrase")) - .click(); + harness.get_by(|node| node.author_id() == Some("phrase")).click(); harness.run(); harness @@ -218,9 +181,7 @@ mod tests { let mut harness = form(); harness.input_mut().focused = false; harness.run(); - harness - .get_by(|node| node.author_id() == Some("phrase")) - .click(); + harness.get_by(|node| node.author_id() == Some("phrase")).click(); harness.run(); harness diff --git a/crates/ui/src/gate/prompt.rs b/crates/ui/src/gate/prompt.rs index 9f2e54683..e9402d401 100644 --- a/crates/ui/src/gate/prompt.rs +++ b/crates/ui/src/gate/prompt.rs @@ -66,23 +66,14 @@ pub fn show( language: Language, ) -> Option { let cross = i18n::translate(language, i18n::keys::dialog::CLOSE, &[]); - let shown = widgets::dialog( - ctx, - stack, - (id(), (&cross, "passphrase-prompt-cross")), - WIDTH, - |ui| body(ui, request, view, language), - )?; + let shown = widgets::dialog(ctx, stack, (id(), (&cross, "passphrase-prompt-cross")), WIDTH, |ui| { + body(ui, request, view, language) + })?; let dismissed = shown.should_close() && !request.working; shown.inner.or(dismissed.then_some(Answer::Cancel)) } -fn body( - ui: &mut Ui, - request: &Request, - view: &mut PromptView, - language: Language, -) -> Option { +fn body(ui: &mut Ui, request: &Request, view: &mut PromptView, language: Language) -> Option { let p = palette(ui.ctx()); let tr = |key: Key| i18n::translate(language, key, &[]); let protecting = request.purpose == Purpose::Protect; @@ -99,9 +90,7 @@ fn body( .color(p.text_0), ); widgets::address(ui, &heading, "passphrase-prompt"); - let said = Message::new(lead) - .with("path", request.file_name.as_str()) - .text(language); + let said = Message::new(lead).with("path", request.file_name.as_str()).text(language); ui.label(RichText::new(said).size(font::LABEL).color(p.text_2)); if protecting { ui.label( @@ -112,36 +101,27 @@ fn body( } let name = tr(keys::vault::PASSPHRASE); ui.label(RichText::new(&name).size(font::META).color(p.text_2)); - let (field, typed) = - PassphraseField::new(&mut view.passphrase, &name, "passphrase-prompt-field") - .invalid(request.refused) - .enabled(!request.working) - .show(ui); + let (field, typed) = PassphraseField::new(&mut view.passphrase, &name, "passphrase-prompt-field") + .invalid(request.refused) + .enabled(!request.working) + .show(ui); if !request.working && ui.memory(|memory| memory.focused().is_none()) { field.request_focus(); } let mut submitted = typed.submitted; if protecting { let confirmation = tr(keys::vault::CONFIRMATION); - ui.label( - RichText::new(&confirmation) - .size(font::META) - .color(p.text_2), - ); - submitted |= PassphraseField::new( - &mut view.confirmation, - &confirmation, - "passphrase-prompt-confirmation", - ) - .enabled(!request.working) - .show(ui) - .1 - .submitted; + ui.label(RichText::new(&confirmation).size(font::META).color(p.text_2)); + submitted |= + PassphraseField::new(&mut view.confirmation, &confirmation, "passphrase-prompt-confirmation") + .enabled(!request.working) + .show(ui) + .1 + .submitted; } let problem = if request.refused { tr(keys::errors::WRONG_PASSPHRASE) - } else if protecting && !view.confirmation.is_empty() && *view.confirmation != *view.passphrase - { + } else if protecting && !view.confirmation.is_empty() && *view.confirmation != *view.passphrase { tr(keys::vault::MISMATCHED) } else { String::new() @@ -191,12 +171,7 @@ mod tests { use super::*; fn request(purpose: Purpose) -> Request { - Request { - purpose, - file_name: "notes.devnotes".to_string(), - refused: false, - working: false, - } + Request { purpose, file_name: "notes.devnotes".to_string(), refused: false, working: false } } fn view(passphrase: &str, confirmation: &str) -> PromptView { @@ -211,14 +186,8 @@ mod tests { let protect = request(Purpose::Protect); assert!(!can_submit(&protect, &view("short", "short"))); - assert!(!can_submit( - &protect, - &view("long enough phrase", "long enough frase") - )); - assert!(can_submit( - &protect, - &view("long enough phrase", "long enough phrase") - )); + assert!(!can_submit(&protect, &view("long enough phrase", "long enough frase"))); + assert!(can_submit(&protect, &view("long enough phrase", "long enough phrase"))); } #[test] @@ -231,23 +200,17 @@ mod tests { fn the_prompt_draws_over_everything_and_answers_its_phrase() { use egui_kittest::kittest::Queryable; - let mut harness = crate::testing::harness() - .with_size(egui::vec2(800.0, 600.0)) - .build_ui_state( - |ui, (stack, view, answered): &mut (DialogStack, PromptView, Option)| { - stack.open(widgets::Layer::Passphrase, id(), None); - if let Some(Answer::Phrase(phrase)) = show( - ui.ctx(), - stack, - &request(Purpose::Unlock), - view, - Language::En, - ) { - *answered = Some(phrase.to_string()); - } - }, - (DialogStack::default(), PromptView::default(), None), - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, (stack, view, answered): &mut (DialogStack, PromptView, Option)| { + stack.open(widgets::Layer::Passphrase, id(), None); + if let Some(Answer::Phrase(phrase)) = + show(ui.ctx(), stack, &request(Purpose::Unlock), view, Language::En) + { + *answered = Some(phrase.to_string()); + } + }, + (DialogStack::default(), PromptView::default(), None), + ); harness.run(); harness .get_by(|node| node.author_id() == Some("passphrase-prompt-field")) diff --git a/crates/ui/src/gate/tests.rs b/crates/ui/src/gate/tests.rs index 2c0b75099..9a39502b3 100644 --- a/crates/ui/src/gate/tests.rs +++ b/crates/ui/src/gate/tests.rs @@ -21,34 +21,24 @@ fn screen(backend: Backend, profile: tempfile::TempDir) -> Harness<'static, Scre let mut gate = Gate::default(); gate.ask(&backend); backend.settle(); - testing::harness() - .with_size(egui::vec2(900.0, 700.0)) - .build_ui_state( - |ui, screen: &mut Screen| { - screen - .gate - .update(&screen.backend, &mut screen.status, &mut screen.errors); - let mut asked = Vec::new(); - show( - ui, - &screen.gate, - &mut screen.view, - (Language::En, None), - &mut asked, - ); - for action in asked { - screen.gate.apply(action, &mut screen.view, &screen.backend); - } - }, - Screen { - backend, - _profile: profile, - gate, - view: GateView::default(), - status: StatusNotifier::default(), - errors: ErrorNotifier::default(), - }, - ) + testing::harness().with_size(egui::vec2(900.0, 700.0)).build_ui_state( + |ui, screen: &mut Screen| { + screen.gate.update(&screen.backend, &mut screen.status, &mut screen.errors); + let mut asked = Vec::new(); + show(ui, &screen.gate, &mut screen.view, (Language::En, None), &mut asked); + for action in asked { + screen.gate.apply(action, &mut screen.view, &screen.backend); + } + }, + Screen { + backend, + _profile: profile, + gate, + view: GateView::default(), + status: StatusNotifier::default(), + errors: ErrorNotifier::default(), + }, + ) } fn node<'a>(harness: &'a Harness<'_, Screen>, author_id: &'a str) -> egui_kittest::Node<'a> { @@ -56,9 +46,7 @@ fn node<'a>(harness: &'a Harness<'_, Screen>, author_id: &'a str) -> egui_kittes } fn present(harness: &Harness<'_, Screen>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } fn type_into(harness: &mut Harness<'_, Screen>, author_id: &str, words: &str) { @@ -79,42 +67,23 @@ fn a_first_launch_asks_for_a_phrase_twice_and_holds_it_to_twelve_characters() { harness.run(); assert!(present(&harness, "vault-confirmation")); - assert!( - !present(&harness, "vault-forgotten"), - "a fresh library has nothing to forget" - ); + assert!(!present(&harness, "vault-forgotten"), "a fresh library has nothing to forget"); type_into(&mut harness, "vault-passphrase", "too short"); type_into(&mut harness, "vault-confirmation", "too short"); - assert!( - node(&harness, "vault-submit") - .accesskit_node() - .is_disabled() - ); + assert!(node(&harness, "vault-submit").accesskit_node().is_disabled()); type_into(&mut harness, "vault-passphrase", " no more"); - assert!( - node(&harness, "vault-submit") - .accesskit_node() - .is_disabled(), - "the two differ" - ); + assert!(node(&harness, "vault-submit").accesskit_node().is_disabled(), "the two differ"); type_into(&mut harness, "vault-confirmation", " no more"); - assert!( - !node(&harness, "vault-submit") - .accesskit_node() - .is_disabled() - ); + assert!(!node(&harness, "vault-submit").accesskit_node().is_disabled()); node(&harness, "vault-submit").click(); harness.run(); settle(&mut harness); assert!(harness.state().gate.is_open()); - assert!( - harness.state().view.passphrase.is_empty(), - "nothing typed is kept" - ); + assert!(harness.state().view.passphrase.is_empty(), "nothing typed is kept"); } #[test] @@ -127,45 +96,135 @@ fn the_pointer_over_the_phrase_is_the_i_beam() { harness.event(egui::Event::PointerMoved(phrase)); harness.run(); - assert_eq!( - harness.output().platform_output.cursor_icon, - egui::CursorIcon::Text - ); + assert_eq!(harness.output().platform_output.cursor_icon, egui::CursorIcon::Text); } -#[test] -fn an_unlock_takes_any_length_and_says_when_the_phrase_is_wrong() { +/// A library locked on the profile, and the gate over it. +fn locked() -> Harness<'static, Screen> { let profile = testing::locked(); let backend = testing::backend_on(profile.path()); let mut harness = screen(backend, profile); harness.run(); + harness +} + +fn unlock(harness: &mut Harness<'_, Screen>, phrase: &str) { + type_into(harness, "vault-passphrase", phrase); + harness.key_press(Key::Enter); + harness.run(); + settle(harness); +} +/// The floor is for a phrase being chosen. +#[test] +fn an_unlock_takes_a_phrase_of_any_length() { + let mut harness = locked(); assert!(!present(&harness, "vault-confirmation")); - assert!(present(&harness, "vault-forgotten")); type_into(&mut harness, "vault-passphrase", "short"); - assert!( - !node(&harness, "vault-submit") - .accesskit_node() - .is_disabled(), - "no floor to unlock" - ); - harness.key_press(Key::Enter); - harness.run(); - settle(&mut harness); + let submit = node(&harness, "vault-submit"); + assert!(!submit.accesskit_node().is_disabled()); +} + +#[test] +fn a_wrong_phrase_is_said_and_the_right_one_opens() { + let mut harness = locked(); + unlock(&mut harness, "short"); assert!(harness.state().gate.refused); let problem = node(&harness, "vault-problem").accesskit_node(); - let said = problem - .label() - .or_else(|| problem.value()) - .unwrap_or_default(); + let said = problem.label().or_else(|| problem.value()).unwrap_or_default(); assert!(said.contains("passphrase"), "{said:?}"); - type_into(&mut harness, "vault-passphrase", testing::PASSPHRASE); - harness.key_press(Key::Enter); + unlock(&mut harness, testing::PASSPHRASE); + assert!(harness.state().gate.is_open()); +} + +#[test] +fn the_phrase_is_shown_while_it_is_asked_and_hidden_again() { + let mut harness = locked(); + type_into(&mut harness, "vault-passphrase", "short"); + let shown = + |harness: &Harness<'_, Screen>| testing::painted(harness).iter().any(|text| text.contains("short")); + assert!(!shown(&harness)); + + node(&harness, "vault-reveal").click(); + harness.run(); + assert!(shown(&harness)); + node(&harness, "vault-reveal").click(); harness.run(); + assert!(!shown(&harness)); +} + +/// The library's folder, as the core made it. +fn library_files(profile: &std::path::Path) -> Vec { + let mut folders = vec![profile.to_owned()]; + let mut files = Vec::new(); + while let Some(folder) = folders.pop() { + for entry in std::fs::read_dir(folder).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + folders.push(path); + } else { + files.push(path); + } + } + } + files +} + +fn file_named(profile: &std::path::Path, ending: &str) -> std::path::PathBuf { + let files = library_files(profile); + let found = files.iter().find(|file| file.to_string_lossy().ends_with(ending)); + found.unwrap_or_else(|| panic!("no {ending} in {files:?}")).clone() +} + +/// Nothing can be typed that would open it: it is set aside, and a new one begun. +#[test] +fn a_library_whose_key_is_missing_is_set_aside() { + let profile = testing::locked(); + std::fs::remove_file(file_named(profile.path(), "vault.json")).unwrap(); + let backend = testing::backend_on(profile.path()); + let mut harness = screen(backend, profile); settle(&mut harness); - assert!(harness.state().gate.is_open()); + assert!(present(&harness, "vault-key-missing")); + assert!(!present(&harness, "vault-passphrase")); + + node(&harness, "vault-set-aside").click(); + settle(&mut harness); + assert!(present(&harness, "vault-confirmation"), "a new library begins"); + assert!(harness.state().status.latest().is_some(), "where the old one is"); + assert!(harness.state().errors.notice().is_none()); +} + +#[test] +fn a_damaged_library_is_set_aside_and_its_phrase_opens_a_new_one() { + let profile = testing::locked(); + let file = file_named(profile.path(), "devnotes.sqlite3"); + let mut bytes = std::fs::read(&file).unwrap(); + for byte in bytes.iter_mut().skip(100) { + *byte = 0x5a; + } + std::fs::write(&file, bytes).unwrap(); + let backend = testing::backend_on(profile.path()); + let mut harness = screen(backend, profile); + settle(&mut harness); + unlock(&mut harness, testing::PASSPHRASE); + assert!(present(&harness, "vault-damaged")); + assert!(!present(&harness, "vault-passphrase")); + harness.run(); + + node(&harness, "vault-set-aside").click(); + settle(&mut harness); + assert!(harness.state().status.latest().is_some(), "where it is"); + unlock(&mut harness, testing::PASSPHRASE); + assert!(harness.state().gate.is_open(), "its phrase opens the new one"); +} + +#[test] +fn one_library_offers_no_other_to_open() { + let harness = locked(); + + assert!(!present(&harness, "vault-library-switch")); } #[test] @@ -206,9 +265,7 @@ fn archiving_a_forgotten_library_says_where_and_starts_a_new_one() { fn opening_another_library_asks_for_its_own_phrase() { let profile = testing::locked(); let backend = testing::backend_on(profile.path()); - let other = engine::libraries::create_library(backend.engine(), "Travail") - .unwrap() - .id; + let other = engine::libraries::create_library(backend.engine(), "Travail").unwrap().id; let mut harness = screen(backend, profile); settle(&mut harness); @@ -223,9 +280,7 @@ fn opening_another_library_asks_for_its_own_phrase() { .position(|entry| entry.id == other) .unwrap(); screen.view.switch_to = Some(rank); - screen - .gate - .apply(Action::SwitchLibrary, &mut screen.view, &screen.backend); + screen.gate.apply(Action::SwitchLibrary, &mut screen.view, &screen.backend); settle(&mut harness); assert!(present(&harness, "vault-confirmation")); diff --git a/crates/ui/src/http/close.rs b/crates/ui/src/http/close.rs index 772db13a6..b5d00adb9 100644 --- a/crates/ui/src/http/close.rs +++ b/crates/ui/src/http/close.rs @@ -22,10 +22,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, actions: &mut Actions) { ui, ( "http-close-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-close-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-close-cross"), ), |ui| { let live = state.http.sockets().is_live(&tab.key); @@ -48,21 +45,12 @@ enum Choice { Save, } -fn body( - ui: &mut Ui, - name: &str, - (modified, live): (bool, bool), - language: i18n::Language, -) -> Option { +fn body(ui: &mut Ui, name: &str, (modified, live): (bool, bool), language: i18n::Language) -> Option { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); ui.set_width(WIDTH.min(ui.ctx().content_rect().width() * 0.9)); ui.spacing_mut().item_spacing.y = gap::INSET; - let title_key = if modified { - keys::http::close::TITLE - } else { - keys::http::close::CONNECTED_TITLE - }; + let title_key = if modified { keys::http::close::TITLE } else { keys::http::close::CONNECTED_TITLE }; let title = i18n::translate(language, title_key, &[("name", name.into())]); crate::widgets::dialog_title(ui, &title, "http-close-dialog"); if modified { @@ -90,11 +78,7 @@ fn body( { chosen = Some(Choice::Save); } - let discard = if modified { - keys::http::close::DISCARD - } else { - keys::http::close::CLOSE - }; + let discard = if modified { keys::http::close::DISCARD } else { keys::http::close::CLOSE }; if Button::new(&tr(discard), "http-close-discard") .kind(Kind::Destructive) .show(ui) diff --git a/crates/ui/src/http/code.rs b/crates/ui/src/http/code.rs index e236238b3..1b535c4c0 100644 --- a/crates/ui/src/http/code.rs +++ b/crates/ui/src/http/code.rs @@ -85,10 +85,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, view: &mut CodeView, actions: &mut ui, ( "http-code-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-code-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-code-cross"), ), |ui| { body(ui, state, (dialog, tab), view, actions); @@ -144,18 +141,9 @@ fn head(ui: &mut Ui, state: &AppState, tab: &Tab) { RequestKind::Websocket => Badge::Websocket, }; let hue = super::badge_hue(ui, badge); - let method = widgets::text( - ui, - badge.short(), - font::META, - 700.0, - FontFamily::Monospace, - hue, - ); + let method = widgets::text(ui, badge.short(), font::META, 700.0, FontFamily::Monospace, hue); ui.label(method); - let name = egui::RichText::new(&tab.draft.name) - .size(font::LABEL) - .color(p.text_1); + let name = egui::RichText::new(&tab.draft.name).size(font::LABEL).color(p.text_1); ui.add(egui::Label::new(name)); }); let active = state.http.environments().active(); @@ -163,16 +151,11 @@ fn head(ui: &mut Ui, state: &AppState, tab: &Tab) { || i18n::translate(language, keys::http::environments::NONE, &[]), |active| active.name.clone(), ); - let dot = active.map_or(p.text_2, |active| { - crate::notes::ui::folder_hue(ui, active.colour) - }); + let dot = active.map_or(p.text_2, |active| crate::notes::ui::folder_hue(ui, active.colour)); let shown = pill(ui, |ui| { let (rect, _) = ui.allocate_exact_size(Vec2::splat(8.0), Sense::hover()); - ui.painter() - .circle_stroke(rect.center(), 3.5, egui::Stroke::new(1.5, dot)); - let words = egui::RichText::new(environment) - .size(font::LABEL) - .color(p.text_1); + ui.painter().circle_stroke(rect.center(), 3.5, egui::Stroke::new(1.5, dot)); + let words = egui::RichText::new(environment).size(font::LABEL).color(p.text_1); ui.add(egui::Label::new(words)); }); widgets::address(ui, &shown, "http-code-environment"); @@ -202,17 +185,13 @@ fn targets( ) { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); - let (label, hint) = ( - tr(keys::http::code::FILTER), - tr(keys::http::code::FILTER_HINT), - ); + let (label, hint) = (tr(keys::http::code::FILTER), tr(keys::http::code::FILTER_HINT)); SearchField::new(&mut view.filter, &label, "http-code-filter") .hint(&hint) .show(ui); let wanted = api::notes::fold(view.filter.trim()); - let matches = |target: CodeTarget| { - wanted.is_empty() || api::notes::fold(&written(target)).contains(&wanted) - }; + let matches = + |target: CodeTarget| wanted.is_empty() || api::notes::fold(&written(target)).contains(&wanted); let mut any = false; egui::ScrollArea::vertical() .id_salt("http-code-targets") @@ -233,10 +212,7 @@ fn targets( } any = true; let title = tr(key).to_uppercase(); - let title = egui::RichText::new(title) - .size(font::CAPTION) - .strong() - .color(p.text_2); + let title = egui::RichText::new(title).size(font::CAPTION).strong().color(p.text_2); ui.add(egui::Label::new(title)); for target in shown { if target_row(ui, target, target == dialog.target()) { @@ -268,11 +244,9 @@ fn target_row(ui: &mut Ui, target: CodeTarget, on: bool) -> bool { let rect = response.rect; if on { let tint = p.amber_fill.gamma_multiply(0.15); - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::CONTROL), tint); + ui.painter().rect_filled(rect, CornerRadius::same(radius::CONTROL), tint); } else if response.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_2); + ui.painter().rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_2); } let (name, library, _) = entry(target); let ink = if on { p.amber_text } else { p.text_0 }; @@ -296,9 +270,7 @@ fn switch(ui: &mut Ui, (on, enabled): (bool, bool), label: &str, author_id: &str let mut checked = on; let changed = widgets::switch(ui, label, author_id, &mut checked, enabled).changed(); let ink = if enabled { p.text_1 } else { p.text_2 }; - ui.add(egui::Label::new( - egui::RichText::new(label).size(font::BODY).color(ink), - )); + ui.add(egui::Label::new(egui::RichText::new(label).size(font::BODY).color(ink))); changed } @@ -317,12 +289,7 @@ fn switches(ui: &mut Ui, dialog: &CodeDialog, language: i18n::Language, actions: ask(actions, Ask::ToggleSecrets); } let on = (options.multiline, shell); - if switch( - ui, - on, - &tr(keys::http::code::MULTILINE), - "http-code-multiline", - ) { + if switch(ui, on, &tr(keys::http::code::MULTILINE), "http-code-multiline") { ask(actions, Ask::Toggle(Switch::Multiline)); } let on = (options.follow_redirects, true); @@ -366,10 +333,7 @@ fn output(ui: &mut Ui, dialog: &CodeDialog, view: &mut CodeView, language: i18n: return; }; let width = ui.available_width(); - let same = view - .shown - .as_ref() - .is_some_and(|(code, _)| *code == generated.code); + let same = view.shown.as_ref().is_some_and(|(code, _)| *code == generated.code); if !same { let syntax = crate::notes::language::syntax(generated.language); let lines = TextLines::new(ui, &generated.code, syntax); @@ -377,8 +341,7 @@ fn output(ui: &mut Ui, dialog: &CodeDialog, view: &mut CodeView, language: i18n: } let (rect, _) = ui.allocate_exact_size(Vec2::new(width, HEIGHT - 110.0), Sense::hover()); let p = palette(ui.ctx()); - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_0); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_0); if let Some((_, lines)) = &mut view.shown { let mut inside = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink(6.0))); lines.show(&mut inside, "http-code-output", true); @@ -440,12 +403,7 @@ fn notes(ui: &mut Ui, dialog: &CodeDialog, generated: &GeneratedCode, language: } } -fn foot( - ui: &mut Ui, - (dialog, tab): (&CodeDialog, &Tab), - language: i18n::Language, - actions: &mut Actions, -) { +fn foot(ui: &mut Ui, (dialog, tab): (&CodeDialog, &Tab), language: i18n::Language, actions: &mut Actions) { let tr = |key| i18n::translate(language, key, &[]); let p = palette(ui.ctx()); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { @@ -470,10 +428,7 @@ fn foot( let title = i18n::translate( language, keys::http::code::NOTE_TITLE, - &[ - ("name", name.as_str().into()), - ("target", entry(dialog.target()).0.into()), - ], + &[("name", name.as_str().into()), ("target", entry(dialog.target()).0.into())], ); let asked = NoteAsked { warning: None, diff --git a/crates/ui/src/http/code_tests.rs b/crates/ui/src/http/code_tests.rs index f21f2de2f..b39e70db8 100644 --- a/crates/ui/src/http/code_tests.rs +++ b/crates/ui/src/http/code_tests.rs @@ -29,15 +29,11 @@ fn dialog() -> Harness<'static, Bench> { let tabs = harness.state_mut().state.http.tabs_mut(); let key = tabs.active().unwrap().key.clone(); tabs.edit(&key, |draft| { - draft.apply(DraftEdit::Auth(RequestAuth::Bearer { - token: "{{token}}".to_owned(), - })); + draft.apply(DraftEdit::Auth(RequestAuth::Bearer { token: "{{token}}".to_owned() })); }); settle(&mut harness); click_id(&mut harness, "http-code-open"); - until(&mut harness, "the code is written", |harness| { - code_of(harness).contains("api.example.com") - }); + until(&mut harness, "the code is written", |harness| code_of(harness).contains("api.example.com")); rest(&mut harness); harness } @@ -58,19 +54,11 @@ fn the_code_is_rust_s_and_each_target_writes_its_own() { assert!(code_of(&harness).starts_with("curl")); click_named(&mut harness, "http-code-target", "JavaScript · fetch"); - until(&mut harness, "the fetch call", |harness| { - code_of(harness).contains("await fetch(") - }); - assert_eq!( - harness.state().state.http.code().target(), - CodeTarget::Fetch - ); + until(&mut harness, "the fetch call", |harness| code_of(harness).contains("await fetch(")); + assert_eq!(harness.state().state.http.code().target(), CodeTarget::Fetch); let multiline = harness.get_by(|node| node.author_id() == Some("http-code-multiline")); - assert!( - multiline.accesskit_node().is_disabled(), - "a program is laid out on its own" - ); + assert!(multiline.accesskit_node().is_disabled(), "a program is laid out on its own"); click_id(&mut harness, "http-code-copy"); click_id(&mut harness, "http-code-copy"); @@ -106,15 +94,9 @@ fn secrets_are_written_in_clear_only_after_a_yes() { rest(&mut harness); click_id(&mut harness, "http-code-secrets-yes"); assert!(harness.state().state.http.code().options().include_secrets); - until(&mut harness, "the note says so", |harness| { - has(harness, "http-code-note") - }); + until(&mut harness, "the note says so", |harness| has(harness, "http-code-note")); - harness - .state_mut() - .state - .http - .ask_code(Asked::ToggleSecrets); + harness.state_mut().state.http.ask_code(Asked::ToggleSecrets); settle(&mut harness); assert!(!harness.state().state.http.code().options().include_secrets); assert!(!has(&harness, "http-code-secrets-ask"), "off never asks"); @@ -123,9 +105,7 @@ fn secrets_are_written_in_clear_only_after_a_yes() { /// A draft begun from the empty workspace, some typing in it. fn draft(harness: &mut Harness<'_, Bench>) { click_id(harness, "http-tab-new"); - until(harness, "the draft is open", |harness| { - has(harness, "http-url") - }); + until(harness, "the draft is open", |harness| has(harness, "http-url")); let tabs = harness.state_mut().state.http.tabs_mut(); let key = tabs.active().unwrap().key.clone(); tabs.edit(&key, |draft| { @@ -138,9 +118,7 @@ fn type_field(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { let field = harness.get_by(|node| node.author_id() == Some(author_id)); field.focus(); settle(harness); - harness - .get_by(|node| node.author_id() == Some(author_id)) - .type_text(words); + harness.get_by(|node| node.author_id() == Some(author_id)).type_text(words); settle(harness); } @@ -160,9 +138,7 @@ fn a_draft_s_first_save_makes_the_collection_it_lacks() { type_field(&mut harness, "http-save-collection", "API"); click_id(&mut harness, "http-save-submit"); - until(&mut harness, "the request is in the rail", |harness| { - names(harness, "http-node-name").len() == 2 - }); + until(&mut harness, "the request is in the rail", |harness| names(harness, "http-node-name").len() == 2); assert!(!has(&harness, "http-save-dialog")); let tab = harness.state().state.http.tabs().active().unwrap(); assert_eq!(tab.request_id.as_deref(), Some(tab.key.as_str())); @@ -186,17 +162,7 @@ fn a_draft_is_saved_in_a_place_of_the_tree_and_in_a_folder_it_names() { until(&mut harness, "the folder is in the rail", |harness| { names(harness, "http-node-name").contains(&"Neuf".to_owned()) }); - assert!( - harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .place - .is_some() - ); + assert!(harness.state().state.http.tabs().active().unwrap().place.is_some()); } #[test] @@ -218,13 +184,49 @@ fn closing_a_draft_can_save_it_first_and_the_tab_goes_once_it_is_written() { } fn active_key(harness: &Harness<'_, Bench>) -> String { + harness.state().state.http.tabs().active().unwrap().key.clone() +} + +#[test] +fn each_switch_turns_its_own_option() { + for (switch, of) in [("http-code-resolve", 0), ("http-code-multiline", 1), ("http-code-follow", 2)] { + let mut harness = dialog(); + let options = |harness: &Harness<'_, Bench>| { + let options = harness.state().state.http.code().options(); + [options.resolve_variables, options.multiline, options.follow_redirects] + }; + let before = options(&harness); + click_id(&mut harness, switch); + let after = options(&harness); + for (at, (was, is)) in before.into_iter().zip(after).enumerate() { + assert_eq!(was != is, at == of, "{switch}, option {at}"); + } + } +} + +#[test] +fn what_no_target_is_called_is_said() { + let mut harness = dialog(); + harness.get_by(|node| node.author_id() == Some("http-code-filter")).focus(); + settle(&mut harness); harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .key - .clone() + .get_by(|node| node.author_id() == Some("http-code-filter")) + .type_text("zzz"); + settle(&mut harness); + let none = i18n::translate(i18n::Language::En, i18n::keys::http::code::NO_TARGET, &[]); + + assert!(testing::painted(&harness).contains(&none)); + assert!(!has(&harness, "http-code-target")); +} + +/// Named after the request and the target, in the code's language. +#[test] +fn the_code_is_kept_as_a_note() { + let mut harness = dialog(); + click_id(&mut harness, "http-code-save"); + until(&mut harness, "its form is there", |harness| has(harness, "save-as-note-title")); + let title = harness.get_by(|node| node.author_id() == Some("save-as-note-title")); + let title = title.accesskit_node().value().unwrap_or_default(); + + assert!(title.contains("Login") && title.contains("cURL"), "{title}"); } diff --git a/crates/ui/src/http/console.rs b/crates/ui/src/http/console.rs index e4e522c26..9a03c8880 100644 --- a/crates/ui/src/http/console.rs +++ b/crates/ui/src/http/console.rs @@ -63,8 +63,7 @@ pub(super) fn show( let p = palette(ui.ctx()); let pane = ui.max_rect(); ui.painter().rect_filled(pane, CornerRadius::ZERO, p.bg_1); - ui.painter() - .hline(pane.x_range(), pane.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(pane.x_range(), pane.top(), Stroke::new(1.0, p.line_soft)); if state.http.console().is_open() { unfolded(ui, state, (of, view), actions); } else { @@ -106,35 +105,22 @@ fn folded(ui: &mut Ui, state: &AppState, of: Of<'_>, actions: &mut Actions) { let summary = format!(" {traffic} · {logs}"); job.append(&summary, 0.0, TextFormat::simple(font.clone(), p.text_2)); if errors > 0 { - let said = i18n::translate( - language, - keys::http::console::ERRORS, - &[("count", errors.into())], - ); + let said = i18n::translate(language, keys::http::console::ERRORS, &[("count", errors.into())]); job.append(&format!(" {said}"), 0.0, TextFormat::simple(font, p.red)); } let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); let at = pos2(pane.left() + 20.0, pane.center().y - galley.size().y / 2.0); - let mut over = - ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_size(at, galley.size()))); + let mut over = ui.new_child(egui::UiBuilder::new().max_rect(Rect::from_min_size(at, galley.size()))); let said = over.add(egui::Label::new(galley).selectable(false)); widgets::address(ui, &said, "http-console-summary"); - let glyph = Rect::from_center_size( - pos2(pane.right() - 20.0, pane.center().y), - egui::Vec2::splat(12.0), - ); + let glyph = Rect::from_center_size(pos2(pane.right() - 20.0, pane.center().y), egui::Vec2::splat(12.0)); crate::theme::icons::paint(ui, glyph, Icon::ChevronUp, p.text_2); if response.clicked() { actions.push(Asked::Http(Action::ToggleConsole)); } } -fn unfolded( - ui: &mut Ui, - state: &AppState, - (of, view): (Of<'_>, &mut ConsoleView), - actions: &mut Actions, -) { +fn unfolded(ui: &mut Ui, state: &AppState, (of, view): (Of<'_>, &mut ConsoleView), actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; egui::Frame::new() @@ -172,12 +158,7 @@ fn rows_of<'a>(state: &'a AppState, key: &str, filter: Filter) -> Vec<(&'a Conso rows } -fn head( - ui: &mut Ui, - state: &AppState, - (of, view): (Of<'_>, &mut ConsoleView), - actions: &mut Actions, -) { +fn head(ui: &mut Ui, state: &AppState, (of, view): (Of<'_>, &mut ConsoleView), actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; let tr = |key| i18n::translate(language, key, &[]); @@ -190,11 +171,7 @@ fn head( let said = ui.add(egui::Label::new(title)); widgets::address(ui, &said, "http-console"); for filter in Filter::ALL { - let words = format!( - "{} {}", - tr(filter_name(filter)), - counted(state, of.key, filter) - ); + let words = format!("{} {}", tr(filter_name(filter)), counted(state, of.key, filter)); let id = format!("http-console-filter-{filter:?}").to_lowercase(); if Button::new(&words, &id) .kind(widgets::Kind::Quiet) @@ -243,13 +220,7 @@ fn sentence(line: &ConsoleLine, language: i18n::Language) -> String { use keys::http::console as said; match line { ConsoleLine::Out { method, url, .. } => format!("{method} {url}"), - ConsoleLine::In { - status, - reason, - millis, - size, - .. - } => i18n::translate( + ConsoleLine::In { status, reason, millis, size, .. } => i18n::translate( language, said::IN, &[ @@ -260,23 +231,14 @@ fn sentence(line: &ConsoleLine, language: i18n::Language) -> String { ], ), ConsoleLine::Failed { code, params, .. } => { - let error = engine::error::AppError { - code: *code, - params: params.clone(), - detail: String::new(), - }; + let error = + engine::error::AppError { code: *code, params: params.clone(), detail: String::new() }; crate::services::errors::message_of(&error) .unwrap_or_else(|| i18n::Message::new(keys::http::send::FAILED)) .text(language) } ConsoleLine::Log { text, .. } => text.clone(), - ConsoleLine::Test { - name, - expected, - actual, - message, - .. - } => { + ConsoleLine::Test { name, expected, actual, message, .. } => { if expected.is_some() || actual.is_some() { i18n::translate( language, @@ -302,10 +264,7 @@ fn sentence(line: &ConsoleLine, language: i18n::Language) -> String { ConsoleLine::Missed { path, variable } => i18n::translate( language, said::MISSED, - &[ - ("path", path.as_str().into()), - ("variable", variable.as_str().into()), - ], + &[("path", path.as_str().into()), ("variable", variable.as_str().into())], ), } } @@ -327,10 +286,8 @@ fn origin(event: &ConsoleEvent, of: Of<'_>, language: i18n::Language) -> String use keys::http::console::origins; let line = &event.line; if let Some(by) = by_of(line) { - let traffic = matches!( - line, - ConsoleLine::Out { .. } | ConsoleLine::In { .. } | ConsoleLine::Failed { .. } - ); + let traffic = + matches!(line, ConsoleLine::Out { .. } | ConsoleLine::In { .. } | ConsoleLine::Failed { .. }); let key = match by.kind { _ if traffic => origins::SENT, ScriptKind::Before => origins::BEFORE, @@ -339,11 +296,7 @@ fn origin(event: &ConsoleEvent, of: Of<'_>, language: i18n::Language) -> String }; return i18n::translate(language, key, &[("name", by.name.as_str().into())]); } - let name = if event.request.is_empty() { - of.name - } else { - event.request.as_str() - }; + let name = if event.request.is_empty() { of.name } else { event.request.as_str() }; i18n::translate(language, origins::REQUEST, &[("name", name.into())]) } @@ -390,36 +343,18 @@ fn row(ui: &mut Ui, (event, headers): (&ConsoleEvent, bool), of: Of<'_>, languag sentence(line, language) }; response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); - let id = if headers { - "http-console-sub" - } else { - "http-console-line" - }; + let id = if headers { "http-console-sub" } else { "http-console-line" }; widgets::address(ui, &response, id); let middle = rect.center().y; let mut left = rect.left(); if headers { left += 88.0; } else { - let time = event - .at - .with_timezone(&Local) - .format("%H:%M:%S%.3f") - .to_string(); - let galley = widgets::text( - ui, - &time, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let time = event.at.with_timezone(&Local).format("%H:%M:%S%.3f").to_string(); + let galley = widgets::text(ui, &time, font::META, 400.0, FontFamily::Monospace, p.text_2); left += galley.size().x + 8.0; - ui.painter().galley( - pos2(rect.left(), middle - galley.size().y / 2.0), - galley, - p.text_2, - ); + ui.painter() + .galley(pos2(rect.left(), middle - galley.size().y / 2.0), galley, p.text_2); let glyph = Rect::from_center_size(pos2(left + 6.0, middle), Vec2::splat(12.0)); mark(ui, glyph, line, ink); } @@ -427,19 +362,9 @@ fn row(ui: &mut Ui, (event, headers): (&ConsoleEvent, bool), of: Of<'_>, languag let mut right = rect.right(); if !headers { let from = origin(event, of, language); - let galley = widgets::text( - ui, - &from, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &from, font::META, 400.0, FontFamily::Proportional, p.text_2); right -= galley.size().x + 12.0; - let at = pos2( - rect.right() - galley.size().x, - middle - galley.size().y / 2.0, - ); + let at = pos2(rect.right() - galley.size().x, middle - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_2); } let job = job_of(&words, ink, p); @@ -449,3 +374,6 @@ fn row(ui: &mut Ui, (event, headers): (&ConsoleEvent, bool), of: Of<'_>, languag ui.painter_at(clip).galley(at, galley, ink); widgets::tooltip(response, &words); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/console/tests.rs b/crates/ui/src/http/console/tests.rs new file mode 100644 index 000000000..ea605106d --- /dev/null +++ b/crates/ui/src/http/console/tests.rs @@ -0,0 +1,132 @@ +//! What a line of the console says, who it comes from, and its colour. + +use engine::error::ErrorCode; +use engine::http::scripts::model::{FailureKind, LogLevel, ScriptKind, ScriptLevel, ScriptStop}; +use i18n::Language; + +use super::*; + +fn by(kind: ScriptKind) -> ConsoleOrigin { + ConsoleOrigin { level: ScriptLevel::Collection, kind, name: "API".to_owned() } +} + +fn out(by: Option) -> ConsoleLine { + ConsoleLine::Out { method: "GET".to_owned(), url: "https://a.fr".to_owned(), headers: Vec::new(), by } +} + +fn got(status: u16, by: Option) -> ConsoleLine { + ConsoleLine::In { status, reason: "Why".to_owned(), millis: 12, size: 34, by } +} + +fn failed(code: ErrorCode) -> ConsoleLine { + ConsoleLine::Failed { code, params: std::collections::BTreeMap::default(), by: None } +} + +fn log(text: &str, by: Option) -> ConsoleLine { + ConsoleLine::Log { level: LogLevel::Log, text: text.to_owned(), by } +} + +fn test(expected: Option<&str>, actual: Option<&str>) -> ConsoleLine { + ConsoleLine::Test { + name: "is fast".to_owned(), + expected: expected.map(str::to_owned), + actual: actual.map(str::to_owned), + message: Some("too slow".to_owned()), + by: Some(by(ScriptKind::Tests)), + } +} + +fn stopped() -> ConsoleLine { + ConsoleLine::Stopped { + stop: ScriptStop { + kind: FailureKind::Error, + level: Some(ScriptLevel::Request), + script: None, + name: None, + owner: None, + line: None, + message: "x is not defined".to_owned(), + }, + } +} + +fn missed() -> ConsoleLine { + ConsoleLine::Missed { path: "$.token".to_owned(), variable: "token".to_owned() } +} + +#[test] +fn a_line_says_what_it_has_to_say() { + for (line, holds) in [ + (out(None), vec!["GET https://a.fr"]), + (got(200, None), vec!["200", "Why", "12", "34"]), + (log("hello", None), vec!["hello"]), + (test(Some("1"), Some("2")), vec!["is fast", "1", "2"]), + (test(Some("1"), None), vec!["is fast", "1", "—"]), + (test(None, None), vec!["is fast", "too slow"]), + (stopped(), vec!["x is not defined"]), + (missed(), vec!["$.token", "token"]), + ] { + let words = sentence(&line, Language::En); + assert!(holds.iter().all(|each| words.contains(each)), "{line:?}: {words}"); + } +} + +/// The code's own sentence, or that the send failed. +#[test] +fn a_failure_is_said_by_its_code() { + let timeout = sentence(&failed(ErrorCode::HttpTimeout), Language::En); + let network = sentence(&failed(ErrorCode::HttpNetwork), Language::En); + + assert!(!timeout.is_empty() && !network.is_empty()); + assert_ne!(timeout, network); +} + +/// A script's own request is said as sent by it, whatever phase it is of. +#[test] +fn a_line_is_signed_by_its_script_or_by_the_request() { + let signed = |line: ConsoleLine, request: &str| { + let event = ConsoleEvent { + id: "1".to_owned(), + at: chrono::Utc::now(), + request: request.to_owned(), + iteration: None, + line, + }; + let of = Of { key: "key", name: "Login" }; + origin(&event, of, Language::En) + }; + let scripts: Vec = [ScriptKind::Before, ScriptKind::After, ScriptKind::Tests] + .into_iter() + .map(|kind| signed(log("x", Some(by(kind))), "")) + .collect(); + let sent: Vec = [out(Some(by(ScriptKind::Before))), got(200, Some(by(ScriptKind::Tests)))] + .into_iter() + .map(|line| signed(line, "")) + .collect(); + + assert!(scripts.iter().all(|words| words.contains("API")), "{scripts:?}"); + assert!(scripts[0] != scripts[1] && scripts[1] != scripts[2], "{scripts:?}"); + assert!(sent[0] == sent[1] && !scripts.contains(&sent[0]), "{sent:?}"); + for (line, request, name) in + [(out(None), "", "Login"), (stopped(), "", "Login"), (missed(), "Ping", "Ping")] + { + assert!(signed(line, request).contains(name), "{name}"); + } +} + +#[test] +fn what_went_wrong_is_red() { + let p = palette(&egui::Context::default()); + for (line, ink) in [ + (out(None), p.text_0), + (got(399, None), p.text_0), + (got(400, None), p.red), + (log("x", None), p.text_0), + (failed(ErrorCode::HttpTimeout), p.red), + (test(None, None), p.red), + (stopped(), p.red), + (missed(), p.red), + ] { + assert_eq!(ink_of(&line, p), ink, "{line:?}"); + } +} diff --git a/crates/ui/src/http/container_settings.rs b/crates/ui/src/http/container_settings.rs index 01964fc03..bc92aaa99 100644 --- a/crates/ui/src/http/container_settings.rs +++ b/crates/ui/src/http/container_settings.rs @@ -49,10 +49,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, view: &mut DialogView, actions: &m ui, ( "http-settings-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-settings-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-settings-cross"), ), |ui| { body(ui, state, form, view, actions); @@ -116,10 +113,7 @@ fn body(ui: &mut Ui, state: &AppState, form: &Form, view: &mut DialogView, actio fn heading(ui: &mut Ui, words: &str, hint: Option) { let p = palette(ui.ctx()); ui.horizontal(|ui| { - let title = egui::RichText::new(words) - .size(font::BODY) - .strong() - .color(p.text_1); + let title = egui::RichText::new(words).size(font::BODY).strong().color(p.text_1); ui.add(egui::Label::new(title)); if let Some(hint) = hint { let hint = format!("· {hint}"); @@ -141,63 +135,33 @@ fn fields( let folder = form.container.item.kind == HttpItemKind::Folder; let mut changed = None; let variables = tr(keys::http::settings::VARIABLES); - heading( - ui, - &variables, - Some(tr(keys::http::settings::VARIABLES_HINT)), - ); - let table = variables_table::Table { - kind: "settings", - label: &variables, - }; + heading(ui, &variables, Some(tr(keys::http::settings::VARIABLES_HINT))); + let table = variables_table::Table { kind: "settings", label: &variables }; let rows = &settings.variables; if let Some(variables_table::Changed::Rows(variables)) = variables_table::show(ui, &table, rows, &mut view.secrets_shown, language) { - changed = Some(ContainerSettings { - variables, - ..settings.clone() - }); + changed = Some(ContainerSettings { variables, ..settings.clone() }); } heading(ui, &tr(keys::http::editor::sections::AUTH), None); - let field = auth::AuthField { - auth: &settings.auth, - above: form.above.as_ref(), - allow_inherit: folder, - }; + let field = auth::AuthField { auth: &settings.auth, above: form.above.as_ref(), allow_inherit: folder }; if let Some(auth) = auth::show(ui, &field, &mut view.revealed, language) { - changed = Some(ContainerSettings { - auth, - ..settings.clone() - }); + changed = Some(ContainerSettings { auth, ..settings.clone() }); } let headers = tr(keys::http::editor::sections::HEADERS); heading(ui, &headers, None); - let table = table::Table { - kind: "settings-headers", - label: &headers, - headers: true, - }; + let table = table::Table { kind: "settings-headers", label: &headers, headers: true }; if let Some(headers) = table::show(ui, &table, &settings.headers, language) { - changed = Some(ContainerSettings { - headers, - ..settings.clone() - }); + changed = Some(ContainerSettings { headers, ..settings.clone() }); } heading(ui, &tr(keys::http::editor::sections::SETTINGS), None); let field = transport::TransportField { settings: settings.transport, - base: form - .above - .as_ref() - .map_or_else(Transport::default, |above| above.transport), + base: form.above.as_ref().map_or_else(Transport::default, |above| above.transport), above_is_default: !folder, }; if let Some(transport) = transport::show(ui, &field, &mut view.numbers, language) { - changed = Some(ContainerSettings { - transport, - ..settings.clone() - }); + changed = Some(ContainerSettings { transport, ..settings.clone() }); } let owner = form.container.item.id.as_str(); let scripts_of = |phases: &'static [ScriptKind]| scripts::ScriptsField { @@ -207,31 +171,17 @@ fn fields( above: None, request_name: "", }; - heading( - ui, - &tr(keys::http::editor::sections::SCRIPTS), - Some(tr(keys::http::settings::SCRIPTS_HINT)), - ); + heading(ui, &tr(keys::http::editor::sections::SCRIPTS), Some(tr(keys::http::settings::SCRIPTS_HINT))); let field = scripts_of(&[ScriptKind::Before, ScriptKind::After]); let typed = scripts::show(ui, &field, &mut view.scripts, language, |_, _| {}); if let Some(scripts::Changed::Scripts(scripts)) = typed { - changed = Some(ContainerSettings { - scripts, - ..settings.clone() - }); + changed = Some(ContainerSettings { scripts, ..settings.clone() }); } - heading( - ui, - &tr(keys::http::editor::sections::TESTS), - Some(tr(keys::http::settings::TESTS_HINT)), - ); + heading(ui, &tr(keys::http::editor::sections::TESTS), Some(tr(keys::http::settings::TESTS_HINT))); let field = scripts_of(&[ScriptKind::Tests]); let typed = scripts::show(ui, &field, &mut view.tests, language, |_, _| {}); if let Some(scripts::Changed::Scripts(scripts)) = typed { - changed = Some(ContainerSettings { - scripts, - ..settings.clone() - }); + changed = Some(ContainerSettings { scripts, ..settings.clone() }); } changed } diff --git a/crates/ui/src/http/cookie_jar.rs b/crates/ui/src/http/cookie_jar.rs index 339d72f8a..57ad2c8fb 100644 --- a/crates/ui/src/http/cookie_jar.rs +++ b/crates/ui/src/http/cookie_jar.rs @@ -28,10 +28,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, actions: &mut Actions) { ui, ( "http-cookies-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-cookies-close", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-cookies-close"), ), |ui| { body(ui, state, actions); @@ -84,19 +81,11 @@ fn head(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let cookies = state.http.cookies(); let question = cookies.confirming().map(|count| { - i18n::translate( - language, - keys::http::cookies::CONFIRM, - &[("count", count.into())], - ) + i18n::translate(language, keys::http::cookies::CONFIRM, &[("count", count.into())]) }); let stored = cookies.domains().is_some_and(|it| !it.is_empty()); - let words = ( - &*tr(keys::http::cookies::CLEAR), - &*tr(keys::http::rail::CANCEL), - ); - let pressed = - widgets::ask_in_place(ui, words, question.as_deref(), stored, "http-cookies-clear"); + let words = (&*tr(keys::http::cookies::CLEAR), &*tr(keys::http::rail::CANCEL)); + let pressed = widgets::ask_in_place(ui, words, question.as_deref(), stored, "http-cookies-clear"); match pressed { Some(InPlace::Ask) => ask(actions, Ask::AskClear), Some(InPlace::Cancel) => ask(actions, Ask::CancelClear), @@ -119,14 +108,8 @@ fn section(ui: &mut Ui, domain: &CookieDomain, language: i18n::Language, actions let said = ui.add(egui::Label::new(name)); widgets::address(ui, &said, "http-cookies-domain"); let count = u32::try_from(domain.cookies.len()).unwrap_or(u32::MAX); - let count = i18n::translate( - language, - keys::http::cookies::COUNT, - &[("count", count.into())], - ); - ui.add(egui::Label::new( - egui::RichText::new(count).size(font::LABEL).color(p.text_2), - )); + let count = i18n::translate(language, keys::http::cookies::COUNT, &[("count", count.into())]); + ui.add(egui::Label::new(egui::RichText::new(count).size(font::LABEL).color(p.text_2))); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { let word = tr(keys::http::cookies::REMOVE_DOMAIN); if Button::new(&word, "http-cookies-domain-remove") @@ -149,10 +132,7 @@ fn section(ui: &mut Ui, domain: &CookieDomain, language: i18n::Language, actions keys::http::cookies::EXPIRES, keys::http::cookies::FLAGS, ] { - let words = egui::RichText::new(tr(key)) - .size(font::CONTROL) - .strong() - .color(p.text_2); + let words = egui::RichText::new(tr(key)).size(font::CONTROL).strong().color(p.text_2); ui.add(egui::Label::new(words)); } ui.end_row(); @@ -165,10 +145,7 @@ fn section(ui: &mut Ui, domain: &CookieDomain, language: i18n::Language, actions fn mono(ui: &mut Ui, words: &str, author_id: Option<&str>) { let p = palette(ui.ctx()); - let words = egui::RichText::new(words) - .monospace() - .size(font::LABEL) - .color(p.text_0); + let words = egui::RichText::new(words).monospace().size(font::LABEL).color(p.text_0); let shown = ui.add(egui::Label::new(words).truncate()); if let Some(author_id) = author_id { widgets::address(ui, &shown, author_id); @@ -184,23 +161,13 @@ fn row(ui: &mut Ui, stored: &StoredCookie, language: i18n::Language, actions: &m mono(ui, &cookie.value, None); }); mono(ui, &cookie.path, None); - let expiry = egui::RichText::new(expiry(cookie, language)) - .size(font::LABEL) - .color(p.text_1); + let expiry = egui::RichText::new(expiry(cookie, language)).size(font::LABEL).color(p.text_1); ui.add(egui::Label::new(expiry)); - let flags = egui::RichText::new(flags(cookie, language)) - .size(font::CONTROL) - .color(p.text_2); + let flags = egui::RichText::new(flags(cookie, language)).size(font::CONTROL).color(p.text_2); ui.add(egui::Label::new(flags)); - let label = i18n::translate( - language, - keys::http::cookies::REMOVE_ONE, - &[("name", cookie.name.as_str().into())], - ); - if IconButton::new(Icon::X, &label, "http-cookie-remove") - .show(ui) - .clicked() - { + let label = + i18n::translate(language, keys::http::cookies::REMOVE_ONE, &[("name", cookie.name.as_str().into())]); + if IconButton::new(Icon::X, &label, "http-cookie-remove").show(ui).clicked() { ask(actions, Ask::Remove(stored.id.clone())); } ui.end_row(); @@ -225,11 +192,10 @@ fn flags(cookie: &JarCookie, language: i18n::Language) -> String { flags.push(format!("SameSite={same_site}")); } if cookie.host_only { - flags.push(i18n::translate( - language, - keys::http::cookies::HOST_ONLY, - &[], - )); + flags.push(i18n::translate(language, keys::http::cookies::HOST_ONLY, &[])); } flags.join(" · ") } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/cookie_jar/tests.rs b/crates/ui/src/http/cookie_jar/tests.rs new file mode 100644 index 000000000..c85125b2a --- /dev/null +++ b/crates/ui/src/http/cookie_jar/tests.rs @@ -0,0 +1,44 @@ +//! What a cookie of the jar is said to be. + +use i18n::Language; + +use super::*; + +fn cookie() -> JarCookie { + JarCookie { + name: "session".to_owned(), + value: "abc".to_owned(), + domain: "a.fr".to_owned(), + host_only: false, + path: "/".to_owned(), + expires: None, + secure: false, + http_only: false, + same_site: None, + created: None, + } +} + +#[test] +fn a_cookie_s_flags_are_those_it_was_set_with() { + assert_eq!(flags(&cookie(), Language::En), ""); + let all = JarCookie { + secure: true, + http_only: true, + same_site: Some("Lax".to_owned()), + host_only: true, + ..cookie() + }; + let words = flags(&all, Language::En); + + assert!(words.starts_with("Secure · HttpOnly · SameSite=Lax · "), "{words}"); +} + +#[test] +fn a_cookie_lasts_the_session_or_until_its_date() { + let until = chrono::DateTime::from_timestamp(1_800_000_000, 0); + let dated = JarCookie { expires: until, ..cookie() }; + + assert_eq!(expiry(&dated, Language::En), "2027-01-15 08:00"); + assert_ne!(expiry(&cookie(), Language::En), ""); +} diff --git a/crates/ui/src/http/dialogs_tests.rs b/crates/ui/src/http/dialogs_tests.rs index 3ba4c8158..2e6fb079c 100644 --- a/crates/ui/src/http/dialogs_tests.rs +++ b/crates/ui/src/http/dialogs_tests.rs @@ -24,9 +24,7 @@ fn jar() -> Harness<'static, Bench> { click_id(&mut harness, "http-send"); answered(&mut harness); click_id(&mut harness, "http-cookies-open"); - until(&mut harness, "the jar is read", |harness| { - has(harness, "http-cookie") - }); + until(&mut harness, "the jar is read", |harness| has(harness, "http-cookie")); harness } @@ -37,29 +35,21 @@ fn a_cookie_set_by_an_answer_is_listed_and_removed() { assert!(has(&harness, "http-cookies-domain")); click_id(&mut harness, "http-cookie-remove"); - until(&mut harness, "the jar is empty", |harness| { - has(harness, "http-cookies-empty") - }); + until(&mut harness, "the jar is empty", |harness| has(harness, "http-cookies-empty")); } #[test] fn emptying_the_jar_says_how_many_go_and_cancel_keeps_them() { let mut harness = jar(); click_id(&mut harness, "http-cookies-clear"); - until(&mut harness, "the count is said", |harness| { - has(harness, "http-cookies-clear-count") - }); + until(&mut harness, "the count is said", |harness| has(harness, "http-cookies-clear-count")); click_id(&mut harness, "http-cookies-clear-cancel"); assert!(has(&harness, "http-cookie")); click_id(&mut harness, "http-cookies-clear"); - until(&mut harness, "the count is said", |harness| { - has(harness, "http-cookies-clear-confirm") - }); + until(&mut harness, "the count is said", |harness| has(harness, "http-cookies-clear-confirm")); click_id(&mut harness, "http-cookies-clear-confirm"); - until(&mut harness, "the jar is empty", |harness| { - has(harness, "http-cookies-empty") - }); + until(&mut harness, "the jar is empty", |harness| has(harness, "http-cookies-empty")); click_id(&mut harness, "http-cookies-close"); assert!(!has(&harness, "http-cookies-dialog")); @@ -83,9 +73,7 @@ fn collection_id(harness: &Harness<'_, Bench>) -> String { /// The dialog on a row, at rest: it centres itself again when what it reads changes its height. fn open_settings(harness: &mut Harness<'_, Bench>, row: &str) { choose(harness, row, &["http-node-settings"]); - until(harness, "the settings are read", |harness| { - has(harness, "http-auth-kind") - }); + until(harness, "the settings are read", |harness| has(harness, "http-auth-kind")); let last = std::cell::Cell::new(None); until(harness, "the dialog rests", |harness| { let cancel = harness.get_by(|node| node.author_id() == Some("http-settings-cancel")); @@ -103,23 +91,16 @@ fn a_collection_s_settings_are_written_on_save_and_not_on_cancel() { click_id(&mut harness, "http-auth-kind-2"); click_id(&mut harness, "http-settings-cancel"); let id = collection_id(&harness); - assert_eq!( - settings_of(&harness, HttpItemKind::Collection, id.clone()), - RequestAuth::Inherit - ); + assert_eq!(settings_of(&harness, HttpItemKind::Collection, id.clone()), RequestAuth::Inherit); open_settings(&mut harness, "Paiements"); click_id(&mut harness, "http-auth-kind"); click_id(&mut harness, "http-auth-kind-2"); click_id(&mut harness, "http-settings-save"); - until(&mut harness, "the dialog closes", |harness| { - !has(harness, "http-settings-dialog") - }); + until(&mut harness, "the dialog closes", |harness| !has(harness, "http-settings-dialog")); assert_eq!( settings_of(&harness, HttpItemKind::Collection, id), - RequestAuth::Bearer { - token: String::new() - } + RequestAuth::Bearer { token: String::new() } ); } @@ -135,3 +116,70 @@ fn a_folder_may_inherit_and_a_collection_may_not() { assert!(!has(&harness, "http-auth-kind-4"), "four kinds, no inherit"); assert!(!has(&harness, "http-auth-inherited"), "nothing is above it"); } + +#[test] +fn a_domain_s_cookies_go_together() { + let mut harness = jar(); + click_id(&mut harness, "http-cookies-domain-remove"); + until(&mut harness, "the jar is empty", |harness| has(harness, "http-cookies-empty")); +} + +fn type_first(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { + let first = |harness: &mut Harness<'_, Bench>| { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .unwrap() + .focus(); + }; + first(harness); + settle(harness); + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .unwrap() + .type_text(words); + settle(harness); +} + +fn whole_settings(harness: &Harness<'_, Bench>) -> engine::http::model::ContainerSettings { + let item = HttpItem { kind: HttpItemKind::Collection, id: collection_id(harness) }; + engine::db::run_here(harness.state().backend.engine(), move |engine| { + engine::http::http_settings(engine, &item) + }) + .unwrap() +} + +/// Every part of a container is one form, written by one button. +#[test] +fn each_part_of_a_collection_s_settings_is_written() { + let mut harness = paiements(); + harness.set_size(egui::vec2(1_200.0, 2_600.0)); + open_settings(&mut harness, "Paiements"); + type_first(&mut harness, "http-variable-name", "host"); + type_first(&mut harness, "http-kv-key", "X-Trace"); + type_first(&mut harness, "http-transport-timeoutMs", "900"); + harness.key_press(egui::Key::Tab); + settle(&mut harness); + click_id(&mut harness, "http-settings-save"); + until(&mut harness, "the dialog closes", |harness| !has(harness, "http-settings-dialog")); + + let written = whole_settings(&harness); + assert_eq!(written.variables[0].name, "host"); + assert_eq!(written.headers[0].key, "X-Trace"); + assert_eq!(written.transport.timeout_ms, Some(900)); +} + +#[test] +fn escape_leaves_a_container_as_it_was() { + let mut harness = paiements(); + open_settings(&mut harness, "Paiements"); + click_id(&mut harness, "http-auth-kind"); + click_id(&mut harness, "http-auth-kind-2"); + let before = whole_settings(&harness); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + + assert!(!has(&harness, "http-settings-dialog")); + assert_eq!(whole_settings(&harness), before); +} diff --git a/crates/ui/src/http/environment_picker.rs b/crates/ui/src/http/environment_picker.rs index 52112ec12..e2cfa675b 100644 --- a/crates/ui/src/http/environment_picker.rs +++ b/crates/ui/src/http/environment_picker.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Popup, PopupCloseBehavior, RectAlign, Response, Role, Sense, - Stroke, Ui, Vec2, WidgetInfo, pos2, + Color32, CornerRadius, FontFamily, Popup, PopupCloseBehavior, RectAlign, Response, Role, Sense, Stroke, + Ui, Vec2, WidgetInfo, pos2, }; use engine::http::environments::{Environment, variable_counts}; use i18n::keys; @@ -29,8 +29,7 @@ fn dot(ui: &Ui, at: egui::Pos2, hue: Option) { ui.painter().circle_filled(at, DOT / 2.0, hue); } None => { - ui.painter() - .circle_stroke(at, DOT / 2.0 - 0.5, Stroke::new(1.0, p.text_2)); + ui.painter().circle_stroke(at, DOT / 2.0 - 0.5, Stroke::new(1.0, p.text_2)); } } } @@ -39,14 +38,7 @@ fn dot(ui: &Ui, at: egui::Pos2, hue: Option) { pub(super) fn width(ui: &Ui, state: &AppState) -> f32 { let p = palette(ui.ctx()); let name = active_name(state); - let galley = widgets::text( - ui, - &name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, &name, font::BODY, 400.0, FontFamily::Proportional, p.text_1); galley.size().x + 44.0 } @@ -85,33 +77,14 @@ fn trigger(ui: &mut Ui, state: &AppState) -> Response { corner, ); let rect = response.rect; - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(1.0, p.line_soft), - egui::StrokeKind::Inside, - ); - let hue = state - .http - .environments() - .active() - .map(|active| folder_hue(ui, active.colour)); + ui.painter() + .rect(rect, corner, p.bg_2, Stroke::new(1.0, p.line_soft), egui::StrokeKind::Inside); + let hue = state.http.environments().active().map(|active| folder_hue(ui, active.colour)); dot(ui, pos2(rect.left() + 14.0, rect.center().y), hue); - let galley = widgets::text( - ui, - &name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, &name, font::BODY, 400.0, FontFamily::Proportional, p.text_1); let at = pos2(rect.left() + 24.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_1); - let caret = egui::Rect::from_center_size( - pos2(rect.right() - 12.0, rect.center().y), - Vec2::splat(12.0), - ); + let caret = egui::Rect::from_center_size(pos2(rect.right() - 12.0, rect.center().y), Vec2::splat(12.0)); crate::theme::icons::paint(ui, caret, crate::theme::icons::Icon::ChevronDown, p.text_2); response } @@ -123,14 +96,7 @@ fn panel(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.set_width(PANEL); ui.spacing_mut().item_spacing.y = gap::LINE; let title = tr(keys::http::environments::ACTIVE_TITLE).to_uppercase(); - let galley = widgets::text( - ui, - &title, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &title, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); let (rect, _) = ui.allocate_exact_size(Vec2::new(PANEL, 22.0), Sense::hover()); ui.painter() .galley(pos2(rect.left() + 10.0, rect.top() + 6.0), galley, p.text_2); @@ -159,13 +125,8 @@ fn panel(ui: &mut Ui, state: &AppState, actions: &mut Actions) { } } ui.separator(); - let manage = Entry { - name: &tr(keys::http::environments::MANAGE), - meta: "", - hue: None, - dotted: false, - on: false, - }; + let manage = + Entry { name: &tr(keys::http::environments::MANAGE), meta: "", hue: None, dotted: false, on: false }; if entry_of(ui, &manage, "http-environment-manage").clicked() { actions.push(Asked::Http(Action::ShowPage(Page::Environments))); } @@ -181,11 +142,7 @@ fn meta(environment: &Environment, language: i18n::Language) -> String { return i18n::translate(language, keys::http::environments::PROTECTED_BADGE, &[]); } let count = variable_counts(&environment.variables).count; - i18n::translate( - language, - keys::http::environments::COUNT, - &[("count", count.into())], - ) + i18n::translate(language, keys::http::environments::COUNT, &[("count", count.into())]) } /// An entry of the panel. @@ -214,40 +171,21 @@ fn entry_of(ui: &mut Ui, shown: &Entry<'_>, author_id: &str) -> Response { ); let rect = response.rect; if response.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_3); + ui.painter().rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_3); } let middle = rect.center().y; if shown.on { - let tick = - egui::Rect::from_center_size(pos2(rect.left() + 14.0, middle), Vec2::splat(12.0)); + let tick = egui::Rect::from_center_size(pos2(rect.left() + 14.0, middle), Vec2::splat(12.0)); crate::theme::icons::paint(ui, tick, crate::theme::icons::Icon::Check, p.amber_text); } if shown.dotted { dot(ui, pos2(rect.left() + 32.0, middle), shown.hue); } - let name = widgets::text( - ui, - shown.name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let name = widgets::text(ui, shown.name, font::BODY, 400.0, FontFamily::Proportional, p.text_0); let at = pos2(rect.left() + 44.0, middle - name.size().y / 2.0); ui.painter().galley(at, name, p.text_0); - let meta = widgets::text( - ui, - shown.meta, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); - let at = pos2( - rect.right() - 10.0 - meta.size().x, - middle - meta.size().y / 2.0, - ); + let meta = widgets::text(ui, shown.meta, font::META, 400.0, FontFamily::Proportional, p.text_2); + let at = pos2(rect.right() - 10.0 - meta.size().x, middle - meta.size().y / 2.0); ui.painter().galley(at, meta, p.text_2); response } diff --git a/crates/ui/src/http/environments.rs b/crates/ui/src/http/environments.rs index c9dc68354..ce887f97a 100644 --- a/crates/ui/src/http/environments.rs +++ b/crates/ui/src/http/environments.rs @@ -42,13 +42,7 @@ fn ask(actions: &mut Actions, asked: Ask) { actions.push(Asked::Http(Action::Environments(asked))); } -pub(super) fn show( - ui: &mut Ui, - region: Rect, - state: &AppState, - view: &mut PageView, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, region: Rect, state: &AppState, view: &mut PageView, actions: &mut Actions) { let (mut top, body) = super::page(ui, region); let p = palette(ui.ctx()); head(&mut top, state, view, actions); @@ -56,11 +50,8 @@ pub(super) fn show( let list_rect = Rect::from_min_size(body.min, Vec2::new(list_width, body.height())); let mut list_ui = ui.new_child(UiBuilder::new().max_rect(list_rect.shrink(10.0))); list(&mut list_ui, state, view, actions); - ui.painter().vline( - list_rect.right(), - body.y_range(), - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .vline(list_rect.right(), body.y_range(), Stroke::new(1.0, p.line_soft)); let main_rect = Rect::from_min_max(pos2(list_rect.right(), body.top()), body.max); let mut main = ui.new_child(UiBuilder::new().max_rect(main_rect.shrink(20.0))); egui::ScrollArea::vertical() @@ -102,31 +93,22 @@ fn head(ui: &mut Ui, state: &AppState, view: &mut PageView, actions: &mut Action fn create(ui: &mut Ui, language: i18n::Language, view: &mut PageView, actions: &mut Actions) { let tr = |key| i18n::translate(language, key, &[]); let Some(name) = &mut view.creating else { - if Button::new( - &tr(keys::http::environments::NEW), - "http-environment-create-open", - ) - .kind(Kind::Filled) - .show(ui) - .clicked() + if Button::new(&tr(keys::http::environments::NEW), "http-environment-create-open") + .kind(Kind::Filled) + .show(ui) + .clicked() { view.creating = Some(String::new()); } return; }; - let mut close = Button::new( - &tr(keys::http::rail::CANCEL), - "http-environment-create-cancel", - ) - .show(ui) - .clicked(); - let mut submit = Button::new( - &tr(keys::http::environments::CREATE), - "http-environment-create-submit", - ) - .kind(Kind::Filled) - .show(ui) - .clicked(); + let mut close = Button::new(&tr(keys::http::rail::CANCEL), "http-environment-create-cancel") + .show(ui) + .clicked(); + let mut submit = Button::new(&tr(keys::http::environments::CREATE), "http-environment-create-submit") + .kind(Kind::Filled) + .show(ui) + .clicked(); ui.allocate_ui(Vec2::new(220.0, 0.0), |ui| { ui.set_width(220.0); let label = tr(keys::http::environments::NEW_NAME); @@ -153,21 +135,14 @@ fn create(ui: &mut Ui, language: i18n::Language, view: &mut PageView, actions: & } } -fn count_words(rows: &[Variable], language: i18n::Language) -> String { +pub(super) fn count_words(rows: &[Variable], language: i18n::Language) -> String { let counts = variable_counts(rows); - let count = i18n::translate( - language, - keys::http::environments::COUNT, - &[("count", counts.count.into())], - ); + let count = i18n::translate(language, keys::http::environments::COUNT, &[("count", counts.count.into())]); if counts.secrets == 0 { return count; } - let secrets = i18n::translate( - language, - keys::http::environments::SECRETS, - &[("count", counts.secrets.into())], - ); + let secrets = + i18n::translate(language, keys::http::environments::SECRETS, &[("count", counts.secrets.into())]); format!("{count} · {secrets}") } @@ -184,10 +159,7 @@ fn list(ui: &mut Ui, state: &AppState, view: &mut PageView, actions: &mut Action let meta = i18n::translate( language, keys::http::environments::GLOBALS_META, - &[( - "count", - variable_counts(environments.globals()).count.into(), - )], + &[("count", variable_counts(environments.globals()).count.into())], ); let globals = Entry { name: &tr(keys::http::environments::GLOBALS), @@ -200,10 +172,7 @@ fn list(ui: &mut Ui, state: &AppState, view: &mut PageView, actions: &mut Action select(view, actions, Target::Globals); } let title = tr(keys::http::environments::LIST_TITLE).to_uppercase(); - let title = egui::RichText::new(title) - .size(font::CAPTION) - .strong() - .color(p.text_2); + let title = egui::RichText::new(title).size(font::CAPTION).strong().color(p.text_2); ui.add(egui::Label::new(title)); for environment in environments.all() { let on = environments.shown().map(|shown| &shown.id) == Some(&environment.id); @@ -211,9 +180,7 @@ fn list(ui: &mut Ui, state: &AppState, view: &mut PageView, actions: &mut Action let badge = if active { Some(tr(keys::http::environments::ACTIVE)) } else { - environment - .protected - .then(|| tr(keys::http::environments::PROTECTED_BADGE)) + environment.protected.then(|| tr(keys::http::environments::PROTECTED_BADGE)) }; let meta = count_words(&environment.variables, language); let shown = Entry { @@ -270,39 +237,22 @@ fn entry(ui: &mut Ui, shown: &Entry<'_>) -> Response { let rect = response.rect; if shown.on { let edge = Stroke::new(1.0, p.amber_dim); - ui.painter() - .rect(rect, corner, p.bg_2, edge, egui::StrokeKind::Inside); + ui.painter().rect(rect, corner, p.bg_2, edge, egui::StrokeKind::Inside); } else if response.hovered() { ui.painter().rect_filled(rect, corner, p.bg_2); } let first = rect.top() + 18.0; - ui.painter() - .circle_filled(pos2(rect.left() + 14.0, first), 4.0, shown.hue); - let name = widgets::text( - ui, - shown.name, - font::READING, - 500.0, - FontFamily::Proportional, - p.text_0, - ); + ui.painter().circle_filled(pos2(rect.left() + 14.0, first), 4.0, shown.hue); + let name = widgets::text(ui, shown.name, font::READING, 500.0, FontFamily::Proportional, p.text_0); let width = name.size().x; let at = pos2(rect.left() + 26.0, first - name.size().y / 2.0); ui.painter().galley(at, name, p.text_0); if let Some(badge) = shown.badge { - let badge = widgets::text( - ui, - badge, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.amber_text, - ); + let badge = widgets::text(ui, badge, font::CAPTION, 600.0, FontFamily::Proportional, p.amber_text); let at = pos2(at.x + width + 8.0, first - badge.size().y / 2.0); ui.painter().galley(at, badge, p.amber_text); } - ui.painter() - .galley(pos2(rect.left() + 26.0, rect.top() + 28.0), meta, p.text_2); + ui.painter().galley(pos2(rect.left() + 26.0, rect.top() + 28.0), meta, p.text_2); response } @@ -329,10 +279,7 @@ fn set(ui: &mut Ui, state: &AppState, view: &mut PageView, actions: &mut Actions None => globals_head(ui, language), } let label = tr(keys::http::environments::VARIABLES); - let table = variables_table::Table { - kind: "environment", - label: &label, - }; + let table = variables_table::Table { kind: "environment", label: &label }; let rows = environments.rows(); match variables_table::show(ui, &table, rows, &mut view.revealed, language) { Some(variables_table::Changed::Rows(rows)) => ask(actions, Ask::Rows(rows)), @@ -363,14 +310,7 @@ fn globals_head(ui: &mut Ui, language: i18n::Language) { ui.painter().circle_filled(dot.center(), 5.0, p.pink); let words = tr(keys::http::environments::GLOBALS); let family = FontFamily::Proportional; - ui.label(widgets::text( - ui, - &words, - font::TITLE, - 600.0, - family, - p.text_0, - )); + ui.label(widgets::text(ui, &words, font::TITLE, 600.0, family, p.text_0)); let hint = egui::RichText::new(tr(keys::http::environments::GLOBALS_HINT)) .size(font::LABEL) .color(p.text_2); @@ -378,13 +318,7 @@ fn globals_head(ui: &mut Ui, language: i18n::Language) { }); } -fn set_head( - ui: &mut Ui, - state: &AppState, - shown: &Environment, - view: &mut PageView, - actions: &mut Actions, -) { +fn set_head(ui: &mut Ui, state: &AppState, shown: &Environment, view: &mut PageView, actions: &mut Actions) { let language = state.language; let tr = |key| i18n::translate(language, key, &[]); ui.horizontal(|ui| { @@ -415,16 +349,11 @@ fn set_head( let id = shown.id.clone(); ask(actions, Ask::Protect { id, protect }); } - let words = egui::RichText::new(&label) - .size(font::BODY) - .color(palette(ui.ctx()).text_1); + let words = egui::RichText::new(&label).size(font::BODY).color(palette(ui.ctx()).text_1); ui.add(egui::Label::new(words)); - if Button::new( - &tr(keys::http::environments::DUPLICATE), - "http-environment-duplicate", - ) - .show(ui) - .clicked() + if Button::new(&tr(keys::http::environments::DUPLICATE), "http-environment-duplicate") + .show(ui) + .clicked() { let name = i18n::translate( language, @@ -505,13 +434,8 @@ fn colours(ui: &mut Ui, shown: &Environment, language: i18n::Language, actions: fn swatch(ui: &Ui, response: &Response, hue: Color32, on: bool) { let rect = Rect::from_center_size(response.rect.center(), Vec2::splat(14.0)); - let shown = if on || response.hovered() { - hue - } else { - hue.gamma_multiply(0.45) - }; - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::TAG), shown); + let shown = if on || response.hovered() { hue } else { hue.gamma_multiply(0.45) }; + ui.painter().rect_filled(rect, CornerRadius::same(radius::TAG), shown); if on { ui.painter().rect_stroke( rect.expand(3.0), @@ -548,9 +472,7 @@ fn delete( keys::http::environments::CONFIRM_DELETE, &[("name", shown.name.as_str().into())], ); - let question = egui::RichText::new(question) - .size(font::BODY) - .color(p.text_1); + let question = egui::RichText::new(question).size(font::BODY).color(p.text_1); let said = ui.add(egui::Label::new(question)); widgets::address(ui, &said, "http-environment-delete-question"); if Button::new(&word, "http-environment-delete-confirm") @@ -561,12 +483,9 @@ fn delete( view.confirming_delete = false; ask(actions, Ask::Delete(shown.id.clone())); } - if Button::new( - &tr(keys::http::rail::CANCEL), - "http-environment-delete-cancel", - ) - .show(ui) - .clicked() + if Button::new(&tr(keys::http::rail::CANCEL), "http-environment-delete-cancel") + .show(ui) + .clicked() { view.confirming_delete = false; } diff --git a/crates/ui/src/http/environments_tests.rs b/crates/ui/src/http/environments_tests.rs index 57734de95..d7147b609 100644 --- a/crates/ui/src/http/environments_tests.rs +++ b/crates/ui/src/http/environments_tests.rs @@ -32,17 +32,12 @@ fn page() -> Harness<'static, Bench> { harness.set_size(TALL); settle(&mut harness); click_id(&mut harness, "http-environments-open"); - until(&mut harness, "the page is read", |harness| { - has(harness, "http-environments-empty") - }); + until(&mut harness, "the page is read", |harness| has(harness, "http-environments-empty")); harness } fn type_in(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { - let node = harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .next() - .unwrap(); + let node = harness.query_all_by(|node| node.author_id() == Some(author_id)).next().unwrap(); node.focus(); settle(harness); harness @@ -57,9 +52,7 @@ pub(super) fn create(harness: &mut Harness<'_, Bench>, name: &str) { click_id(harness, "http-environment-create-open"); type_in(harness, "http-environment-create-input", name); click_id(harness, "http-environment-create-submit"); - until(harness, "the environment is shown", |harness| { - has(harness, "http-environment-name") - }); + until(harness, "the environment is shown", |harness| has(harness, "http-environment-name")); } fn listed(harness: &Harness<'_, Bench>) -> Vec { @@ -69,9 +62,7 @@ fn listed(harness: &Harness<'_, Bench>) -> Vec { .collect() } -fn environments<'a>( - harness: &'a Harness<'_, Bench>, -) -> &'a crate::state::http::environments::Environments { +fn environments<'a>(harness: &'a Harness<'_, Bench>) -> &'a crate::state::http::environments::Environments { harness.state().state.http.environments() } @@ -83,10 +74,7 @@ fn an_environment_is_created_shown_used_and_deleted_after_a_question() { assert_eq!(environments(&harness).active_id(), None); click_id(&mut harness, "http-environment-use"); - assert_eq!( - environments(&harness).active().map(|it| it.name.as_str()), - Some("Staging") - ); + assert_eq!(environments(&harness).active().map(|it| it.name.as_str()), Some("Staging")); click_id(&mut harness, "http-environment-delete"); assert!(has(&harness, "http-environment-delete-question")); @@ -95,9 +83,7 @@ fn an_environment_is_created_shown_used_and_deleted_after_a_question() { click_id(&mut harness, "http-environment-delete"); click_id(&mut harness, "http-environment-delete-confirm"); - until(&mut harness, "it has gone", |harness| { - listed(harness) == ["Globals"] - }); + until(&mut harness, "it has gone", |harness| listed(harness) == ["Globals"]); assert_eq!(environments(&harness).active_id(), None); } @@ -108,14 +94,10 @@ fn a_name_is_written_once_left_and_a_copy_is_shown() { type_in(&mut harness, "http-environment-name", " EU"); harness.key_press(egui::Key::Enter); - until(&mut harness, "the name is written", |harness| { - listed(harness) == ["Globals", "Staging EU"] - }); + until(&mut harness, "the name is written", |harness| listed(harness) == ["Globals", "Staging EU"]); click_id(&mut harness, "http-environment-duplicate"); - until(&mut harness, "the copy is listed", |harness| { - listed(harness).len() == 3 - }); + until(&mut harness, "the copy is listed", |harness| listed(harness).len() == 3); let shown = environments(&harness).shown().unwrap(); assert_eq!(shown.name, "Staging EU (copy)"); } @@ -127,10 +109,7 @@ fn rows_typed_stay_as_typed_and_are_written_once_the_keys_rest() { assert_eq!(values(&harness, "http-variable-name")[0], "base"); until(&mut harness, "the globals hold it", |harness| { - environments(harness) - .globals() - .first() - .is_some_and(|row| row.name == "base") + environments(harness).globals().first().is_some_and(|row| row.name == "base") }); assert_eq!(values(&harness, "http-variable-name")[0], "base"); } @@ -159,9 +138,7 @@ fn a_secret_shown_in_one_set_is_masked_in_the_next() { create(&mut harness, "Staging"); click_first(&mut harness, "http-environment-entry"); - until(&mut harness, "the globals are shown again", |harness| { - has(harness, "http-variable-reveal") - }); + until(&mut harness, "the globals are shown again", |harness| has(harness, "http-variable-reveal")); assert_ne!(values(&harness, "http-variable-value")[0], "abc"); } @@ -175,9 +152,7 @@ fn a_protected_environment_asks_before_a_post_and_lets_a_get_through() { click_id(&mut harness, "http-environment-use"); click_id(&mut harness, "http-environment-protected"); until(&mut harness, "it is protected", |harness| { - environments(harness) - .active() - .is_some_and(|active| active.protected) + environments(harness).active().is_some_and(|active| active.protected) }); assert!(has(&harness, "http-environment-protected-note")); click_id(&mut harness, "http-environments-open"); @@ -218,9 +193,7 @@ fn a_name_nothing_sets_is_given_a_row_on_the_page() { tabs.edit(&key, |draft| { draft.apply(DraftEdit::Url("{{base}}/login".to_owned())); }); - until(&mut harness, "the chip is shown", |harness| { - has(harness, "http-used-variable") - }); + until(&mut harness, "the chip is shown", |harness| has(harness, "http-used-variable")); click_id(&mut harness, "http-used-variable"); assert_eq!(harness.state().state.http.page(), Page::Environments); @@ -232,8 +205,90 @@ fn a_name_nothing_sets_is_given_a_row_on_the_page() { fn a_request_opened_from_the_rail_leaves_the_page() { let mut harness = page(); click_named(&mut harness, "http-node-name", "POST Login"); - until(&mut harness, "the request is shown", |harness| { - has(harness, "http-url") - }); + until(&mut harness, "the request is shown", |harness| has(harness, "http-url")); assert_eq!(harness.state().state.http.page(), Page::Requests); } + +#[test] +fn a_name_typed_is_taken_on_enter_and_dropped_on_escape() { + let mut harness = page(); + let before = listed(&harness).len(); + click_id(&mut harness, "http-environment-create-open"); + type_in(&mut harness, "http-environment-create-input", "Staging"); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + assert_eq!(listed(&harness).len(), before); + assert!(!has(&harness, "http-environment-create-input")); + + click_id(&mut harness, "http-environment-create-open"); + type_in(&mut harness, "http-environment-create-input", "Staging"); + harness.key_press(egui::Key::Enter); + until(&mut harness, "it is made", |harness| listed(harness).len() > before); +} + +#[test] +fn an_environment_wears_the_colour_chosen() { + let mut harness = page(); + create(&mut harness, "Staging"); + let colour = |harness: &Harness<'_, Bench>| environments(harness).all()[0].colour; + let before = colour(&harness); + let swatches = harness + .query_all_by(|node| node.author_id() == Some("http-environment-colour")) + .count(); + assert!(swatches > 1); + for rank in 0..swatches { + harness + .query_all_by(|node| node.author_id() == Some("http-environment-colour")) + .nth(rank) + .unwrap() + .click(); + settle(&mut harness); + if colour(&harness) != before { + return; + } + } + panic!("no colour changed"); +} + +#[test] +fn the_one_chosen_in_the_list_is_the_one_shown() { + let mut harness = page(); + create(&mut harness, "Staging"); + create(&mut harness, "Production"); + let shown = |harness: &Harness<'_, Bench>| values(harness, "http-environment-name").join(""); + assert_eq!(shown(&harness), "Production"); + harness + .get_by(|node| { + node.author_id() == Some("http-environment-entry") + && node.label().is_some_and(|label| label.contains("Staging")) + }) + .click(); + settle(&mut harness); + + assert_eq!(shown(&harness), "Staging"); +} + +#[test] +fn the_rail_is_put_away_from_the_page() { + let mut harness = page(); + click_id(&mut harness, "http-rail-toggle"); + + assert!(!harness.state().state.settings.rail_shown); +} + +#[test] +fn a_set_counts_its_variables_and_its_secrets() { + let variable = |kind| engine::http::environments::Variable { + name: "a".to_owned(), + kind, + ..engine::http::environments::Variable::default() + }; + let words = |rows: &[engine::http::environments::Variable]| { + super::environments::count_words(rows, i18n::Language::En) + }; + let plain = words(&[variable(VariableKind::Text)]); + let both = words(&[variable(VariableKind::Text), variable(VariableKind::Secret)]); + + assert!(plain.contains('1') && !plain.contains('·'), "{plain}"); + assert!(both.contains('2') && both.contains(" · ") && both.contains('1'), "{both}"); +} diff --git a/crates/ui/src/http/extract.rs b/crates/ui/src/http/extract.rs index 8e54f23ea..2cea1fb64 100644 --- a/crates/ui/src/http/extract.rs +++ b/crates/ui/src/http/extract.rs @@ -25,20 +25,11 @@ pub(crate) struct Extracting { impl Extracting { pub(crate) fn of(explorer_path: &str) -> Self { let path = api::http::body_path(explorer_path); - Self { - name: api::http::variable_name_of(&path), - secret: api::http::looks_secret(&path), - path, - } + Self { name: api::http::variable_name_of(&path), secret: api::http::looks_secret(&path), path } } } -pub(super) fn show( - ui: &Ui, - state: &AppState, - form: &mut Option, - actions: &mut Actions, -) { +pub(super) fn show(ui: &Ui, state: &AppState, form: &mut Option, actions: &mut Actions) { let Some(tab) = state.http.tabs().active() else { *form = None; return; @@ -50,10 +41,7 @@ pub(super) fn show( ui, ( "http-extract-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-extract-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-extract-cross"), ), |ui| body(ui, open, (&tab.draft.name, state)), ); @@ -64,10 +52,7 @@ pub(super) fn show( variable: open.name.trim().to_owned(), secret: open.secret, }; - actions.push(Asked::Http(Action::AddExtraction { - key: tab.key.clone(), - rule, - })); + actions.push(Asked::Http(Action::AddExtraction { key: tab.key.clone(), rule })); *form = None; } Some(false) => *form = None, @@ -86,10 +71,7 @@ fn body(ui: &mut Ui, form: &mut Extracting, (request, state): (&str, &AppState)) let title = tr(keys::http::extract::TITLE); crate::widgets::dialog_title(ui, &title, "http-extract-dialog"); caption(ui, &tr(keys::http::extract::PATH)); - let path = egui::RichText::new(&form.path) - .monospace() - .size(font::BODY) - .color(p.text_0); + let path = egui::RichText::new(&form.path).monospace().size(font::BODY).color(p.text_0); let path = ui.add(egui::Label::new(path).truncate()); widgets::address(ui, &path, "http-extract-path"); let label = tr(keys::http::extract::NAME); @@ -99,9 +81,7 @@ fn body(ui: &mut Ui, form: &mut Extracting, (request, state): (&str, &AppState)) ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; Checkbox::new(&mut form.secret, &secret, "http-extract-secret").show(ui); - let words = egui::RichText::new(&secret) - .size(font::BODY) - .color(p.text_1); + let words = egui::RichText::new(&secret).size(font::BODY).color(p.text_1); ui.add(egui::Label::new(words)); }); let into = into_words(request, state); @@ -142,15 +122,8 @@ fn into_words(request: &str, state: &AppState) -> String { Some(active) => i18n::translate( language, keys::http::extract::INTO, - &[ - ("request", request.into()), - ("environment", active.name.as_str().into()), - ], - ), - None => i18n::translate( - language, - keys::http::extract::INTO_GLOBALS, - &[("request", request.into())], + &[("request", request.into()), ("environment", active.name.as_str().into())], ), + None => i18n::translate(language, keys::http::extract::INTO_GLOBALS, &[("request", request.into())]), } } diff --git a/crates/ui/src/http/history.rs b/crates/ui/src/http/history.rs index a182fcd7a..68e04d01e 100644 --- a/crates/ui/src/http/history.rs +++ b/crates/ui/src/http/history.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, gap, radius}; use chrono::{Days, Local, NaiveDate}; use egui::{ - Align, CornerRadius, FontFamily, Key, Layout, Modifiers, Rect, Role, Sense, Ui, UiBuilder, - Vec2, WidgetInfo, pos2, + Align, CornerRadius, FontFamily, Key, Layout, Modifiers, Rect, Role, Sense, Ui, UiBuilder, Vec2, + WidgetInfo, pos2, }; use engine::error::AppError; use engine::http::history::{HistoryDay, HistoryEntry, HistoryItem}; @@ -48,21 +48,13 @@ fn rows(days: &[HistoryDay]) -> Vec> { rows } -pub(super) fn show( - ui: &mut Ui, - region: Rect, - state: &AppState, - view: &mut PageView, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, region: Rect, state: &AppState, view: &mut PageView, actions: &mut Actions) { let (mut top, body) = super::page(ui, region); head(&mut top, state, actions); let setting = (state.settings.history_list_width, HISTORY_LIST_WIDTH); - let rest = view - .list_width - .show(ui, body, setting, "http-history-edge", |ui| { - list(ui, state, actions); - }); + let rest = view.list_width.show(ui, body, setting, "http-history-edge", |ui| { + list(ui, state, actions); + }); if let Some(width) = view.list_width.rested(ui) { actions.push(Asked::App(AppAction::SetHistoryWidth(width))); } @@ -94,16 +86,9 @@ fn head(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let question = history.confirming().map(|count| { - i18n::translate( - language, - keys::http::history::CONFIRM, - &[("count", count.into())], - ) + i18n::translate(language, keys::http::history::CONFIRM, &[("count", count.into())]) }); - let words = ( - &*tr(keys::http::history::CLEAR), - &*tr(keys::http::rail::CANCEL), - ); + let words = (&*tr(keys::http::history::CLEAR), &*tr(keys::http::rail::CANCEL)); let pressed = widgets::ask_in_place( ui, words, @@ -126,9 +111,7 @@ fn day_label(day: &str, today: NaiveDate, language: i18n::Language) -> String { let yesterday = today.checked_sub_days(Days::new(1)); match NaiveDate::parse_from_str(day, "%Y-%m-%d") { Ok(date) if date == today => i18n::translate(language, keys::http::history::TODAY, &[]), - Ok(date) if Some(date) == yesterday => { - i18n::translate(language, keys::http::history::YESTERDAY, &[]) - } + Ok(date) if Some(date) == yesterday => i18n::translate(language, keys::http::history::YESTERDAY, &[]), _ => day.to_owned(), } } @@ -140,11 +123,7 @@ fn list(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let today = state.clock.now().with_timezone(&Local).date_naive(); let rows = rows(history.days()); ui.spacing_mut().item_spacing.y = 0.0; - let bottom = if history.removed().is_some() { - 44.0 - } else { - 0.0 - }; + let bottom = if history.removed().is_some() { 44.0 } else { 0.0 }; let room = Vec2::new(ui.available_width(), ui.available_height() - bottom); ui.allocate_ui(room, |ui| { ui.set_min_height(room.y); @@ -154,16 +133,10 @@ fn list(ui: &mut Ui, state: &AppState, actions: &mut Actions) { widgets::empty_state(ui, room, (&words, "http-history-empty"), &[]); return; } - virtual_list( - ui, - "http-history-list", - ROW, - rows.len(), - |ui, at| match rows[at] { - Row::Day(day) => day_row(ui, &day_label(&day.day, today, language)), - Row::Item(item) => item_row(ui, state, item, actions), - }, - ); + virtual_list(ui, "http-history-list", ROW, rows.len(), |ui, at| match rows[at] { + Row::Day(day) => day_row(ui, &day_label(&day.day, today, language)), + Row::Item(item) => item_row(ui, state, item, actions), + }); }); if let Some(removed) = history.removed() { undo(ui, removed, language, actions); @@ -175,10 +148,7 @@ fn day_row(ui: &mut Ui, label: &str) { let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); let mut over = ui.new_child(UiBuilder::new().max_rect(rect.shrink2(Vec2::new(12.0, 8.0)))); over.with_layout(Layout::left_to_right(Align::Max), |ui| { - let words = egui::RichText::new(label) - .size(font::LABEL) - .strong() - .color(p.text_2); + let words = egui::RichText::new(label).size(font::LABEL).strong().color(p.text_2); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-history-day"); }); @@ -210,17 +180,14 @@ fn item_row(ui: &mut Ui, state: &AppState, item: &HistoryItem, actions: &mut Act ); let rect = response.rect; if on { - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_2); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_2); } else if response.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_1); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_1); } let method = item.method.as_str(); let hue = badge_hue(ui, Badge::Method(item.method)); let badge = widgets::text(ui, method, font::META, 700.0, FontFamily::Monospace, hue); - ui.painter() - .galley(pos2(rect.left() + 10.0, rect.top() + 9.0), badge, hue); + ui.painter().galley(pos2(rect.left() + 10.0, rect.top() + 9.0), badge, hue); let right = rect.right() - 36.0; let status = item.status.map_or_else( || i18n::translate(language, keys::http::history::NO_ANSWER, &[]), @@ -232,34 +199,13 @@ fn item_row(ui: &mut Ui, state: &AppState, item: &HistoryItem, actions: &mut Act let mut over = ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(at, galley.size()))); let said = over.add(egui::Label::new(galley).selectable(false)); widgets::address(ui, &said, "http-history-status"); - let time = item - .sent_at - .with_timezone(&Local) - .format("%H:%M:%S") - .to_string(); - let galley = widgets::text( - ui, - &time, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let time = item.sent_at.with_timezone(&Local).format("%H:%M:%S").to_string(); + let galley = widgets::text(ui, &time, font::META, 400.0, FontFamily::Proportional, p.text_2); let at = pos2(right - galley.size().x, rect.top() + 27.0); ui.painter().galley(at, galley, p.text_2); let text_left = rect.left() + 64.0; - let clip = Rect::from_min_max( - pos2(text_left, rect.top()), - pos2(right - 64.0, rect.bottom()), - ); - let name_ink = widgets::text( - ui, - name, - font::READING, - 500.0, - FontFamily::Proportional, - p.text_0, - ); + let clip = Rect::from_min_max(pos2(text_left, rect.top()), pos2(right - 64.0, rect.bottom())); + let name_ink = widgets::text(ui, name, font::READING, 500.0, FontFamily::Proportional, p.text_0); let width = name_ink.size().x; ui.painter_at(clip) .galley(pos2(text_left, rect.top() + 7.0), name_ink, p.text_0); @@ -267,18 +213,11 @@ fn item_row(ui: &mut Ui, state: &AppState, item: &HistoryItem, actions: &mut Act let hue = folder_hue(ui, environment.colour); let dot = pos2(text_left + width + 12.0, rect.top() + 15.0); ui.painter_at(clip).circle_filled(dot, 3.5, hue); - let words = widgets::text( - ui, - &environment.name, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let words = + widgets::text(ui, &environment.name, font::META, 400.0, FontFamily::Proportional, p.text_2); let at = pos2(dot.x + 8.0, rect.top() + 9.0); let size = words.size(); - let mut over = - ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(at, size).intersect(clip))); + let mut over = ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size(at, size).intersect(clip))); let said = over.add(egui::Label::new(words).selectable(false).truncate()); widgets::address(ui, &said, "http-history-environment"); } @@ -287,8 +226,7 @@ fn item_row(ui: &mut Ui, state: &AppState, item: &HistoryItem, actions: &mut Act response.request_focus(); ask(actions, Ask::Select(item.id.clone())); } - if response.has_focus() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Delete)) - { + if response.has_focus() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Delete)) { ask(actions, Ask::Delete(item.id.clone())); } remove(ui, rect, item, language, actions); @@ -297,49 +235,26 @@ fn item_row(ui: &mut Ui, state: &AppState, item: &HistoryItem, actions: &mut Act /// Cut in what repeats, not at its end: the host gives way, the path and the query stay. fn url(ui: &Ui, clip: Rect, item: &HistoryItem) { let p = palette(ui.ctx()); - let tail = widgets::text( - ui, - &item.url_tail, - font::CONTROL, - 400.0, - FontFamily::Monospace, - p.text_1, - ); - let head = widgets::text( - ui, - &item.url_head, - font::CONTROL, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let tail = widgets::text(ui, &item.url_tail, font::CONTROL, 400.0, FontFamily::Monospace, p.text_1); + let head = widgets::text(ui, &item.url_head, font::CONTROL, 400.0, FontFamily::Monospace, p.text_2); let top = clip.top() + 27.0; let room = clip.width(); let tail_width = tail.size().x.min(room); let head_room = (room - tail_width).max(0.0); let head_clip = Rect::from_min_size(clip.min, Vec2::new(head_room, clip.height())); - ui.painter_at(head_clip) - .galley(pos2(clip.left(), top), head.clone(), p.text_2); + ui.painter_at(head_clip).galley(pos2(clip.left(), top), head.clone(), p.text_2); let at = clip.left() + head.size().x.min(head_room); ui.painter_at(clip).galley(pos2(at, top), tail, p.text_1); } -fn remove( - ui: &mut Ui, - rect: Rect, - item: &HistoryItem, - language: i18n::Language, - actions: &mut Actions, -) { +fn remove(ui: &mut Ui, rect: Rect, item: &HistoryItem, language: i18n::Language, actions: &mut Actions) { let label = i18n::translate( language, keys::http::history::DELETE, &[("name", item.summary.name.as_str().into())], ); - let at = Rect::from_center_size( - pos2(rect.right() - 18.0, rect.center().y), - Vec2::splat(widgets::MIN_TARGET), - ); + let at = + Rect::from_center_size(pos2(rect.right() - 18.0, rect.center().y), Vec2::splat(widgets::MIN_TARGET)); let mut over = ui.new_child(UiBuilder::new().max_rect(at)); if IconButton::new(Icon::X, &label, "http-history-delete") .show(&mut over) @@ -363,13 +278,9 @@ fn undo(ui: &mut Ui, removed: &HistoryEntry, language: i18n::Language, actions: let said = ui.add(egui::Label::new(words).truncate()); widgets::address(ui, &said, "http-history-undo"); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if IconButton::new( - Icon::X, - &tr(keys::undo::DISMISS), - "http-history-undo-dismiss", - ) - .show(ui) - .clicked() + if IconButton::new(Icon::X, &tr(keys::undo::DISMISS), "http-history-undo-dismiss") + .show(ui) + .clicked() { ask(actions, Ask::DismissUndo); } @@ -417,11 +328,7 @@ fn detail(ui: &mut Ui, state: &AppState, view: &mut response::ResponseView, acti /// The sentence the send itself showed: the code, and the values it stated. fn failure(item: &HistoryItem, language: i18n::Language) -> String { let known = item.summary.failure.and_then(|code| { - let error = AppError { - code, - params: item.summary.failure_params.clone(), - detail: String::new(), - }; + let error = AppError { code, params: item.summary.failure_params.clone(), detail: String::new() }; crate::services::errors::message_of(&error) }); known @@ -463,31 +370,19 @@ fn entry_head(ui: &mut Ui, state: &AppState, entry: &HistoryEntry, actions: &mut { ask(actions, Ask::Reopen(true)); } - let question = i18n::translate( - language, - keys::http::history::REPLACE, - &[("name", name.into())], - ); - let question = egui::RichText::new(question) - .size(font::BODY) - .color(p.text_1); + let question = + i18n::translate(language, keys::http::history::REPLACE, &[("name", name.into())]); + let question = egui::RichText::new(question).size(font::BODY).color(p.text_1); let said = ui.add(egui::Label::new(question)); widgets::address(ui, &said, "http-history-replace"); } else { let words = state.http.reopen_into(&entry.item).map_or_else( || tr(keys::http::history::REOPEN_DRAFT), |name| { - i18n::translate( - language, - keys::http::history::REOPEN_INTO, - &[("name", name.into())], - ) + i18n::translate(language, keys::http::history::REOPEN_INTO, &[("name", name.into())]) }, ); - if Button::new(&words, "http-history-reopen") - .show(ui) - .clicked() - { + if Button::new(&words, "http-history-reopen").show(ui).clicked() { ask(actions, Ask::Reopen(false)); } } @@ -498,3 +393,6 @@ fn entry_head(ui: &mut Ui, state: &AppState, entry: &HistoryEntry, actions: &mut }); }); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/history/tests.rs b/crates/ui/src/http/history/tests.rs new file mode 100644 index 000000000..1699b085d --- /dev/null +++ b/crates/ui/src/http/history/tests.rs @@ -0,0 +1,20 @@ +//! What the list of the sends says. + +use chrono::NaiveDate; +use i18n::Language; + +use super::*; + +#[test] +fn a_day_is_named_by_how_near_it_is() { + let today = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(); + for (day, words) in [ + ("2026-03-01", "Today"), + ("2026-02-28", "Yesterday"), + ("2026-02-27", "2026-02-27"), + ("2026-03-02", "2026-03-02"), + ("else", "else"), + ] { + assert_eq!(day_label(day, today, Language::En), words); + } +} diff --git a/crates/ui/src/http/history_tests.rs b/crates/ui/src/http/history_tests.rs index fb87ec543..5d3394982 100644 --- a/crates/ui/src/http/history_tests.rs +++ b/crates/ui/src/http/history_tests.rs @@ -22,9 +22,7 @@ fn sent() -> Harness<'static, Bench> { click_id(&mut harness, "http-send"); answered(&mut harness); click_id(&mut harness, "http-history-open"); - until(&mut harness, "the send is listed", |harness| { - has(harness, "http-history-item") - }); + until(&mut harness, "the send is listed", |harness| has(harness, "http-history-item")); harness } @@ -34,30 +32,19 @@ fn page(harness: &Harness<'_, Bench>) -> Page { fn read_it(harness: &mut Harness<'_, Bench>) { click_id(harness, "http-history-item"); - until(harness, "the send is read", |harness| { - has(harness, "http-history-url") - }); + until(harness, "the send is read", |harness| has(harness, "http-history-url")); } #[test] fn a_send_is_listed_by_day_and_read_like_an_answer() { let mut harness = sent(); - assert_eq!( - said_by(&harness, "http-history-day").as_deref(), - Some("Today") - ); - assert_eq!( - said_by(&harness, "http-history-status").as_deref(), - Some("200") - ); + assert_eq!(said_by(&harness, "http-history-day").as_deref(), Some("Today")); + assert_eq!(said_by(&harness, "http-history-status").as_deref(), Some("200")); read_it(&mut harness); assert!(said_by(&harness, "http-history-url").is_some_and(|url| url.ends_with("/json"))); assert!(has(&harness, "http-response-status")); - assert!( - !has(&harness, "http-response-clear"), - "no tab to clear it from" - ); + assert!(!has(&harness, "http-response-clear"), "no tab to clear it from"); } #[test] @@ -77,9 +64,7 @@ fn a_send_deleted_comes_back_from_its_bar() { }); click_id(&mut harness, "http-history-undo-restore"); - until(&mut harness, "the send is back", |harness| { - has(harness, "http-history-item") - }); + until(&mut harness, "the send is back", |harness| has(harness, "http-history-item")); assert!(!has(&harness, "http-history-undo")); } @@ -87,20 +72,14 @@ fn a_send_deleted_comes_back_from_its_bar() { fn clearing_says_how_many_go() { let mut harness = sent(); click_id(&mut harness, "http-history-clear"); - until(&mut harness, "the count is said", |harness| { - has(harness, "http-history-clear-count") - }); + until(&mut harness, "the count is said", |harness| has(harness, "http-history-clear-count")); click_id(&mut harness, "http-history-clear-cancel"); assert!(has(&harness, "http-history-item")); click_id(&mut harness, "http-history-clear"); - until(&mut harness, "the count is said", |harness| { - has(harness, "http-history-clear-confirm") - }); + until(&mut harness, "the count is said", |harness| has(harness, "http-history-clear-confirm")); click_id(&mut harness, "http-history-clear-confirm"); - until(&mut harness, "nothing is left", |harness| { - has(harness, "http-history-empty") - }); + until(&mut harness, "nothing is left", |harness| has(harness, "http-history-empty")); } fn change_method(harness: &mut Harness<'_, Bench>, method: HttpMethod) { @@ -123,9 +102,7 @@ fn a_send_goes_back_onto_its_request_asking_before_it_replaces_changes() { click_id(&mut harness, "http-history-reopen"); click_id(&mut harness, "http-history-replace-confirm"); - until(&mut harness, "the requests are shown again", |harness| { - page(harness) == Page::Requests - }); + until(&mut harness, "the requests are shown again", |harness| page(harness) == Page::Requests); assert_eq!(active(&harness).method, HttpMethod::Get); assert!(values(&harness, "http-url")[0].ends_with("/json")); } @@ -136,19 +113,14 @@ fn a_send_from_a_request_gone_opens_as_a_draft_named_after_its_time() { read_it(&mut harness); let id = active_request(&harness); let bench = harness.state_mut(); - let item = HttpItem { - kind: HttpItemKind::Request, - id, - }; + let item = HttpItem { kind: HttpItemKind::Request, id }; bench.state.http.write(&bench.backend, Write::Delete(item)); until(&mut harness, "the tree is read again", |harness| { said_by(harness, "http-history-reopen").is_some_and(|said| !said.contains("in ")) }); click_id(&mut harness, "http-history-reopen"); - until(&mut harness, "the draft is open", |harness| { - page(harness) == Page::Requests - }); + until(&mut harness, "the draft is open", |harness| page(harness) == Page::Requests); let tab = harness.state().state.http.tabs().active().unwrap(); assert!(tab.request_id.is_none()); assert!(tab.draft.name.contains(" · "), "{}", tab.draft.name); @@ -158,3 +130,43 @@ fn active_request(harness: &Harness<'_, Bench>) -> String { let tabs = harness.state().state.http.tabs(); tabs.active().unwrap().request_id.clone().unwrap() } + +#[test] +fn a_send_that_had_no_answer_says_why() { + let mut harness = sending_to("/json"); + let tabs = harness.state_mut().state.http.tabs_mut(); + let key = tabs.active().unwrap().key.clone(); + tabs.edit(&key, |draft| { + draft.apply(DraftEdit::Url("http://127.0.0.1:1/".to_owned())); + }); + settle(&mut harness); + click_id(&mut harness, "http-send"); + until(&mut harness, "it failed", |harness| has(harness, "http-response-failure")); + click_id(&mut harness, "http-history-open"); + until(&mut harness, "the send is listed", |harness| has(harness, "http-history-item")); + let status = said_by(&harness, "http-history-status").unwrap_or_default(); + assert_eq!(status, i18n::translate(i18n::Language::En, i18n::keys::http::history::NO_ANSWER, &[])); + + read_it(&mut harness); + assert!(said_by(&harness, "http-history-failure").is_some_and(|words| !words.is_empty())); +} + +#[test] +fn delete_takes_the_send_that_has_the_keys_and_its_bar_can_be_dismissed() { + let mut harness = sent(); + harness.get_by(|node| node.author_id() == Some("http-history-item")).focus(); + settle(&mut harness); + harness.key_press(egui::Key::Delete); + until(&mut harness, "it went", |harness| has(harness, "http-history-undo")); + click_id(&mut harness, "http-history-undo-dismiss"); + + assert!(!has(&harness, "http-history-undo") && !has(&harness, "http-history-item")); +} + +#[test] +fn the_rail_is_put_away_from_the_page() { + let mut harness = sent(); + click_id(&mut harness, "http-rail-toggle"); + + assert!(!harness.state().state.settings.rail_shown); +} diff --git a/crates/ui/src/http/kept_tests.rs b/crates/ui/src/http/kept_tests.rs index 2c7b22a12..4317f3479 100644 --- a/crates/ui/src/http/kept_tests.rs +++ b/crates/ui/src/http/kept_tests.rs @@ -28,15 +28,7 @@ fn answer() -> Harness<'static, Bench> { } fn active_key(harness: &Harness<'_, Bench>) -> String { - harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .key - .clone() + harness.state().state.http.tabs().active().unwrap().key.clone() } /// A line under the send the tab is showing. @@ -46,39 +38,25 @@ fn say(harness: &mut Harness<'_, Bench>, line: ConsoleLine) { let http = &harness.state().state.http; http.sends().of(&key).unwrap().id.clone() }; - harness - .state_mut() - .state - .http - .receive_console(ConsoleEvent { - id, - at: Utc::now(), - request: "Ping".to_owned(), - iteration: None, - line, - }); + harness.state_mut().state.http.receive_console(ConsoleEvent { + id, + at: Utc::now(), + request: "Ping".to_owned(), + iteration: None, + line, + }); settle(harness); } fn log(text: &str) -> ConsoleLine { - ConsoleLine::Log { - level: LogLevel::default(), - text: text.to_owned(), - by: None, - } + ConsoleLine::Log { level: LogLevel::default(), text: text.to_owned(), by: None } } #[test] fn folded_the_console_counts_and_unfolded_it_filters() { let mut harness = answer(); say(&mut harness, log("hello {{token}}")); - say( - &mut harness, - ConsoleLine::Missed { - path: "body.id".to_owned(), - variable: "id".to_owned(), - }, - ); + say(&mut harness, ConsoleLine::Missed { path: "body.id".to_owned(), variable: "id".to_owned() }); assert!(said_by(&harness, "http-console-summary").is_some()); click_id(&mut harness, "http-console-unfold"); @@ -103,17 +81,10 @@ fn folded_the_console_counts_and_unfolded_it_filters() { fn a_secret_written_as_its_name_is_set_apart() { assert_eq!( secret_segments("Bearer {{token}} now"), - [ - ("Bearer ".to_owned(), false), - ("{{token}}".to_owned(), true), - (" now".to_owned(), false), - ] + [("Bearer ".to_owned(), false), ("{{token}}".to_owned(), true), (" now".to_owned(), false),] ); let empty = secret_segments("{{}} x"); - assert!( - empty.iter().all(|(_, secret)| !secret), - "no name, no secret" - ); + assert!(empty.iter().all(|(_, secret)| !secret), "no name, no secret"); } #[test] @@ -121,13 +92,9 @@ fn an_answer_is_kept_as_a_note_where_the_dialog_says() { let mut harness = answer(); let bench = harness.state_mut(); bench.state.spaces.create_space(&bench.backend, "Travail"); - until(&mut harness, "the space is read", |harness| { - !harness.state().state.spaces.spaces().is_empty() - }); + until(&mut harness, "the space is read", |harness| !harness.state().state.spaces.spaces().is_empty()); click_id(&mut harness, "http-response-save-note"); - until(&mut harness, "the dialog asks", |harness| { - has(harness, "save-as-note-submit") - }); + until(&mut harness, "the dialog asks", |harness| has(harness, "save-as-note-submit")); let last = std::cell::Cell::new(None); until(&mut harness, "the dialog rests", |harness| { let submit = harness.get_by(|node| node.author_id() == Some("save-as-note-submit")); diff --git a/crates/ui/src/http/leave.rs b/crates/ui/src/http/leave.rs index f76f3ff6d..c65987740 100644 --- a/crates/ui/src/http/leave.rs +++ b/crates/ui/src/http/leave.rs @@ -30,10 +30,7 @@ pub(crate) fn show(ui: &Ui, state: &AppState, view: &mut View, actions: &mut Act ui, ( "http-leave-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-leave-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-leave-cross"), ), |ui| body(ui, state), ); @@ -49,41 +46,19 @@ fn body(ui: &mut Ui, state: &AppState) -> Option { let p = palette(ui.ctx()); let language = state.language; let tr = |key| i18n::translate(language, key, &[]); - let names: Vec<&str> = state - .http - .modified() - .map(|tab| tab.draft.name.as_str()) - .collect(); + let names: Vec<&str> = state.http.modified().map(|tab| tab.draft.name.as_str()).collect(); ui.set_width(WIDTH.min(ui.ctx().content_rect().width() * 0.9)); ui.spacing_mut().item_spacing.y = gap::INSET; let count = u32::try_from(names.len()).unwrap_or(u32::MAX); - let title = i18n::translate( - language, - keys::http::leave::TITLE, - &[("count", count.into())], - ); + let title = i18n::translate(language, keys::http::leave::TITLE, &[("count", count.into())]); crate::widgets::dialog_title(ui, &title, "http-leave-dialog"); let (hint, discard) = match state.http.leave().reason() { - Reason::Quit => ( - keys::http::leave::hint::QUIT, - keys::http::leave::discard::QUIT, - ), - Reason::Switch => ( - keys::http::leave::hint::SWITCH, - keys::http::leave::discard::SWITCH, - ), - Reason::Restore => ( - keys::http::leave::hint::RESTORE, - keys::http::leave::discard::RESTORE, - ), - Reason::Update => ( - keys::http::leave::hint::UPDATE, - keys::http::leave::discard::UPDATE, - ), + Reason::Quit => (keys::http::leave::hint::QUIT, keys::http::leave::discard::QUIT), + Reason::Switch => (keys::http::leave::hint::SWITCH, keys::http::leave::discard::SWITCH), + Reason::Restore => (keys::http::leave::hint::RESTORE, keys::http::leave::discard::RESTORE), + Reason::Update => (keys::http::leave::hint::UPDATE, keys::http::leave::discard::UPDATE), }; - let hint = egui::RichText::new(tr(hint)) - .size(font::BODY) - .color(p.text_2); + let hint = egui::RichText::new(tr(hint)).size(font::BODY).color(p.text_2); ui.add(egui::Label::new(hint).wrap()); for name in names { let words = egui::RichText::new(name).size(font::BODY).color(p.text_0); @@ -92,11 +67,7 @@ fn body(ui: &mut Ui, state: &AppState) -> Option { } let connected = state.http.connected(); if connected > 0 { - let words = i18n::translate( - language, - keys::http::leave::CONNECTED, - &[("count", connected.into())], - ); + let words = i18n::translate(language, keys::http::leave::CONNECTED, &[("count", connected.into())]); let words = egui::RichText::new(words).size(font::BODY).color(p.text_2); let said = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &said, "http-leave-connected"); diff --git a/crates/ui/src/http/leave_tests.rs b/crates/ui/src/http/leave_tests.rs index 06dcd3c3b..8a275a7e9 100644 --- a/crates/ui/src/http/leave_tests.rs +++ b/crates/ui/src/http/leave_tests.rs @@ -104,9 +104,7 @@ fn a_request_never_saved_is_asked_its_place_and_refusing_keeps_the_question() { ask(&mut harness); stand_still(&mut harness); click_id(&mut harness, "http-leave-save"); - until(&mut harness, "its place is asked", |harness| { - has(harness, "http-save-dialog") - }); + until(&mut harness, "its place is asked", |harness| has(harness, "http-save-dialog")); let last = std::cell::Cell::new(None); until(&mut harness, "the dialog rests", |harness| { let cancel = harness.get_by(|node| node.author_id() == Some("http-save-cancel")); @@ -115,9 +113,7 @@ fn a_request_never_saved_is_asked_its_place_and_refusing_keeps_the_question() { }); click_id(&mut harness, "http-save-cancel"); - until(&mut harness, "the question is back", |harness| { - has(harness, "http-leave-dialog") - }); + until(&mut harness, "the question is back", |harness| has(harness, "http-leave-dialog")); assert!(!released(&harness)); } @@ -130,3 +126,42 @@ fn a_write_queued_just_before_the_exit_is_written() { let tree = engine::db::run_here(backend.engine(), engine::http::http_tree).unwrap(); assert_eq!(tree.collections.len(), 1); } + +/// Each reason has its own sentence and its own word for going on. +#[test] +fn the_question_is_put_by_what_asks_it() { + use crate::state::http::leave::Reason; + + let mut words: Vec = [Reason::Quit, Reason::Switch, Reason::Restore, Reason::Update] + .into_iter() + .map(|reason| { + let mut harness = modified(); + assert!(!harness.state_mut().state.http.ask_leave(reason)); + settle(&mut harness); + let discard = harness.get_by(|node| node.author_id() == Some("http-leave-discard")); + discard.accesskit_node().label().unwrap_or_default() + }) + .collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count, "{words:?}"); +} + +/// The place of a draft is asked over whatever area is shown. +#[test] +fn a_draft_s_place_is_asked_from_another_area() { + let mut harness = paiements(); + click_id(&mut harness, "http-workspace-new-http"); + let tabs = harness.state_mut().state.http.tabs_mut(); + let key = tabs.active().unwrap().key.clone(); + tabs.edit(&key, |draft| { + draft.apply(DraftEdit::Url("https://api.test/new".to_owned())); + }); + settle(&mut harness); + ask(&mut harness); + stand_still(&mut harness); + click_id(&mut harness, "http-leave-save"); + until(&mut harness, "its place is asked", |harness| has(harness, "http-save-dialog")); +} diff --git a/crates/ui/src/http/mod.rs b/crates/ui/src/http/mod.rs index 6687b645b..7529e67d5 100644 --- a/crates/ui/src/http/mod.rs +++ b/crates/ui/src/http/mod.rs @@ -199,17 +199,12 @@ pub struct View { } pub fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { - let region = widgets::area_room( - ui, - "area-http", - &i18n::translate(state.language, i18n::keys::areas::HTTP, &[]), - ); + let region = + widgets::area_room(ui, "area-http", &i18n::translate(state.language, i18n::keys::areas::HTTP, &[])); let rail = (state.settings.rail_shown, state.settings.rail_width); - let rest = view - .rail_width - .beside(ui, region, rail, "http-rail-edge", |ui| { - rail::show(ui, state, &mut view.rail, actions); - }); + let rest = view.rail_width.beside(ui, region, rail, "http-rail-edge", |ui| { + rail::show(ui, state, &mut view.rail, actions); + }); match state.http.page() { Page::Environments => { let mut page = ui.new_child(UiBuilder::new().max_rect(rest)); @@ -243,20 +238,13 @@ pub fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Action pub(super) fn page(ui: &mut Ui, region: Rect) -> (Ui, Rect) { use crate::theme::tokens::{BAR_HEIGHT, BAR_INSET}; let p = palette(ui.ctx()); - ui.painter() - .rect_filled(region, egui::CornerRadius::ZERO, p.bg_0); + ui.painter().rect_filled(region, egui::CornerRadius::ZERO, p.bg_0); let head = Rect::from_min_size(region.min, egui::Vec2::new(region.width(), BAR_HEIGHT)); let inset = head.shrink2(egui::Vec2::new(BAR_INSET, 0.0)); let top = ui.new_child(egui::UiBuilder::new().max_rect(inset)); - ui.painter().hline( - region.x_range(), - head.bottom() - 0.5, - egui::Stroke::new(1.0, p.line_soft), - ); - ( - top, - Rect::from_min_max(egui::pos2(region.left(), head.bottom()), region.max), - ) + ui.painter() + .hline(region.x_range(), head.bottom() - 0.5, egui::Stroke::new(1.0, p.line_soft)); + (top, Rect::from_min_max(egui::pos2(region.left(), head.bottom()), region.max)) } pub(crate) fn modal( @@ -313,17 +301,10 @@ fn split( actions: &mut Actions, ) { let total = region.height(); - let share = view - .dragged_share - .unwrap_or(state.settings.http_request_share); - let wanted = if share > 0 { - total * f32::from(share) / 1000.0 - } else { - view.editor_height.min(total * 0.6) - }; - let upper = wanted - .max(FLOORS.0) - .min((total - FLOORS.1 - HANDLE).max(FLOORS.0)); + let share = view.dragged_share.unwrap_or(state.settings.http_request_share); + let wanted = + if share > 0 { total * f32::from(share) / 1000.0 } else { view.editor_height.min(total * 0.6) }; + let upper = wanted.max(FLOORS.0).min((total - FLOORS.1 - HANDLE).max(FLOORS.0)); let top = Rect::from_min_size(region.min, Vec2::new(region.width(), upper)); let line = Rect::from_min_size(top.left_bottom(), Vec2::new(region.width(), HANDLE)); let bottom = Rect::from_min_max(line.left_bottom(), region.max); @@ -346,6 +327,7 @@ fn split( actions.push(Asked::Http(Action::SetShare(0))); } if widgets::takes_keys(ui, &handle) { + widgets::keep_arrows(ui, &handle); for (key, step) in [(egui::Key::ArrowUp, -16.0), (egui::Key::ArrowDown, 16.0)] { if ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)) { actions.push(Asked::Http(Action::SetShare(share_at(upper + step, total)))); @@ -369,10 +351,7 @@ fn split( response::show(&mut answer, state, (tab, &mut view.response), actions); let mut lines = ui.new_child(UiBuilder::new().max_rect(below)); lines.set_clip_rect(below); - let of = console::Of { - key: &tab.key, - name: &tab.draft.name, - }; + let of = console::Of { key: &tab.key, name: &tab.draft.name }; console::show(&mut lines, state, (of, &mut view.console), actions); } @@ -380,11 +359,7 @@ fn split( fn share_at(upper: f32, total: f32) -> u16 { let (min, max) = crate::services::settings::HTTP_SHARE; let tenths = (upper / total.max(1.0) * 1000.0).round(); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "clamped" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "clamped")] let tenths = tenths.clamp(f32::from(min), f32::from(max)) as u16; tenths } diff --git a/crates/ui/src/http/rail/forms.rs b/crates/ui/src/http/rail/forms.rs index 6fb42865a..b33932092 100644 --- a/crates/ui/src/http/rail/forms.rs +++ b/crates/ui/src/http/rail/forms.rs @@ -26,10 +26,7 @@ impl Default for Draft { impl Draft { pub(super) fn named(name: &str) -> Self { - Self { - name: name.to_owned(), - focus: true, - } + Self { name: name.to_owned(), focus: true } } } @@ -54,19 +51,12 @@ pub(super) fn name_form(ui: &mut Ui, draft: &mut Draft, words: &Words, ids: (&st } /// The field and its button on the row itself, in place of its name. -pub(super) fn inline_form( - ui: &mut Ui, - draft: &mut Draft, - words: &Words, - ids: (&str, &str), -) -> Typed { +pub(super) fn inline_form(ui: &mut Ui, draft: &mut Draft, words: &Words, ids: (&str, &str)) -> Typed { let button = Button::width(ui, &words.submit); ui.spacing_mut().item_spacing.x = gap::TIGHT; let room = ui.available_width() - button - 4.0; let field = ui - .allocate_ui(egui::vec2(room.max(48.0), ui.available_height()), |ui| { - field(ui, draft, words, ids.0) - }) + .allocate_ui(egui::vec2(room.max(48.0), ui.available_height()), |ui| field(ui, draft, words, ids.0)) .inner; let clicked = Button::new(&words.submit, ids.1).show(ui).clicked(); settle(ui, draft, &field, clicked) @@ -93,11 +83,7 @@ fn settle(ui: &Ui, draft: &Draft, field: &egui::Response, clicked: bool) -> Type return Typed::Typing; } let name = draft.name.trim(); - if name.is_empty() { - Typed::Dropped - } else { - Typed::Name(name.to_owned()) - } + if name.is_empty() { Typed::Dropped } else { Typed::Name(name.to_owned()) } } /// « Delete “Auth”? », what goes with it counted by Rust, and its two buttons — red at rest. @@ -113,28 +99,16 @@ pub(super) fn confirm_delete( .stroke(Stroke::new(1.0, p.line)) .corner_radius(CornerRadius::same(radius::MENU)) .inner_margin(gap::margin(gap::INSET, gap::CONTROLS)) - .outer_margin(Margin { - left: 4, - right: 4, - top: 4, - bottom: 6, - }); + .outer_margin(Margin { left: 4, right: 4, top: 4, bottom: 6 }); let response = frame .show(ui, |ui| { ui.spacing_mut().item_spacing.y = gap::CONTROLS; - let question = i18n::translate( - language, - keys::http::rail::CONFIRM, - &[("name", row.name.as_str().into())], - ); - let label = egui::RichText::new(&question) - .size(font::LABEL) - .color(p.text_0); + let question = + i18n::translate(language, keys::http::rail::CONFIRM, &[("name", row.name.as_str().into())]); + let label = egui::RichText::new(&question).size(font::LABEL).color(p.text_0); ui.add(egui::Label::new(label).wrap()); if contents.folders + contents.requests > 0 { - let count = egui::RichText::new(noun(contents, language)) - .size(font::LABEL) - .color(p.text_2); + let count = egui::RichText::new(noun(contents, language)).size(font::LABEL).color(p.text_2); let response = ui.add(egui::Label::new(count).wrap()); crate::widgets::address(ui, &response, "http-delete-count"); } @@ -149,30 +123,18 @@ pub(super) fn confirm_delete( .show(ui) .clicked() { - let item = HttpItem { - kind: row.kind, - id: row.id.clone(), - }; - push( - actions, - Action::Write(crate::state::http::Write::Delete(item)), - ); + let item = HttpItem { kind: row.kind, id: row.id.clone() }; + push(actions, Action::Write(crate::state::http::Write::Delete(item))); } let cancel = i18n::translate(language, keys::http::rail::CANCEL, &[]); - if Button::new(&cancel, "http-delete-cancel") - .show(ui) - .clicked() - { + if Button::new(&cancel, "http-delete-cancel").show(ui).clicked() { push(actions, Action::CancelDelete); } }); }) .response; - let question = i18n::translate( - language, - keys::http::rail::CONFIRM, - &[("name", row.name.as_str().into())], - ); + let question = + i18n::translate(language, keys::http::rail::CONFIRM, &[("name", row.name.as_str().into())]); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::AlertDialog, true, &question)); crate::widgets::address(ui, &response, "http-delete-confirm"); } @@ -204,12 +166,9 @@ fn lost(ui: &mut Ui, row: &RailRow, unsaved: &[String], language: i18n::Language ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::TIGHT; // The dot a modified tab wears, drawn: no embedded face has it. - let (dot, _) = - ui.allocate_exact_size(egui::vec2(6.0, 12.0), egui::Sense::hover()); + let (dot, _) = ui.allocate_exact_size(egui::vec2(6.0, 12.0), egui::Sense::hover()); ui.painter().circle_filled(dot.center(), 3.0, p.amber_text); - let line = egui::RichText::new(name) - .size(font::CONTROL) - .color(p.text_0); + let line = egui::RichText::new(name).size(font::CONTROL).color(p.text_0); let said = ui.add(egui::Label::new(line).truncate()); crate::widgets::address(ui, &said, "http-delete-unsaved-name"); }); @@ -232,9 +191,9 @@ fn noun(contents: HttpContents, language: i18n::Language) -> String { i18n::translate( language, key, - &[ - ("folders", contents.folders.into()), - ("requests", contents.requests.into()), - ], + &[("folders", contents.folders.into()), ("requests", contents.requests.into())], ) } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/rail/forms/tests.rs b/crates/ui/src/http/rail/forms/tests.rs new file mode 100644 index 000000000..f380665f1 --- /dev/null +++ b/crates/ui/src/http/rail/forms/tests.rs @@ -0,0 +1,14 @@ +//! What a deletion says it takes. + +use super::*; + +/// « no folder » is noise in a sentence about loss. +#[test] +fn only_what_is_there_is_counted() { + let said = |folders, requests| noun(HttpContents { folders, requests }, i18n::Language::En); + let (folders, requests, both) = (said(2, 0), said(0, 3), said(2, 3)); + + assert!(folders.contains('2') && !folders.contains('0'), "{folders}"); + assert!(requests.contains('3') && !requests.contains('0'), "{requests}"); + assert!(both.contains('2') && both.contains('3'), "{both}"); +} diff --git a/crates/ui/src/http/rail/mod.rs b/crates/ui/src/http/rail/mod.rs index e7679e026..374f72dfa 100644 --- a/crates/ui/src/http/rail/mod.rs +++ b/crates/ui/src/http/rail/mod.rs @@ -83,22 +83,15 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: let s = spacing(ui.ctx()); // The tree is wider than the switch by what the rail's padding can spare: the rows are what // run out of room, and the switch keeps the place it has in the other areas. - let margin = Margin { - left: 4, - right: 4, - top: to_margin(s.card), - bottom: to_margin(s.canvas), - }; + let margin = Margin { left: 4, right: 4, top: to_margin(s.card), bottom: to_margin(s.canvas) }; let http = &state.http; let language = state.language; egui::Frame::new().inner_margin(margin).show(ui, |ui| { ui.set_min_height(ui.available_height()); ui.spacing_mut().item_spacing.y = gap::SNUG; - egui::Frame::new() - .inner_margin(gap::margin(gap::SNUG, 0.0)) - .show(ui, |ui| { - crate::titlebar::area_switch::rail(ui, Area::Http, language, actions); - }); + egui::Frame::new().inner_margin(gap::margin(gap::SNUG, 0.0)).show(ui, |ui| { + crate::titlebar::area_switch::rail(ui, Area::Http, language, actions); + }); head(ui, view, actions, language); if view.creating_under(None).is_some() { create_form(ui, view, actions, language); @@ -136,10 +129,7 @@ fn foot(ui: &mut Ui, state: &AppState, actions: &mut Actions) { } let words = tr(keys::http::cookies::OPEN); if foot_item(ui, &words, "http-cookies-open", false).clicked() { - push( - actions, - Action::Cookies(crate::state::http::cookies::Asked::Open), - ); + push(actions, Action::Cookies(crate::state::http::cookies::Asked::Open)); } } @@ -156,18 +146,10 @@ fn foot_item(ui: &mut Ui, words: &str, author_id: &str, on: bool) -> egui::Respo ); let rect = response.rect; if on || response.hovered() { - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_2); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), p.bg_2); } let ink = if on { p.amber_text } else { p.text_1 }; - let galley = widgets::text( - ui, - words, - font::READING, - 400.0, - FontFamily::Proportional, - ink, - ); + let galley = widgets::text(ui, words, font::READING, 400.0, FontFamily::Proportional, ink); let at = pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, ink); response @@ -184,10 +166,7 @@ fn push(actions: &mut Actions, action: Action) { } fn item(row: &RailRow) -> HttpItem { - HttpItem { - kind: row.kind, - id: row.id.clone(), - } + HttpItem { kind: row.kind, id: row.id.clone() } } /// « COLLECTIONS », and what makes one: its name when there is room, an icon otherwise. Not a @@ -195,25 +174,12 @@ fn item(row: &RailRow) -> HttpItem { fn head(ui: &mut Ui, view: &mut RailView, actions: &mut Actions, language: i18n::Language) { let p = palette(ui.ctx()); let new = i18n::translate(language, keys::http::rail::NEW_COLLECTION, &[]); - let worded = (ui.available_width() + 8.0 >= WORDED_FROM).then(|| { - format!( - "+ {}", - i18n::translate(language, keys::http::rail::COLLECTION, &[]) - ) - }); + let worded = (ui.available_width() + 8.0 >= WORDED_FROM) + .then(|| format!("+ {}", i18n::translate(language, keys::http::rail::COLLECTION, &[]))); ui.horizontal(|ui| { let title = i18n::translate(language, keys::http::rail::TITLE, &[]).to_uppercase(); - let galley = widgets::text( - ui, - &title, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - let button = worded - .as_deref() - .map_or(widgets::MIN_TARGET, |words| Button::width(ui, words)); + let galley = widgets::text(ui, &title, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); + let button = worded.as_deref().map_or(widgets::MIN_TARGET, |words| Button::width(ui, words)); let room = ui.available_width() - button - ui.spacing().item_spacing.x; let (rect, response) = ui.allocate_exact_size(Vec2::new(room, widgets::MIN_TARGET), egui::Sense::hover()); @@ -260,18 +226,11 @@ fn empty(ui: &mut Ui, view: &mut RailView, actions: &mut Actions, language: i18n egui::Frame::new() .inner_margin(gap::margin(gap::INSET, gap::TIGHT)) .show(ui, |ui| { - let label = egui::Label::new( - egui::RichText::new(&words) - .size(font::CONTROL) - .color(p.text_2), - ) - .wrap(); + let label = + egui::Label::new(egui::RichText::new(&words).size(font::CONTROL).color(p.text_2)).wrap(); let response = ui.add(label); widgets::address(ui, &response, "http-rail-empty"); - if Button::new(&new, "http-rail-empty-create") - .show(ui) - .clicked() - { + if Button::new(&new, "http-rail-empty-create").show(ui).clicked() { start_collection(view, actions); } }); @@ -282,11 +241,7 @@ fn empty(ui: &mut Ui, view: &mut RailView, actions: &mut Actions, language: i18n fn tree(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: &mut Actions) { let rows = state.http.rows(); let attached = attached_row(state, view); - let extra = if attached.is_some() { - view.attached - } else { - 0.0 - }; + let extra = if attached.is_some() { view.attached } else { 0.0 }; let scroll_to = state .http .said() @@ -309,10 +264,8 @@ fn tree(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: &mut Action if attached.is_some_and(|under| under < at) { top += extra; } - let rect = Rect::from_min_size( - whole.min + Vec2::new(0.0, top), - Vec2::new(width, row::HEIGHT), - ); + let rect = + Rect::from_min_size(whole.min + Vec2::new(0.0, top), Vec2::new(width, row::HEIGHT)); let seen = rect.translate(-whole.min.to_vec2()); if scroll_to.as_deref() == Some(row.id.as_str()) { ui.scroll_to_rect(rect, None); @@ -328,13 +281,9 @@ fn tree(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: &mut Action draw_row(&mut row_ui, state, view, actions, row); view.drawn.push((rect, at)); if under { - let below = - Rect::from_min_size(rect.left_bottom(), Vec2::new(width, f32::INFINITY)); - let mut below_ui = ui.new_child( - UiBuilder::new() - .scope_id(id.with("attached")) - .max_rect(below), - ); + let below = Rect::from_min_size(rect.left_bottom(), Vec2::new(width, f32::INFINITY)); + let mut below_ui = + ui.new_child(UiBuilder::new().scope_id(id.with("attached")).max_rect(below)); attached_under(&mut below_ui, state, view, actions, row); measured = Some(below_ui.min_rect().height()); } @@ -360,26 +309,13 @@ fn attached_row(state: &AppState, view: &RailView) -> Option { state.http.rows().iter().position(|row| row.id == id) } -fn draw_row( - ui: &mut Ui, - state: &AppState, - view: &mut RailView, - actions: &mut Actions, - row: &RailRow, -) { +fn draw_row(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: &mut Actions, row: &RailRow) { let language = state.language; let look = Look { active: state.http.tabs().active_request() == Some(row.id.as_str()), - drop: view - .drop - .as_ref() - .filter(|(id, _)| *id == row.id) - .map(|(_, zone)| *zone), + drop: view.drop.as_ref().filter(|(id, _)| *id == row.id).map(|(_, zone)| *zone), moved: moved(ui.ctx(), state, row), - dragged: view - .dragging - .as_ref() - .is_some_and(|dragged| dragged.id == row.id), + dragged: view.dragging.as_ref().is_some_and(|dragged| dragged.id == row.id), renaming: view.renaming(&row.id), }; if look.moved.is_some() { @@ -428,22 +364,12 @@ fn moved(ctx: &egui::Context, state: &AppState, row: &RailRow) -> Option<(Moved, return None; }; // The mark is the style the fade comes down to: where motion is cut short it stays whole. - let strength = if state.reduced_motion { - 1.0 - } else { - crate::theme::motion::fading(ctx, mark.since) - }; + let strength = if state.reduced_motion { 1.0 } else { crate::theme::motion::fading(ctx, mark.since) }; Some((which, strength)) } /// `Alt` and an arrow move the row, `F2` renames it, `Delete` asks before deleting it. -fn row_keys( - ui: &Ui, - name: &egui::Response, - view: &mut RailView, - actions: &mut Actions, - row: &RailRow, -) { +fn row_keys(ui: &Ui, name: &egui::Response, view: &mut RailView, actions: &mut Actions, row: &RailRow) { if !widgets::takes_keys(ui, name) { return; } @@ -455,14 +381,7 @@ fn row_keys( ]; for (key, moved) in keys { if ui.input_mut(|input| input.consume_key(Modifiers::ALT, key)) { - push( - actions, - Action::KeyMove { - item: item(row), - name: row.name.clone(), - key: moved, - }, - ); + push(actions, Action::KeyMove { item: item(row), name: row.name.clone(), key: moved }); } } if ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::F2)) { @@ -492,11 +411,7 @@ const RUN: &str = "http-node-run"; /// A request holds nothing: it is renamed, copied or deleted. The three kinds of request sit /// behind one entry, as a card's priorities do. -fn node_menu( - menu: &egui::Response, - row: &RailRow, - language: i18n::Language, -) -> Option<&'static str> { +fn node_menu(menu: &egui::Response, row: &RailRow, language: i18n::Language) -> Option<&'static str> { use keys::http::{kinds::new, rail::actions}; let tr = |key| i18n::translate(language, key, &[]); let words = [ @@ -533,19 +448,9 @@ fn node_menu( ]; widgets::menu(menu, &items).map(str::to_owned) }?; - [ - NEW_HTTP, - NEW_GRAPHQL, - NEW_WEBSOCKET, - NEW_FOLDER, - RENAME, - DUPLICATE, - DELETE, - SETTINGS, - RUN, - ] - .into_iter() - .find(|known| *known == chosen) + [NEW_HTTP, NEW_GRAPHQL, NEW_WEBSOCKET, NEW_FOLDER, RENAME, DUPLICATE, DELETE, SETTINGS, RUN] + .into_iter() + .find(|known| *known == chosen) } fn on_menu( @@ -567,25 +472,16 @@ fn on_menu( } RUN => { let target = crate::state::http::runner::Target { - item: HttpItem { - kind: row.kind, - id: row.id.clone(), - }, + item: HttpItem { kind: row.kind, id: row.id.clone() }, name: row.name.clone(), }; let asked = crate::state::http::runner::Asked::Open(target); return push(actions, Action::Runner(asked)); } DUPLICATE => { - let name = i18n::translate( - language, - keys::http::rail::COPY_NAME, - &[("name", row.name.as_str().into())], - ); - let write = Write::Duplicate { - item: item(row), - name, - }; + let name = + i18n::translate(language, keys::http::rail::COPY_NAME, &[("name", row.name.as_str().into())]); + let write = Write::Duplicate { item: item(row), name }; return push(actions, Action::Write(write)); } _ => { @@ -605,13 +501,7 @@ fn on_menu( } /// What opens under a row: the name of what is made in it, or the question before deleting it. -fn attached_under( - ui: &mut Ui, - state: &AppState, - view: &mut RailView, - actions: &mut Actions, - row: &RailRow, -) { +fn attached_under(ui: &mut Ui, state: &AppState, view: &mut RailView, actions: &mut Actions, row: &RailRow) { let language = state.language; if let Some(deleting) = state.http.deleting() && deleting.item.id == row.id @@ -646,15 +536,8 @@ fn create_form(ui: &mut Ui, view: &mut RailView, actions: &mut Actions, language let typed = ui .horizontal(|ui| { ui.add_space(indent); - ui.vertical(|ui| { - forms::name_form( - ui, - draft, - &words, - ("http-create-input", "http-create-submit"), - ) - }) - .inner + ui.vertical(|ui| forms::name_form(ui, draft, &words, ("http-create-input", "http-create-submit"))) + .inner }) .inner; match typed { @@ -705,22 +588,14 @@ fn rename_form( .max_rect(rest) .layout(egui::Layout::left_to_right(egui::Align::Center)), ); - let typed = forms::inline_form( - &mut inside, - draft, - &words, - ("http-rename-input", "http-rename-submit"), - ); + let typed = forms::inline_form(&mut inside, draft, &words, ("http-rename-input", "http-rename-submit")); match typed { Typed::Typing => {} Typed::Dropped => view.form = None, Typed::Name(name) => { view.form = None; if name != row.name { - let write = Write::Rename { - item: item(row), - name, - }; + let write = Write::Rename { item: item(row), name }; push(actions, Action::Write(write)); } } @@ -742,9 +617,7 @@ fn drop_dragged(ui: &Ui, state: &AppState, view: &mut RailView, actions: &mut Ac let zone = match target.kind { HttpItemKind::Request if share < 0.5 => DropZone::Before, HttpItemKind::Request => DropZone::After, - HttpItemKind::Collection if dragged.kind != HttpItemKind::Collection => { - DropZone::Inside - } + HttpItemKind::Collection if dragged.kind != HttpItemKind::Collection => DropZone::Inside, _ if share < 0.25 => DropZone::Before, _ if share > 0.75 => DropZone::After, _ => DropZone::Inside, diff --git a/crates/ui/src/http/rail/row.rs b/crates/ui/src/http/rail/row.rs index 03618bf5f..bf5c60000 100644 --- a/crates/ui/src/http/rail/row.rs +++ b/crates/ui/src/http/rail/row.rs @@ -4,9 +4,7 @@ //! pointer or the keyboard is on it. use crate::theme::tokens::{font, radius}; -use egui::{ - Color32, CornerRadius, FontFamily, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, -}; +use egui::{Color32, CornerRadius, FontFamily, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2}; use engine::http::model::HttpItemKind; use i18n::keys; @@ -50,8 +48,7 @@ pub(super) struct Drawn { } pub(super) fn show(ui: &mut Ui, row: &RailRow, look: &Look, language: i18n::Language) -> Drawn { - let (whole, _) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), HEIGHT), Sense::hover()); + let (whole, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), HEIGHT), Sense::hover()); level_lines(ui, whole, row.depth); #[expect(clippy::cast_precision_loss, reason = "a few levels")] let indent = row.depth as f32 * INDENT; @@ -68,24 +65,14 @@ pub(super) fn show(ui: &mut Ui, row: &RailRow, look: &Look, language: i18n::Lang let twisty = (row.kind != HttpItemKind::Request).then(|| twisty(&mut inside, row, language)); let rest = Rect::from_min_max(inside.cursor().min, rest.max); if look.renaming { - return Drawn { - twisty, - name: None, - menu: None, - rest, - }; + return Drawn { twisty, name: None, menu: None, rest }; } let lit = inside.rect_contains_pointer(rest); let (name, menu) = name_and_menu(&mut inside, row, look, (lit, language)); if let Some(zone) = look.drop { drop_mark(ui, rest, zone); } - Drawn { - twisty, - name: Some(name), - menu: Some(menu), - rest, - } + Drawn { twisty, name: Some(name), menu: Some(menu), rest } } /// A line a level, so that depth is read at rest: at 8 px a level, a row above a folder and a @@ -95,18 +82,13 @@ fn level_lines(ui: &Ui, row: Rect, depth: usize) { for level in 0..depth { #[expect(clippy::cast_precision_loss, reason = "a few levels")] let x = row.left() + level as f32 * INDENT + INDENT / 2.0; - ui.painter() - .vline(x.round() + 0.5, row.y_range(), Stroke::new(1.0, p.line)); + ui.painter().vline(x.round() + 0.5, row.y_range(), Stroke::new(1.0, p.line)); } } fn twisty(ui: &mut Ui, row: &RailRow, language: i18n::Language) -> Response { let p = palette(ui.ctx()); - let key = if row.expanded { - keys::http::rail::COLLAPSE - } else { - keys::http::rail::EXPAND - }; + let key = if row.expanded { keys::http::rail::COLLAPSE } else { keys::http::rail::EXPAND }; let label = i18n::translate(language, key, &[("name", row.name.as_str().into())]); let response = interact( ui, @@ -117,13 +99,8 @@ fn twisty(ui: &mut Ui, row: &RailRow, language: i18n::Language) -> Response { CornerRadius::same(radius::CONTROL), ); let expanded = row.expanded; - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_expanded(expanded)); - let ink = if response.hovered() { - p.text_0 - } else { - p.text_2 - }; + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(expanded)); + let ink = if response.hovered() { p.text_0 } else { p.text_2 }; widgets::triangle(ui, response.rect.center(), row.expanded, ink); response } @@ -152,8 +129,7 @@ fn name_and_menu( ); if row.kind != HttpItemKind::Request { let expanded = row.expanded; - ui.ctx() - .accesskit_node_builder(name.id, |node| node.set_expanded(expanded)); + ui.ctx().accesskit_node_builder(name.id, |node| node.set_expanded(expanded)); } let rect = name.rect; let collection = row.kind == HttpItemKind::Collection; @@ -178,39 +154,21 @@ fn name_and_menu( let middle = rect.center().y; if let Some(badge) = row.badge { let hue = badge_hue(ui, badge); - let galley = widgets::text( - ui, - badge.short(), - font::CAPTION, - 700.0, - FontFamily::Monospace, - hue, - ); + let galley = widgets::text(ui, badge.short(), font::CAPTION, 700.0, FontFamily::Monospace, hue); let width = galley.size().x; - ui.painter().galley( - egui::pos2(left, middle - galley.size().y / 2.0), - galley, - hue, - ); + ui.painter() + .galley(egui::pos2(left, middle - galley.size().y / 2.0), galley, hue); left += width + 6.0; } - let right = if shown { - menu_rect.left() - } else { - rect.right() - 5.0 - }; + let right = if shown { menu_rect.left() } else { rect.right() - 5.0 }; let weight = if collection { 600.0 } else { 400.0 }; let galley = widgets::one_line(ui, &row.name, (font::BODY, weight), ink, right - left); - ui.painter().galley( - egui::pos2(left, middle - galley.size().y / 2.0), - galley, - ink, - ); + ui.painter() + .galley(egui::pos2(left, middle - galley.size().y / 2.0), galley, ink); if shown { let glyph = Rect::from_center_size(menu_rect.center(), Vec2::splat(16.0)); if menu.hovered() { - ui.painter() - .rect_filled(menu_rect, CornerRadius::same(radius::CONTROL), p.bg_3); + ui.painter().rect_filled(menu_rect, CornerRadius::same(radius::CONTROL), p.bg_3); } icons::paint(ui, glyph, Icon::Ellipsis, p.text_0); } @@ -219,11 +177,7 @@ fn name_and_menu( /// Over the end of the name, there at rest for the keyboard's order, inked only when shown. fn menu_button(ui: &mut Ui, rect: Rect, row: &RailRow, language: i18n::Language) -> Response { - let label = i18n::translate( - language, - keys::http::rail::OPTIONS, - &[("name", row.name.as_str().into())], - ); + let label = i18n::translate(language, keys::http::rail::OPTIONS, &[("name", row.name.as_str().into())]); let mut over = ui.new_child(egui::UiBuilder::new().max_rect(rect)); interact( &mut over, @@ -247,22 +201,16 @@ fn drop_mark(ui: &Ui, rest: Rect, zone: DropZone) { egui::pos2(rest.left() + 4.0, y - 1.0), egui::pos2(rest.right() - 4.0, y + 1.0), ); - ui.painter() - .rect_filled(bar, CornerRadius::same(radius::MARK), p.amber_text); + ui.painter().rect_filled(bar, CornerRadius::same(radius::MARK), p.amber_text); }; match zone { DropZone::Before => line(rest.top()), DropZone::After => line(rest.bottom()), DropZone::Inside => { let corner = CornerRadius::same(radius::CONTROL); + ui.painter().rect_filled(rest, corner, p.amber_text.gamma_multiply(0.08)); ui.painter() - .rect_filled(rest, corner, p.amber_text.gamma_multiply(0.08)); - ui.painter().rect_stroke( - rest, - corner, - Stroke::new(1.0, p.amber_dim), - StrokeKind::Inside, - ); + .rect_stroke(rest, corner, Stroke::new(1.0, p.amber_dim), StrokeKind::Inside); } } } diff --git a/crates/ui/src/http/request/auth.rs b/crates/ui/src/http/request/auth.rs index fac9a2fbc..fc42dc471 100644 --- a/crates/ui/src/http/request/auth.rs +++ b/crates/ui/src/http/request/auth.rs @@ -25,13 +25,7 @@ enum Kind { } impl Kind { - const ALL: [Self; 5] = [ - Self::Inherit, - Self::None, - Self::Basic, - Self::Bearer, - Self::ApiKey, - ]; + const ALL: [Self; 5] = [Self::Inherit, Self::None, Self::Basic, Self::Bearer, Self::ApiKey]; fn of(auth: &RequestAuth) -> Self { match auth { @@ -58,18 +52,11 @@ impl Kind { match self { Self::Inherit => RequestAuth::Inherit, Self::None => RequestAuth::None, - Self::Basic => RequestAuth::Basic { - username: String::new(), - password: String::new(), - }, - Self::Bearer => RequestAuth::Bearer { - token: String::new(), - }, - Self::ApiKey => RequestAuth::ApiKey { - name: String::new(), - value: String::new(), - place: KeyPlace::Header, - }, + Self::Basic => RequestAuth::Basic { username: String::new(), password: String::new() }, + Self::Bearer => RequestAuth::Bearer { token: String::new() }, + Self::ApiKey => { + RequestAuth::ApiKey { name: String::new(), value: String::new(), place: KeyPlace::Header } + } } } } @@ -97,15 +84,10 @@ pub(crate) fn show( match auth.clone() { RequestAuth::Inherit => inherited(ui, editor.above, language), RequestAuth::None => hint(ui, &tr(keys::http::auth::NONE_HINT)), - RequestAuth::Basic { - mut username, - mut password, - } => { + RequestAuth::Basic { mut username, mut password } => { let label = tr(keys::http::auth::USERNAME); let typed = field(ui, &label, |ui| { - TextField::new(&mut username, &label, "http-auth-username") - .show(ui) - .changed() + TextField::new(&mut username, &label, "http-auth-username").show(ui).changed() }); let label = tr(keys::http::auth::secrets::PASSWORD); let secret = secret(ui, (&label, &mut password), revealed, language); @@ -119,11 +101,7 @@ pub(crate) fn show( changed = Some(RequestAuth::Bearer { token }); } } - RequestAuth::ApiKey { - mut name, - mut value, - mut place, - } => { + RequestAuth::ApiKey { mut name, mut value, mut place } => { let label = tr(keys::http::auth::KEY_NAME); let mut edited = field(ui, &label, |ui| { TextField::new(&mut name, &label, "http-auth-key-name") @@ -187,20 +165,10 @@ fn kind_line(ui: &mut Ui, editor: &AuthField<'_>, language: i18n::Language) -> O fn place_line(ui: &mut Ui, place: &mut KeyPlace, language: i18n::Language) -> bool { let tr = |key| i18n::translate(language, key, &[]); - let (header, query) = ( - tr(keys::http::auth::places::HEADER), - tr(keys::http::auth::places::QUERY), - ); - let options = [ - (KeyPlace::Header, header.as_str()), - (KeyPlace::Query, query.as_str()), - ]; + let (header, query) = (tr(keys::http::auth::places::HEADER), tr(keys::http::auth::places::QUERY)); + let options = [(KeyPlace::Header, header.as_str()), (KeyPlace::Query, query.as_str())]; let label = tr(keys::http::auth::PLACE); - field(ui, &label, |ui| { - ChoiceMenu::new(&label, "http-auth-place", &options) - .show(ui, place) - .changed() - }) + field(ui, &label, |ui| ChoiceMenu::new(&label, "http-auth-place", &options).show(ui, place).changed()) } /// The secret, masked until asked for; `true` when it changed. @@ -213,18 +181,12 @@ fn secret( field(ui, label, |ui| { let eye = i18n::translate( language, - if *revealed { - keys::http::auth::HIDE - } else { - keys::http::auth::SHOW - }, + if *revealed { keys::http::auth::HIDE } else { keys::http::auth::SHOW }, &[], ); let icon = if *revealed { Icon::EyeOff } else { Icon::Eye }; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let pressed = IconButton::new(icon, &eye, "http-auth-reveal") - .pressed(*revealed) - .show(ui); + let pressed = IconButton::new(icon, &eye, "http-auth-reveal").pressed(*revealed).show(ui); if pressed.clicked() { *revealed = !*revealed; } @@ -238,22 +200,20 @@ fn secret( } /// « Bearer {{accessToken}} », the secret masked unless it is a variable. -fn summary(auth: &RequestAuth) -> String { +fn summary(auth: &RequestAuth, language: i18n::Language) -> String { let secret = |value: &str| { let whole = api::http::spans(value) .first() .is_some_and(|(range, _)| *range == (0..value.len())); - if whole { - value.to_owned() - } else { - "••••••".to_owned() - } + if whole { value.to_owned() } else { "••••••".to_owned() } }; match auth { RequestAuth::Basic { username, .. } => format!("Basic {username}"), RequestAuth::Bearer { token } => format!("Bearer {}", secret(token)), RequestAuth::ApiKey { name, value, .. } => format!("{name}: {}", secret(value)), - RequestAuth::Inherit | RequestAuth::None => String::new(), + RequestAuth::Inherit | RequestAuth::None => { + i18n::translate(language, keys::http::auth::kinds::NONE, &[]) + } } } @@ -278,7 +238,7 @@ fn inherited_words(above: &Inherited, language: i18n::Language) -> String { _ => keys::http::auth::from::COLLECTION, }; let origin = i18n::translate(language, key, &[("name", from.name.as_str().into())]); - format!("{} {origin}", summary(&above.auth)) + format!("{} {origin}", summary(&above.auth, language)) } fn hint(ui: &mut Ui, words: &str) { @@ -286,3 +246,6 @@ fn hint(ui: &mut Ui, words: &str) { let words = egui::RichText::new(words).size(font::LABEL).color(p.text_2); ui.add(egui::Label::new(words).wrap()); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/request/auth/tests.rs b/crates/ui/src/http/request/auth/tests.rs new file mode 100644 index 000000000..85e695130 --- /dev/null +++ b/crates/ui/src/http/request/auth/tests.rs @@ -0,0 +1,155 @@ +//! A request's auth, and what « Inherited » says it takes. + +use engine::http::model::{ContainerSettings, HttpItemKind}; +use engine::http::settings::{HttpOrigin, inherit}; +use i18n::Language; + +use super::*; + +fn above(kind: HttpItemKind, auth: RequestAuth) -> Inherited { + let origin = HttpOrigin { kind, id: "id".to_owned(), name: "API".to_owned() }; + let settings = ContainerSettings { auth, ..ContainerSettings::default() }; + inherit(&[(origin, settings)]) +} + +/// The secret masked, a variable named. +#[test] +fn what_is_inherited_is_said_with_where_from() { + let bearer = |token: &str| RequestAuth::Bearer { token: token.to_owned() }; + let key = + RequestAuth::ApiKey { name: "X-Key".to_owned(), value: "s3cret".to_owned(), place: KeyPlace::Header }; + let basic = RequestAuth::Basic { username: "ada".to_owned(), password: "s3cret".to_owned() }; + for (kind, auth, words) in [ + (HttpItemKind::Collection, bearer("s3cret"), "Bearer •••••• inherited from the collection API"), + (HttpItemKind::Folder, bearer("{{token}}"), "Bearer {{token}} inherited from the folder API"), + (HttpItemKind::Folder, bearer("x{{token}}"), "Bearer •••••• inherited from the folder API"), + (HttpItemKind::Collection, key, "X-Key: •••••• inherited from the collection API"), + (HttpItemKind::Collection, basic, "Basic ada inherited from the collection API"), + (HttpItemKind::Folder, RequestAuth::None, "None inherited from the folder API"), + ] { + assert_eq!(inherited_words(&above(kind, auth), Language::En), words); + } + let nothing = inherit(&[]); + assert_eq!(inherited_words(¬hing, Language::En), "Nothing above sets an auth: none is sent."); +} + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +struct Screen { + auth: RequestAuth, + allow_inherit: bool, + above: Option, + revealed: bool, +} + +fn screen(auth: RequestAuth) -> Harness<'static, Screen> { + let state = Screen { auth, allow_inherit: true, above: None, revealed: false }; + let mut harness = crate::testing::harness().with_size(egui::vec2(700.0, 500.0)).build_ui_state( + |ui, screen: &mut Screen| { + let field = AuthField { + auth: &screen.auth, + above: screen.above.as_ref(), + allow_inherit: screen.allow_inherit, + }; + if let Some(auth) = show(ui, &field, &mut screen.revealed, Language::En) { + screen.auth = auth; + } + }, + state, + ); + harness.run(); + harness +} + +fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness.get_by(|node| node.author_id() == Some(author_id)).click(); + harness.run(); + harness.run(); +} + +fn type_in(harness: &mut Harness<'_, Screen>, author_id: &str, words: &str) { + click(harness, author_id); + harness.get_by(|node| node.author_id() == Some(author_id)).type_text(words); + harness.run(); +} + +fn basic(username: &str, password: &str) -> RequestAuth { + RequestAuth::Basic { username: username.to_owned(), password: password.to_owned() } +} + +fn key(name: &str, value: &str, place: KeyPlace) -> RequestAuth { + RequestAuth::ApiKey { name: name.to_owned(), value: value.to_owned(), place } +} + +/// In the menu's order. +fn kinds() -> [RequestAuth; 5] { + let bearer = RequestAuth::Bearer { token: String::new() }; + [RequestAuth::Inherit, RequestAuth::None, basic("", ""), bearer, key("", "", KeyPlace::Header)] +} + +#[test] +fn a_kind_chosen_starts_empty() { + for (rank, auth) in kinds().into_iter().enumerate() { + let from = if rank == 0 { kinds()[1].clone() } else { RequestAuth::Inherit }; + let mut harness = screen(from); + click(&mut harness, "http-auth-kind"); + click(&mut harness, &format!("http-auth-kind-{rank}")); + assert_eq!(harness.state().auth, auth); + } +} + +/// A filled auth is not lost to its own name in the menu. +#[test] +fn the_kind_in_force_chosen_again_keeps_what_it_holds() { + let mut harness = screen(basic("ada", "s3cret")); + click(&mut harness, "http-auth-kind"); + click(&mut harness, "http-auth-kind-2"); + + assert_eq!(harness.state().auth, basic("ada", "s3cret")); +} + +#[test] +fn each_kind_s_fields_are_typed_into() { + let mut harness = screen(basic("", "")); + type_in(&mut harness, "http-auth-username", "ada"); + type_in(&mut harness, "http-auth-secret", "s3cret"); + assert_eq!(harness.state().auth, basic("ada", "s3cret")); + + let mut harness = screen(key("", "", KeyPlace::Header)); + type_in(&mut harness, "http-auth-key-name", "X-Key"); + type_in(&mut harness, "http-auth-secret", "v"); + click(&mut harness, "http-auth-place"); + click(&mut harness, "http-auth-place-1"); + assert_eq!(harness.state().auth, key("X-Key", "v", KeyPlace::Query)); +} + +#[test] +fn nothing_to_inherit_from_yet_is_said() { + let harness = screen(RequestAuth::Inherit); + let words = i18n::translate(Language::En, keys::http::auth::PLACE_FIRST, &[]); + + assert!( + crate::testing::painted(&harness) + .iter() + .any(|text| words.starts_with(text.as_str()) || text.contains(&words)) + ); +} + +/// A collection's « inherited » is none at all, and is not offered. +#[test] +fn with_nothing_above_there_is_nothing_to_inherit() { + let mut harness = screen(RequestAuth::Inherit); + harness.state_mut().allow_inherit = false; + harness.run(); + let kind = harness.get_by(|node| node.author_id() == Some("http-auth-kind")); + let shown = kind.accesskit_node(); + let words = [shown.value(), shown.label()].map(Option::unwrap_or_default).join(" "); + assert!(words.contains("None"), "{words}"); + click(&mut harness, "http-auth-kind"); + let offered = harness + .query_all_by(|node| node.author_id().is_some_and(|id| id.starts_with("http-auth-kind-"))) + .count(); + + assert_eq!(offered, 4); +} diff --git a/crates/ui/src/http/request/body.rs b/crates/ui/src/http/request/body.rs index b4d9fe40b..8dd58f6db 100644 --- a/crates/ui/src/http/request/body.rs +++ b/crates/ui/src/http/request/body.rs @@ -2,9 +2,7 @@ //! a file is a path, read when the request is sent. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - Align, CornerRadius, FontFamily, FontId, Layout, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, -}; +use egui::{Align, CornerRadius, FontFamily, FontId, Layout, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2}; use engine::http::BodyAnswer; use engine::http::model::RequestBody; use engine::json::parse::JsonError; @@ -81,13 +79,7 @@ pub(super) fn text_box_of( (output.changed.map(|_| editor.text()), output.response) } -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - tab: &Tab, - editor: &mut Editor, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, tab: &Tab, editor: &mut Editor, actions: &mut Actions) { let language = state.language; let said = state.http.body_answer(); head(ui, tab, said, language, actions); @@ -103,11 +95,7 @@ pub(super) fn show( RequestBody::Text { text } => typed(ui, tab, (editor, text), language, actions), RequestBody::Form { fields } => { let label = i18n::translate(language, keys::http::body::kinds::FORM, &[]); - let table = table::Table { - kind: "form", - label: &label, - headers: false, - }; + let table = table::Table { kind: "form", label: &label, headers: false }; if let Some(fields) = table::show(ui, &table, fields, language) { edit(actions, tab, DraftEdit::Body(RequestBody::Form { fields })); } @@ -125,17 +113,11 @@ pub(super) fn show( } fn pick(actions: &mut Actions, tab: &Tab, target: FileFor) { - actions.push(Asked::Http(Action::PickFile { - key: tab.key.clone(), - target, - })); + actions.push(Asked::Http(Action::PickFile { key: tab.key.clone(), target })); } fn choose(actions: &mut Actions, tab: &Tab, kind: BodyKind) { - actions.push(Asked::Http(Action::ChooseBody { - key: tab.key.clone(), - kind, - })); + actions.push(Asked::Http(Action::ChooseBody { key: tab.key.clone(), kind })); } fn kind_name(kind: BodyKind) -> i18n::Key { @@ -150,13 +132,7 @@ fn kind_name(kind: BodyKind) -> i18n::Key { } } -fn head( - ui: &mut Ui, - tab: &Tab, - said: Option<&BodyAnswer>, - language: i18n::Language, - actions: &mut Actions, -) { +fn head(ui: &mut Ui, tab: &Tab, said: Option<&BodyAnswer>, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); let names = BodyKind::ALL.map(|kind| i18n::translate(language, kind_name(kind), &[])); let options: Vec<(BodyKind, &str)> = BodyKind::ALL @@ -167,22 +143,12 @@ fn head( ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::BLOCKS; let mut kind = BodyKind::of(&tab.draft.document.body); - if Segmented::new(&options, "http-body-kind") - .show(ui, &mut kind) - .changed() - { + if Segmented::new(&options, "http-body-kind").show(ui, &mut kind).changed() { choose(actions, tab, kind); } if let Some(sent_as) = said.and_then(|said| said.content_type.as_deref()) { - let words = i18n::translate( - language, - keys::http::body::SENT_AS, - &[("type", sent_as.into())], - ); - let words = egui::RichText::new(words) - .monospace() - .size(font::LABEL) - .color(p.text_2); + let words = i18n::translate(language, keys::http::body::SENT_AS, &[("type", sent_as.into())]); + let words = egui::RichText::new(words).monospace().size(font::LABEL).color(p.text_2); let shown = ui.add(egui::Label::new(words)); widgets::address(ui, &shown, "http-body-type"); } @@ -199,16 +165,11 @@ fn unusual(ui: &mut Ui, tab: &Tab, language: i18n::Language, actions: &mut Actio keys::http::body::UNUSUAL, &[("method", tab.draft.method.as_str().into())], ); - let words = egui::RichText::new(words) - .size(font::BODY) - .color(p.amber_text); + let words = egui::RichText::new(words).size(font::BODY).color(p.amber_text); let shown = ui.add(egui::Label::new(words)); widgets::address(ui, &shown, "http-body-unusual"); let to_none = i18n::translate(language, keys::http::body::TO_NONE, &[]); - if Button::new(&to_none, "http-body-to-none") - .show(ui) - .clicked() - { + if Button::new(&to_none, "http-body-to-none").show(ui).clicked() { choose(actions, tab, BodyKind::None); } }); @@ -223,20 +184,11 @@ fn typed( ) { let kind = BodyKind::of(&tab.draft.document.body); let label = i18n::translate(language, kind_name(kind), &[]); - let field = TextBox { - label: &label, - author_id: "http-body-text", - hint: "", - height: BOX_HEIGHT, - }; + let field = TextBox { label: &label, author_id: "http-body-text", hint: "", height: BOX_HEIGHT }; let Some(text) = text_box(ui, editor, text, &field, language) else { return; }; - let body = if kind == BodyKind::Json { - RequestBody::Json { text } - } else { - RequestBody::Text { text } - }; + let body = if kind == BodyKind::Json { RequestBody::Json { text } } else { RequestBody::Text { text } }; edit(actions, tab, DraftEdit::Body(body)); } @@ -247,11 +199,7 @@ pub(super) fn invalid(problem: &JsonError, language: i18n::Language) -> String { i18n::translate( language, keys::json::INVALID_AT, - &[ - ("line", problem.line.into()), - ("column", problem.column.into()), - ("format", "JSON".into()), - ], + &[("line", problem.line.into()), ("column", problem.column.into()), ("format", "JSON".into()),], ), i18n::translate(language, json_explorer::reason(problem.reason), &[]), ) @@ -276,21 +224,15 @@ fn status( .show(ui) .clicked() { - actions.push(Asked::Http(Action::Rewrite { - key: tab.key.clone(), - part: Rewritten::Body, - })); + actions.push(Asked::Http(Action::Rewrite { key: tab.key.clone(), part: Rewritten::Body })); } ui.with_layout(Layout::left_to_right(Align::Center), |ui| { if let Some(problem) = problem { - let words = egui::RichText::new(invalid(problem, language)) - .size(font::LABEL) - .color(p.red); + let words = egui::RichText::new(invalid(problem, language)).size(font::LABEL).color(p.red); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, "http-body-problem"); } else if !blank { - let words = - i18n::translate(language, keys::json::VALID, &[("format", "JSON".into())]); + let words = i18n::translate(language, keys::json::VALID, &[("format", "JSON".into())]); let words = egui::RichText::new(words).size(font::LABEL).color(p.green); let shown = ui.add(egui::Label::new(words)); widgets::address(ui, &shown, "http-body-valid"); @@ -311,15 +253,8 @@ fn file(ui: &mut Ui, tab: &Tab, path: &str, language: i18n::Language, actions: & pick(actions, tab, FileFor::Body); } ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - let words = if path.is_empty() { - tr(keys::http::body::NO_FILE) - } else { - path.to_owned() - }; - let words = egui::RichText::new(words) - .monospace() - .size(font::BODY) - .color(p.text_1); + let words = if path.is_empty() { tr(keys::http::body::NO_FILE) } else { path.to_owned() }; + let words = egui::RichText::new(words).monospace().size(font::BODY).color(p.text_1); let shown = ui.add(egui::Label::new(words).truncate()); widgets::address(ui, &shown, "http-body-path"); }); diff --git a/crates/ui/src/http/request/chips.rs b/crates/ui/src/http/request/chips.rs index 4b66ab724..6698d35bf 100644 --- a/crates/ui/src/http/request/chips.rs +++ b/crates/ui/src/http/request/chips.rs @@ -43,13 +43,9 @@ fn chip(ui: &mut Ui, state: &AppState, known: &UsedVariable, actions: &mut Actio CornerRadius::same(radius::CONTROL), ); let rect = response.rect; - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::CONTROL), - hue.gamma_multiply(0.16), - ); ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, hue); + .rect_filled(rect, CornerRadius::same(radius::CONTROL), hue.gamma_multiply(0.16)); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, hue); card(ui, &response, state, known, actions); if response.clicked() && known.resolved.is_none() { actions.push(Asked::Http(Action::Define(known.name.clone()))); @@ -62,9 +58,7 @@ fn card(ui: &Ui, chip: &Response, state: &AppState, known: &UsedVariable, action let card_id = chip.id.with("card"); let drawn: Option = ui.data(|data| data.get_temp(card_id)); let pointer = ui.ctx().pointer_hover_pos(); - let kept = drawn - .zip(pointer) - .is_some_and(|(rect, at)| rect.contains(at)); + let kept = drawn.zip(pointer).is_some_and(|(rect, at)| rect.contains(at)); let open = chip.hovered() || chip.has_focus() || kept; let shown = Popup::from_response(chip) .id(card_id) @@ -97,10 +91,7 @@ fn resolved(ui: &mut Ui, state: &AppState, found: &ScopedVariable, card_id: Id) let secret = found.kind == VariableKind::Secret; let mut from = from_words(language, found); if secret { - from = format!( - "{from} · {}", - i18n::translate(language, keys::http::variables::used::SECRET, &[]) - ); + from = format!("{from} · {}", i18n::translate(language, keys::http::variables::used::SECRET, &[])); } head(ui, &found.name, &from, p.text_2); let revealed_id = card_id.with("revealed"); @@ -114,10 +105,7 @@ fn resolved(ui: &mut Ui, state: &AppState, found: &ScopedVariable, card_id: Id) } else { (found.value.clone(), FontFamily::Monospace) }; - let value = egui::RichText::new(&words) - .family(family) - .size(font::LABEL) - .color(p.text_0); + let value = egui::RichText::new(&words).family(family).size(font::LABEL).color(p.text_0); let shown = ui.add(egui::Label::new(value).wrap()); widgets::address(ui, &shown, "http-used-variable-value"); if secret { @@ -127,10 +115,7 @@ fn resolved(ui: &mut Ui, state: &AppState, found: &ScopedVariable, card_id: Id) keys::http::variables::used::REVEAL }; let label = i18n::translate(language, key, &[]); - if Button::new(&label, "http-used-variable-reveal") - .show(ui) - .clicked() - { + if Button::new(&label, "http-used-variable-reveal").show(ui).clicked() { ui.data_mut(|data| data.insert_temp(revealed_id, !revealed)); } } @@ -139,9 +124,7 @@ fn resolved(ui: &mut Ui, state: &AppState, found: &ScopedVariable, card_id: Id) let hidden: Vec = found .shadows .iter() - .filter_map(|scope| { - i18n::Key::find(&format!("http.variables.used.scopes.{}", scope.as_str())) - }) + .filter_map(|scope| i18n::Key::find(&format!("http.variables.used.scopes.{}", scope.as_str()))) .map(|key| i18n::translate(language, key, &[])) .collect(); let words = format!( @@ -158,10 +141,7 @@ fn unset(ui: &mut Ui, state: &AppState, name: &str, actions: &mut Actions) { let none = i18n::translate(state.language, keys::http::variables::used::NONE, &[]); head(ui, name, &none, p.red); let define = define_words(state); - if Button::new(&define, "http-used-variable-define") - .show(ui) - .clicked() - { + if Button::new(&define, "http-used-variable-define").show(ui).clicked() { actions.push(Asked::Http(Action::Define(name.to_owned()))); } } @@ -170,10 +150,7 @@ fn unset(ui: &mut Ui, state: &AppState, name: &str, actions: &mut Actions) { fn head(ui: &mut Ui, name: &str, from: &str, ink: egui::Color32) { let p = palette(ui.ctx()); ui.horizontal(|ui| { - let name = egui::RichText::new(name) - .monospace() - .size(font::LABEL) - .color(p.text_0); + let name = egui::RichText::new(name).monospace().size(font::LABEL).color(p.text_0); ui.label(name); let from = ui.label(egui::RichText::new(from).size(font::META).color(ink)); widgets::address(ui, &from, "http-used-variable-from"); @@ -182,16 +159,9 @@ fn head(ui: &mut Ui, name: &str, from: &str, ink: egui::Color32) { /// « collection API Paiements », « globales »… fn from_words(language: i18n::Language, found: &ScopedVariable) -> String { - let key = i18n::Key::find(&format!( - "http.variables.used.from.{}", - found.scope.as_str() - )); + let key = i18n::Key::find(&format!("http.variables.used.from.{}", found.scope.as_str())); key.map_or_else(String::new, |key| { - i18n::translate( - language, - key, - &[("name", found.from.clone().unwrap_or_default().into())], - ) + i18n::translate(language, key, &[("name", found.from.clone().unwrap_or_default().into())]) }) } @@ -203,10 +173,6 @@ fn define_words(state: &AppState) -> String { keys::http::variables::used::DEFINE, &[("name", active.name.as_str().into())], ), - None => i18n::translate( - state.language, - keys::http::variables::used::DEFINE_GLOBALS, - &[], - ), + None => i18n::translate(state.language, keys::http::variables::used::DEFINE_GLOBALS, &[]), } } diff --git a/crates/ui/src/http/request/composer.rs b/crates/ui/src/http/request/composer.rs index 50d1adccd..3e54ffb59 100644 --- a/crates/ui/src/http/request/composer.rs +++ b/crates/ui/src/http/request/composer.rs @@ -24,28 +24,16 @@ const COLUMN_GAP: f32 = gap::BLOCKS; const NAME_LENGTH: usize = 40; fn send(actions: &mut Actions, tab: &Tab, text: String) { - actions.push(Asked::Http(Action::SendMessage { - key: tab.key.clone(), - text, - })); + actions.push(Asked::Http(Action::SendMessage { key: tab.key.clone(), text })); } fn keep(actions: &mut Actions, tab: &Tab, messages: Vec) { - let websocket = WebsocketDocument { - messages, - ..tab.draft.document.websocket.clone() - }; + let websocket = WebsocketDocument { messages, ..tab.draft.document.websocket.clone() }; edit(actions, tab, DraftEdit::Websocket(websocket)); } /// The message on the left, those kept on the right: three fifths and two. -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - tab: &Tab, - boxes: &mut TextBoxes, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, tab: &Tab, boxes: &mut TextBoxes, actions: &mut Actions) { let whole = ui.available_width() - COLUMN_GAP; let (left, right) = (whole * 0.6, whole * 0.4); let open = state.http.sockets().is_open(&tab.key); @@ -67,16 +55,9 @@ fn compose(ui: &mut Ui, state: &AppState, tab: &Tab, boxes: &mut TextBoxes, acti let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let open = state.http.sockets().is_open(&tab.key); - let (label, hint) = ( - tr(keys::http::socket::MESSAGE), - tr(keys::http::socket::MESSAGE_PLACEHOLDER), - ); - let field = TextBox { - label: &label, - author_id: "http-socket-message", - hint: &hint, - height: MESSAGE_HEIGHT, - }; + let (label, hint) = (tr(keys::http::socket::MESSAGE), tr(keys::http::socket::MESSAGE_PLACEHOLDER)); + let field = + TextBox { label: &label, author_id: "http-socket-message", hint: &hint, height: MESSAGE_HEIGHT }; let text = boxes.message.text(); let (_, typing) = text_box_of(ui, &mut boxes.message, &text, &field, language); let text = boxes.message.text(); @@ -117,10 +98,7 @@ fn compose(ui: &mut Ui, state: &AppState, tab: &Tab, boxes: &mut TextBoxes, acti let line = text.trim().lines().next().unwrap_or_default(); let name: String = line.chars().take(NAME_LENGTH).collect(); let mut messages = tab.draft.document.websocket.messages.clone(); - messages.push(SavedMessage { - name, - text: text.clone(), - }); + messages.push(SavedMessage { name, text: text.clone() }); keep(actions, tab, messages); } }); @@ -150,10 +128,7 @@ fn saved( for (at, message) in messages.iter().enumerate() { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; - if Button::new(&message.name, "http-socket-saved") - .show(ui) - .clicked() - { + if Button::new(&message.name, "http-socket-saved").show(ui).clicked() { boxes.message.replace_all(&message.text); } if Button::new(&tr(keys::http::socket::SEND), "http-socket-saved-send") @@ -168,10 +143,7 @@ fn saved( keys::http::socket::REMOVE, &[("name", message.name.as_str().into())], ); - if IconButton::new(Icon::X, &label, "http-socket-saved-remove") - .show(ui) - .clicked() - { + if IconButton::new(Icon::X, &label, "http-socket-saved-remove").show(ui).clicked() { let mut rest = messages.clone(); rest.remove(at); keep(actions, tab, rest); @@ -191,9 +163,7 @@ pub(super) fn protocols( let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); let document = &tab.draft.document.websocket; - let mut text = typed - .clone() - .unwrap_or_else(|| document.protocols.join(", ")); + let mut text = typed.clone().unwrap_or_else(|| document.protocols.join(", ")); let label = tr(keys::http::socket::PROTOCOLS); let words = egui::RichText::new(&label).size(font::BODY).color(p.text_1); ui.add(egui::Label::new(words)); @@ -210,10 +180,7 @@ pub(super) fn protocols( .filter(|name| !name.is_empty()) .map(str::to_owned) .collect(); - let websocket = WebsocketDocument { - protocols, - ..document.clone() - }; + let websocket = WebsocketDocument { protocols, ..document.clone() }; edit(actions, tab, DraftEdit::Websocket(websocket)); } let hint = egui::RichText::new(tr(keys::http::socket::PROTOCOLS_HINT)) diff --git a/crates/ui/src/http/request/extractions.rs b/crates/ui/src/http/request/extractions.rs index 3d23749ca..507487688 100644 --- a/crates/ui/src/http/request/extractions.rs +++ b/crates/ui/src/http/request/extractions.rs @@ -16,11 +16,7 @@ pub(super) fn show(ui: &mut Ui, tab: &Tab, language: i18n::Language) -> Option bool { let p = palette(ui.ctx()); ui.horizontal(|ui| { ui.spacing_mut().item_spacing = Vec2::new(gap::CONTROLS, 0.0); - let mono = |words: String, ink| { - egui::RichText::new(words) - .monospace() - .size(font::BODY) - .color(ink) - }; + let mono = |words: String, ink| egui::RichText::new(words).monospace().size(font::BODY).color(ink); let path = ui.add(egui::Label::new(mono(rule.path.clone(), p.text_1))); widgets::address(ui, &path, "http-extraction"); let (arrow, _) = ui.allocate_exact_size(Vec2::splat(12.0), egui::Sense::hover()); @@ -64,9 +55,7 @@ fn row(ui: &mut Ui, rule: &Extraction, language: i18n::Language) -> bool { keys::http::extract::REMOVE, &[("variable", rule.variable.as_str().into())], ); - IconButton::new(Icon::X, &label, "http-extraction-remove") - .show(ui) - .clicked() + IconButton::new(Icon::X, &label, "http-extraction-remove").show(ui).clicked() }) .inner } diff --git a/crates/ui/src/http/request/graphql.rs b/crates/ui/src/http/request/graphql.rs index 16b81b910..ec4d83f7b 100644 --- a/crates/ui/src/http/request/graphql.rs +++ b/crates/ui/src/http/request/graphql.rs @@ -44,13 +44,7 @@ fn cell(ui: &mut Ui, width: f32, content: impl FnOnce(&mut Ui)) { }); } -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - tab: &Tab, - boxes: &mut TextBoxes, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, tab: &Tab, boxes: &mut TextBoxes, actions: &mut Actions) { let language = state.language; let said = state.http.graphql_answer(); cells( @@ -82,12 +76,7 @@ pub(super) fn show( } /// The two boxes, and the document as typed this frame. -fn typed( - ui: &mut Ui, - tab: &Tab, - boxes: &mut TextBoxes, - language: i18n::Language, -) -> Option { +fn typed(ui: &mut Ui, tab: &Tab, boxes: &mut TextBoxes, language: i18n::Language) -> Option { let tr = |key| i18n::translate(language, key, &[]); let document = &tab.draft.document.graphql; let mut typed = None; @@ -95,28 +84,16 @@ fn typed( ui, &mut typed, |ui, typed| { - let (label, hint) = ( - tr(keys::http::graphql::QUERY), - tr(keys::http::graphql::QUERY_PLACEHOLDER), - ); - let field = TextBox { - label: &label, - author_id: "http-graphql-query", - hint: &hint, - height: BOX_HEIGHT, - }; + let (label, hint) = (tr(keys::http::graphql::QUERY), tr(keys::http::graphql::QUERY_PLACEHOLDER)); + let field = + TextBox { label: &label, author_id: "http-graphql-query", hint: &hint, height: BOX_HEIGHT }; if let Some(query) = text_box(ui, &mut boxes.query, &document.query, &field, language) { - *typed = Some(GraphqlDocument { - query, - ..document.clone() - }); + *typed = Some(GraphqlDocument { query, ..document.clone() }); } }, |ui, typed| { - let (label, hint) = ( - tr(keys::http::graphql::VARIABLES), - tr(keys::http::graphql::VARIABLES_PLACEHOLDER), - ); + let (label, hint) = + (tr(keys::http::graphql::VARIABLES), tr(keys::http::graphql::VARIABLES_PLACEHOLDER)); let field = TextBox { label: &label, author_id: "http-graphql-variables", @@ -125,10 +102,7 @@ fn typed( }; let text = &document.variables; if let Some(variables) = text_box(ui, &mut boxes.variables, text, &field, language) { - *typed = Some(GraphqlDocument { - variables, - ..document.clone() - }); + *typed = Some(GraphqlDocument { variables, ..document.clone() }); } }, ); @@ -136,19 +110,13 @@ fn typed( } fn rewrite(actions: &mut Actions, tab: &Tab, part: Rewritten) { - actions.push(Asked::Http(Action::Rewrite { - key: tab.key.clone(), - part, - })); + actions.push(Asked::Http(Action::Rewrite { key: tab.key.clone(), part })); } fn title(ui: &mut Ui, key: i18n::Key, language: i18n::Language) { let p = palette(ui.ctx()); let words = i18n::translate(language, key, &[]).to_uppercase(); - let words = egui::RichText::new(words) - .size(font::CONTROL) - .strong() - .color(p.text_2); + let words = egui::RichText::new(words).size(font::CONTROL).strong().color(p.text_2); ui.add(egui::Label::new(words)); } @@ -156,10 +124,7 @@ fn title(ui: &mut Ui, key: i18n::Key, language: i18n::Language) { fn format_button(ui: &mut Ui, language: i18n::Language, author_id: &str, enabled: bool) -> bool { let words = i18n::translate(language, keys::http::graphql::FORMAT, &[]); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - Button::new(&words, author_id) - .enabled(enabled) - .show(ui) - .clicked() + Button::new(&words, author_id).enabled(enabled).show(ui).clicked() }) .inner } @@ -195,8 +160,7 @@ fn variables_head( actions: &mut Actions, ) { let variables = &tab.draft.document.graphql.variables; - let enabled = - !variables.trim().is_empty() && said.is_none_or(|said| said.variables_problem.is_none()); + let enabled = !variables.trim().is_empty() && said.is_none_or(|said| said.variables_problem.is_none()); ui.horizontal(|ui| { title(ui, keys::http::graphql::VARIABLES, language); if format_button(ui, language, "http-graphql-format-variables", enabled) { @@ -205,19 +169,10 @@ fn variables_head( }); } -fn operation( - ui: &mut Ui, - tab: &Tab, - operations: &[String], - language: i18n::Language, - actions: &mut Actions, -) { +fn operation(ui: &mut Ui, tab: &Tab, operations: &[String], language: i18n::Language, actions: &mut Actions) { let document = &tab.draft.document.graphql; - let options: Vec<(usize, &str)> = operations - .iter() - .enumerate() - .map(|(at, name)| (at, name.as_str())) - .collect(); + let options: Vec<(usize, &str)> = + operations.iter().enumerate().map(|(at, name)| (at, name.as_str())).collect(); let mut chosen = operations .iter() .position(|name| Some(name) == document.operation_name.as_ref()) @@ -227,10 +182,8 @@ fn operation( .show(ui, &mut chosen) .changed() { - let document = GraphqlDocument { - operation_name: Some(operations[chosen].clone()), - ..document.clone() - }; + let document = + GraphqlDocument { operation_name: Some(operations[chosen].clone()), ..document.clone() }; edit(actions, tab, DraftEdit::Graphql(document)); } } @@ -250,10 +203,7 @@ fn query_problem(ui: &mut Ui, problem: &QueryProblem, language: i18n::Language) i18n::translate( language, keys::http::graphql::PROBLEM_AT, - &[ - ("line", problem.line.into()), - ("column", problem.column.into()), - ], + &[("line", problem.line.into()), ("column", problem.column.into()),], ), i18n::translate(language, fault, &[]), ); @@ -274,9 +224,7 @@ fn variables_notes(ui: &mut Ui, said: Option<&GraphqlAnswer>, language: i18n::La return false; }; if let Some(problem) = &said.variables_problem { - let words = egui::RichText::new(invalid(problem, language)) - .size(font::LABEL) - .color(p.red); + let words = egui::RichText::new(invalid(problem, language)).size(font::LABEL).color(p.red); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, "http-graphql-problem"); } @@ -313,10 +261,7 @@ fn named( let shown = ui.add(egui::Label::new(words)); widgets::address(ui, &shown, author_id); for name in names { - let words = egui::RichText::new(name) - .monospace() - .size(font::LABEL) - .color(p.text_0); + let words = egui::RichText::new(name).monospace().size(font::LABEL).color(p.text_0); let shown = ui.add(egui::Label::new(words)); widgets::address(ui, &shown, "http-graphql-variable"); } @@ -331,14 +276,8 @@ fn as_get(ui: &mut Ui, tab: &Tab, language: i18n::Language, actions: &mut Action ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let mut as_get = document.as_get; - if Checkbox::new(&mut as_get, &label, "http-graphql-get") - .show(ui) - .changed() - { - let document = GraphqlDocument { - as_get, - ..document.clone() - }; + if Checkbox::new(&mut as_get, &label, "http-graphql-get").show(ui).changed() { + let document = GraphqlDocument { as_get, ..document.clone() }; edit(actions, tab, DraftEdit::Graphql(document)); } let words = egui::RichText::new(&label).size(font::BODY).color(p.text_1); diff --git a/crates/ui/src/http/request/mod.rs b/crates/ui/src/http/request/mod.rs index 952d200d1..17944a2ed 100644 --- a/crates/ui/src/http/request/mod.rs +++ b/crates/ui/src/http/request/mod.rs @@ -21,8 +21,8 @@ use crate::theme::tokens::{font, gap, radius}; use std::sync::Arc; use egui::{ - CornerRadius, FontFamily, FontId, Galley, Rect, Role, Sense, Stroke, StrokeKind, TextEdit, Ui, - Vec2, WidgetInfo, pos2, + CornerRadius, FontFamily, FontId, Galley, Rect, Role, Sense, Stroke, StrokeKind, TextEdit, Ui, Vec2, + WidgetInfo, pos2, }; use engine::http::model::{HttpMethod, RequestAuth, RequestKind}; use engine::http::scripts::model::ScriptKind; @@ -114,13 +114,9 @@ fn sections(kind: RequestKind) -> &'static [Section] { Section::Tests, Section::Settings, ], - RequestKind::Websocket => &[ - Section::Message, - Section::Headers, - Section::Auth, - Section::Variables, - Section::Protocols, - ], + RequestKind::Websocket => { + &[Section::Message, Section::Headers, Section::Auth, Section::Variables, Section::Protocols] + } } } @@ -147,10 +143,7 @@ pub(crate) struct TextBoxes { impl TextBoxes { fn of(&mut self, key: &str) -> &mut Self { if self.key != key { - *self = Self { - key: key.to_owned(), - ..Self::default() - }; + *self = Self { key: key.to_owned(), ..Self::default() }; } self } @@ -167,19 +160,12 @@ impl EditorView { /// The part chosen, or the first when the kind leaves it behind. fn section(&self, kind: RequestKind) -> Section { let offered = sections(kind); - if offered.contains(&self.chosen) { - self.chosen - } else { - offered[0] - } + if offered.contains(&self.chosen) { self.chosen } else { offered[0] } } } fn edit(actions: &mut Actions, tab: &Tab, edit: DraftEdit) { - actions.push(Asked::Http(Action::Edit { - key: tab.key.clone(), - edit, - })); + actions.push(Asked::Http(Action::Edit { key: tab.key.clone(), edit })); } /// Answers how tall what it holds is: the line under it follows that while left automatic. @@ -222,9 +208,7 @@ pub(crate) fn show( above: tab.place.as_ref().and(state.http.inherited()), allow_inherit: true, }; - if let Some(auth) = - auth::show(ui, &field, &mut boxes.revealed, language) - { + if let Some(auth) = auth::show(ui, &field, &mut boxes.revealed, language) { edit(actions, tab, DraftEdit::Auth(auth)); } } @@ -262,8 +246,7 @@ fn name(ui: &mut Ui, tab: &Tab, actions: &mut Actions, language: i18n::Language) .desired_width(f32::INFINITY), ); let label = i18n::translate(language, keys::http::editor::NAME, &[]); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); widgets::address(ui, &response, "http-request-name"); if response.changed() { edit(actions, tab, DraftEdit::Name(name)); @@ -284,16 +267,11 @@ fn line(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::INSET; if tab.draft.kind == RequestKind::Http { - let options: Vec<(HttpMethod, &str)> = HttpMethod::ALL - .iter() - .map(|method| (*method, method.as_str())) - .collect(); + let options: Vec<(HttpMethod, &str)> = + HttpMethod::ALL.iter().map(|method| (*method, method.as_str())).collect(); let mut method = tab.draft.method; let label = tr(keys::http::editor::METHOD); - if ChoiceMenu::new(&label, "http-method", &options) - .show(ui, &mut method) - .changed() - { + if ChoiceMenu::new(&label, "http-method", &options).show(ui, &mut method).changed() { edit(actions, tab, DraftEdit::Method(method)); } } else { @@ -301,11 +279,7 @@ fn line(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { } let save = tr(keys::http::editor::SAVE); let sending = state.http.sends().is_sending(&tab.key); - let send = if sending { - tr(keys::http::send::CANCEL) - } else { - tr(keys::http::send::SEND) - }; + let send = if sending { tr(keys::http::send::CANCEL) } else { tr(keys::http::send::SEND) }; let sends = tab.draft.kind != RequestKind::Websocket; let connect = tr(keys::http::socket::DISCONNECT); let code = tr(keys::http::code::OPEN); @@ -313,11 +287,7 @@ fn line(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { let keys = (!sending && !compact).then_some(SEND_KEYS); let first = Button::tall_width(ui, if sends { &send } else { &connect }, keys); let worded = |label: &str| { - if compact { - ICON_WIDTH - } else { - Button::tall_width(ui, label, None) - } + if compact { ICON_WIDTH } else { Button::tall_width(ui, label, None) } }; let code = if sends { worded(&code) + 10.0 } else { 0.0 }; first + 10.0 + code + worded(&save) + 10.0 @@ -333,11 +303,7 @@ fn line(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { keys::http::editor::URL_PLACEHOLDER }), ); - let field = url::UrlField { - label: &label, - hint: &hint, - scopes: &scopes, - }; + let field = url::UrlField { label: &label, hint: &hint, scopes: &scopes }; let mut typed = tab.draft.document.url.clone(); if url::show(ui, &mut typed, &field, room).changed() { edit(actions, tab, DraftEdit::Url(typed)); @@ -347,9 +313,7 @@ fn line(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { } else { connect_button(ui, state, tab, actions); } - let mut save_button = Button::new(&save, "http-save") - .tall() - .enabled(tab.is_dirty()); + let mut save_button = Button::new(&save, "http-save").tall().enabled(tab.is_dirty()); if compact { save_button = save_button.icon_only(Icon::Save); } @@ -367,12 +331,7 @@ fn connect_button(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Action (keys::http::socket::CONNECT, widgets::Kind::Filled) }; let words = i18n::translate(state.language, key, &[]); - if Button::new(&words, "http-socket-connect") - .kind(kind) - .tall() - .show(ui) - .clicked() - { + if Button::new(&words, "http-socket-connect").kind(kind).tall().show(ui).clicked() { actions.push(Asked::Http(Action::Send(Some(tab.key.clone())))); } } @@ -392,11 +351,7 @@ fn send_buttons(ui: &mut Ui, state: &AppState, tab: &Tab, compact: bool, actions button = button.keys(SEND_KEYS); } let pressed = button.show(ui); - let pressed = if sending { - pressed - } else { - widgets::tooltip(pressed, &tr(keys::http::send::SEND_HINT)) - }; + let pressed = if sending { pressed } else { widgets::tooltip(pressed, &tr(keys::http::send::SEND_HINT)) }; if pressed.clicked() && sending { actions.push(Asked::Http(Action::CancelSend(tab.key.clone()))); } else if pressed.clicked() { @@ -405,10 +360,7 @@ fn send_buttons(ui: &mut Ui, state: &AppState, tab: &Tab, compact: bool, actions let code = tr(keys::http::code::OPEN); let pressed = if compact { let label = tr(keys::http::code::OPEN_LABEL); - Button::new(&label, "http-code-open") - .tall() - .icon_only(Icon::Code) - .show(ui) + Button::new(&label, "http-code-open").tall().icon_only(Icon::Code).show(ui) } else { let pressed = Button::new(&code, "http-code-open").tall().show(ui); widgets::tooltip(pressed, &tr(keys::http::code::OPEN_LABEL)) @@ -427,14 +379,7 @@ fn kind_badge(ui: &mut Ui, kind: RequestKind, language: i18n::Language) { RequestKind::Http | RequestKind::Websocket => keys::http::kinds::badge::WEBSOCKET, }; let words = i18n::translate(language, key, &[]); - let galley = widgets::text( - ui, - &words, - font::LABEL, - 700.0, - FontFamily::Monospace, - p.text_1, - ); + let galley = widgets::text(ui, &words, font::LABEL, 700.0, FontFamily::Monospace, p.text_1); let size = Vec2::new(galley.size().x + 24.0, url::HEIGHT); let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); ui.painter().rect( @@ -444,8 +389,7 @@ fn kind_badge(ui: &mut Ui, kind: RequestKind, language: i18n::Language) { Stroke::new(1.0, p.line), StrokeKind::Inside, ); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, p.text_1); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text_1); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "http-kind-badge"); } @@ -454,18 +398,10 @@ fn kind_badge(ui: &mut Ui, kind: RequestKind, language: i18n::Language) { fn protected(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { let language = state.language; let tr = |key| i18n::translate(language, key, &[]); - let name = state - .http - .environments() - .active() - .map_or("", |active| active.name.as_str()); + let name = state.http.environments().active().map_or("", |active| active.name.as_str()); let (question, go) = if tab.draft.kind == RequestKind::Websocket { ( - i18n::translate( - language, - keys::http::environments::ASK_CONNECT, - &[("name", name.into())], - ), + i18n::translate(language, keys::http::environments::ASK_CONNECT, &[("name", name.into())]), tr(keys::http::environments::CONNECT_ANYWAY), ) } else { @@ -473,20 +409,13 @@ fn protected(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { i18n::translate( language, keys::http::environments::ASK_SEND, - &[ - ("name", name.into()), - ("method", tab.draft.method.as_str().into()), - ], + &[("name", name.into()), ("method", tab.draft.method.as_str().into())], ), tr(keys::http::environments::SEND_ANYWAY), ) }; let cancel = tr(keys::http::rail::CANCEL); - let ids = ( - "http-protected-confirm", - "http-protected-send", - "http-protected-cancel", - ); + let ids = ("http-protected-confirm", "http-protected-send", "http-protected-cancel"); match protected_question(ui, (&question, &go, &cancel), ids) { Some(true) => actions.push(Asked::Http(Action::SendAnyway(tab.key.clone()))), Some(false) => actions.push(Asked::Http(Action::StopAsking)), @@ -510,16 +439,10 @@ pub(super) fn protected_question( .show(ui, |ui| { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = gap::INSET; - let words = egui::RichText::new(question) - .size(font::BODY) - .color(p.text_0); + let words = egui::RichText::new(question).size(font::BODY).color(p.text_0); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, said_id); - if Button::new(go, go_id) - .kind(widgets::Kind::Destructive) - .show(ui) - .clicked() - { + if Button::new(go, go_id).kind(widgets::Kind::Destructive).show(ui).clicked() { chosen = Some(true); } if Button::new(cancel, cancel_id).show(ui).clicked() { @@ -536,10 +459,7 @@ fn section_tabs(ui: &mut Ui, state: &AppState, tab: &Tab, view: &mut EditorView) let current = view.section(tab.draft.kind); let label = i18n::translate(language, keys::http::editor::PARTS, &[]); let all = sections(tab.draft.kind); - let widths: Vec = all - .iter() - .map(|section| tab_width(ui, state, tab, *section)) - .collect(); + let widths: Vec = all.iter().map(|section| tab_width(ui, state, tab, *section)).collect(); let (shown, hidden) = fitting(all, &widths, current, ui.available_width()); let row = ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::TIGHT; @@ -553,13 +473,9 @@ fn section_tabs(ui: &mut Ui, state: &AppState, tab: &Tab, view: &mut EditorView) } }); let rect = row.response.rect; - ui.painter().hline( - rect.x_range(), - rect.bottom() - 0.5, - Stroke::new(1.0, p.line_soft), - ); - row.response - .widget_info(|| WidgetInfo::labeled(Role::TabList, true, &label)); + ui.painter() + .hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.line_soft)); + row.response.widget_info(|| WidgetInfo::labeled(Role::TabList, true, &label)); } /// Room for the « … » that lists the tabs left out, and the gap before it. @@ -567,12 +483,7 @@ const MORE_WIDTH: f32 = widgets::MIN_TARGET + 8.0; /// The tabs drawn and the tabs listed under « … »: as many as fit, in their order, the one /// chosen always among those drawn. -fn fitting( - all: &[Section], - widths: &[f32], - current: Section, - room: f32, -) -> (Vec
, Vec
) { +fn fitting(all: &[Section], widths: &[f32], current: Section, room: f32) -> (Vec
, Vec
) { if widths.iter().map(|width| width + 4.0).sum::() <= room { return (all.to_vec(), Vec::new()); } @@ -590,26 +501,16 @@ fn fitting( shown.pop(); shown.push(chosen); } - let (shown, hidden): (Vec<_>, Vec<_>) = all - .iter() - .enumerate() - .partition(|(at, _)| shown.contains(at)); - let only = - |list: Vec<(usize, &Section)>| list.into_iter().map(|(_, section)| *section).collect(); + let (shown, hidden): (Vec<_>, Vec<_>) = all.iter().enumerate().partition(|(at, _)| shown.contains(at)); + let only = |list: Vec<(usize, &Section)>| list.into_iter().map(|(_, section)| *section).collect(); (only(shown), only(hidden)) } /// One tab's width: its name, its mark, its padding. fn tab_width(ui: &Ui, state: &AppState, tab: &Tab, section: Section) -> f32 { let words = i18n::translate(state.language, section.name(), &[]); - let galley = widgets::text( - ui, - &words, - font::READING, - 500.0, - FontFamily::Proportional, - egui::Color32::WHITE, - ); + let galley = + widgets::text(ui, &words, font::READING, 500.0, FontFamily::Proportional, egui::Color32::WHITE); let extra = mark(ui, state, tab, section).map_or(0.0, |(galley, _)| galley.size().x + 12.0); galley.size().x + 24.0 + extra } @@ -619,18 +520,9 @@ fn section_tab(ui: &mut Ui, state: &AppState, tab: &Tab, section: Section, on: b let p = palette(ui.ctx()); let words = i18n::translate(state.language, section.name(), &[]); let ink = if on { p.text_0 } else { p.text_1 }; - let galley = widgets::text( - ui, - &words, - font::READING, - 500.0, - FontFamily::Proportional, - ink, - ); + let galley = widgets::text(ui, &words, font::READING, 500.0, FontFamily::Proportional, ink); let mark = mark(ui, state, tab, section); - let extra = mark - .as_ref() - .map_or(0.0, |(galley, _)| galley.size().x + 12.0); + let extra = mark.as_ref().map_or(0.0, |(galley, _)| galley.size().x + 12.0); let size = Vec2::new(galley.size().x + 24.0 + extra, 34.0); let response = interact( ui, @@ -641,11 +533,8 @@ fn section_tab(ui: &mut Ui, state: &AppState, tab: &Tab, section: Section, on: b CornerRadius::ZERO, ); let rect = response.rect; - ui.painter().galley( - pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0), - galley, - ink, - ); + ui.painter() + .galley(pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0), galley, ink); if let Some((galley, author_id)) = mark { let size = galley.size(); let at = pos2(rect.right() - 12.0 - size.x, rect.center().y - size.y / 2.0); @@ -657,8 +546,7 @@ fn section_tab(ui: &mut Ui, state: &AppState, tab: &Tab, section: Section, on: b } if on { let edge = Rect::from_min_max(pos2(rect.left(), rect.bottom() - 2.0), rect.max); - ui.painter() - .rect_filled(edge, CornerRadius::ZERO, p.amber_fill); + ui.painter().rect_filled(edge, CornerRadius::ZERO, p.amber_fill); } response.clicked() } @@ -671,10 +559,7 @@ fn more_tabs(ui: &mut Ui, hidden: &[Section], language: i18n::Language) -> Optio let names: Vec<(String, String)> = hidden .iter() .map(|section| { - ( - i18n::translate(language, section.name(), &[]), - format!("http-section-more-{}", section.id()), - ) + (i18n::translate(language, section.name(), &[]), format!("http-section-more-{}", section.id())) }) .collect(); let items: Vec> = names @@ -684,20 +569,13 @@ fn more_tabs(ui: &mut Ui, hidden: &[Section], language: i18n::Language) -> Optio let label = i18n::translate(language, keys::http::editor::MORE_PARTS, &[]); let trigger = widgets::IconButton::new(Icon::Ellipsis, &label, "http-section-more").show(ui); let picked = widgets::menu(&trigger, &items)?; - let at = names - .iter() - .position(|(_, author_id)| author_id == picked)?; + let at = names.iter().position(|(_, author_id)| author_id == picked)?; hidden.get(at).copied() } /// What a part's tab says beside its name, seen from the others: how many rows it sends, that /// its auth is inherited, that its body is unusual. -fn mark( - ui: &Ui, - state: &AppState, - tab: &Tab, - section: Section, -) -> Option<(Arc, &'static str)> { +fn mark(ui: &Ui, state: &AppState, tab: &Tab, section: Section) -> Option<(Arc, &'static str)> { let p = palette(ui.ctx()); let language = state.language; let count = counted(tab, section); @@ -706,14 +584,9 @@ fn mark( } else if section == Section::Auth && tab.draft.document.auth == RequestAuth::Inherit { let words = i18n::translate(language, keys::http::auth::INHERITS_SHORT, &[]); (words, p.text_2, "http-auth-inherits") - } else if section == Section::Body && state.http.body_answer().is_some_and(|said| said.unusual) - { + } else if section == Section::Body && state.http.body_answer().is_some_and(|said| said.unusual) { let method = tab.draft.method.as_str(); - let words = i18n::translate( - language, - keys::http::body::UNUSUAL_SHORT, - &[("method", method.into())], - ); + let words = i18n::translate(language, keys::http::body::UNUSUAL_SHORT, &[("method", method.into())]); (words, p.amber_text, "http-body-unusual-mark") } else { return None; @@ -726,9 +599,7 @@ fn mark( fn counted(tab: &Tab, section: Section) -> usize { let document = &tab.draft.document; let sent = |rows: &[engine::http::model::KeyValue]| { - rows.iter() - .filter(|row| row.enabled && !row.key.is_empty()) - .count() + rows.iter().filter(|row| row.enabled && !row.key.is_empty()).count() }; match section { Section::Params => sent(&document.params), @@ -787,11 +658,7 @@ fn scripts_of( request_name: &tab.draft.name, }; let tests = phases == [ScriptKind::Tests]; - let view = if tests { - &mut boxes.tests - } else { - &mut boxes.scripts - }; + let view = if tests { &mut boxes.tests } else { &mut boxes.scripts }; let language = state.language; let mut removal = None; let changed = scripts::show(ui, &field, view, language, |ui, phase| { @@ -807,24 +674,14 @@ fn scripts_of( edit(actions, tab, DraftEdit::Scripts(scripts)); } Some(scripts::Changed::Level(origin)) => { - let phase = if tests { - ScriptKind::Tests - } else { - boxes.scripts.phase() - }; + let phase = if tests { ScriptKind::Tests } else { boxes.scripts.phase() }; actions.push(Asked::Http(Action::OpenLevel { origin, phase })); } None => {} } } -fn settings( - ui: &mut Ui, - state: &AppState, - tab: &Tab, - boxes: &mut TextBoxes, - actions: &mut Actions, -) { +fn settings(ui: &mut Ui, state: &AppState, tab: &Tab, boxes: &mut TextBoxes, actions: &mut Actions) { let field = transport::TransportField { settings: tab.draft.document.transport, base: tab @@ -839,18 +696,9 @@ fn settings( } } -fn variables( - ui: &mut Ui, - tab: &Tab, - boxes: &mut TextBoxes, - actions: &mut Actions, - language: i18n::Language, -) { +fn variables(ui: &mut Ui, tab: &Tab, boxes: &mut TextBoxes, actions: &mut Actions, language: i18n::Language) { let label = i18n::translate(language, keys::http::editor::sections::VARIABLES, &[]); - let table = variables_table::Table { - kind: "request", - label: &label, - }; + let table = variables_table::Table { kind: "request", label: &label }; let rows = &tab.draft.document.variables; match variables_table::show(ui, &table, rows, &mut boxes.secrets_shown, language) { Some(variables_table::Changed::Rows(rows)) => { @@ -867,11 +715,7 @@ fn variables( fn params(ui: &mut Ui, tab: &Tab, actions: &mut Actions, language: i18n::Language) { let label = i18n::translate(language, keys::http::editor::sections::PARAMS, &[]); - let table = table::Table { - kind: "params", - label: &label, - headers: false, - }; + let table = table::Table { kind: "params", label: &label, headers: false }; if let Some(rows) = table::show(ui, &table, &tab.draft.document.params, language) { edit(actions, tab, DraftEdit::Params(rows)); } @@ -884,11 +728,7 @@ fn headers(ui: &mut Ui, state: &AppState, tab: &Tab, actions: &mut Actions) { implied_list(ui, implied, language); } let label = i18n::translate(language, keys::http::editor::sections::HEADERS, &[]); - let table = table::Table { - kind: "headers", - label: &label, - headers: true, - }; + let table = table::Table { kind: "headers", label: &label, headers: true }; if let Some(rows) = table::show(ui, &table, &tab.draft.document.headers, language) { edit(actions, tab, DraftEdit::Headers(rows)); } @@ -904,9 +744,8 @@ const IMPLIED_ROW: f32 = 26.0; fn implied_list(ui: &mut Ui, implied: &[ImpliedHeader], language: i18n::Language) { let p = palette(ui.ctx()); let title = i18n::translate(language, keys::http::headers::IMPLIED, &[]); - let mono = |ui: &Ui, words: &str, ink| { - widgets::text(ui, words, font::LABEL, 400.0, FontFamily::Monospace, ink) - }; + let mono = + |ui: &Ui, words: &str, ink| widgets::text(ui, words, font::LABEL, 400.0, FontFamily::Monospace, ink); let names = implied .iter() .map(|header| mono(ui, &header.name, p.text_1).size().x) @@ -920,10 +759,8 @@ fn implied_list(ui: &mut Ui, implied: &[ImpliedHeader], language: i18n::Language ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = 0.0; for header in implied { - let (row, _) = ui.allocate_exact_size( - Vec2::new(ui.available_width(), IMPLIED_ROW), - Sense::hover(), - ); + let (row, _) = + ui.allocate_exact_size(Vec2::new(ui.available_width(), IMPLIED_ROW), Sense::hover()); let inner = row.shrink2(Vec2::new(gap::BLOCKS, 0.0)); let middle = inner.center().y; let name = mono(ui, &header.name, p.text_1); @@ -942,10 +779,8 @@ fn implied_list(ui: &mut Ui, implied: &[ImpliedHeader], language: i18n::Language ui.painter().galley(at, from, p.text_2); let value_left = inner.left() + names + gap::GROUPS; let room = (from_left - gap::GROUPS - value_left).max(1.0); - let value = Rect::from_min_max( - pos2(value_left, row.top()), - pos2(value_left + room, row.bottom()), - ); + let value = + Rect::from_min_max(pos2(value_left, row.top()), pos2(value_left + room, row.bottom())); let said = ui.allocate_rect(value, Sense::hover()); said.widget_info(|| WidgetInfo::labeled(Role::Label, true, &header.value)); widgets::address(ui, &said, "http-implied-value"); @@ -960,8 +795,7 @@ fn implied_list(ui: &mut Ui, implied: &[ImpliedHeader], language: i18n::Language ui.painter().galley(at, shown, p.text_0); } }); - list.response - .widget_info(|| WidgetInfo::labeled(Role::List, true, &title)); + list.response.widget_info(|| WidgetInfo::labeled(Role::List, true, &title)); widgets::address(ui, &list.response, "http-implied-headers"); ui.add_space(gap::INSET); } diff --git a/crates/ui/src/http/request/parts.rs b/crates/ui/src/http/request/parts.rs index f93ee88f7..4c4c6b47c 100644 --- a/crates/ui/src/http/request/parts.rs +++ b/crates/ui/src/http/request/parts.rs @@ -2,9 +2,7 @@ //! One blank row at the end becomes a part as soon as something is typed or chosen in it. use crate::theme::tokens::font; -use egui::{ - CornerRadius, FontFamily, Id, Rect, Role, Sense, Stroke, Ui, UiBuilder, Vec2, WidgetInfo, pos2, -}; +use egui::{CornerRadius, FontFamily, Id, Rect, Role, Sense, Stroke, Ui, UiBuilder, Vec2, WidgetInfo, pos2}; use engine::http::model::FormPart; use i18n::keys; @@ -38,15 +36,8 @@ struct Columns { impl Columns { fn of(frame: Rect) -> Self { let half = ((frame.width() - CHECK - KIND - REMOVE) / 2.0).max(60.0); - let [check, key, kind, value, remove] = - table::columns(frame, [CHECK, half, KIND, half, REMOVE]); - Self { - check, - key, - kind, - value, - remove, - } + let [check, key, kind, value, remove] = table::columns(frame, [CHECK, half, KIND, half, REMOVE]); + Self { check, key, kind, value, remove } } } @@ -67,8 +58,7 @@ pub(super) fn show(ui: &mut Ui, parts: &[FormPart], language: i18n::Language) -> for at in 0..=parts.len() { #[expect(clippy::cast_precision_loss, reason = "rows of a table")] let top = frame.top() + (at + 1) as f32 * ROW; - ui.painter() - .hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); let blank = at == parts.len(); let part = parts.get(at).cloned().unwrap_or_default(); if let Some(row) = row_of(ui, &columns, (id.with(at), top, blank), part, language) { @@ -102,24 +92,13 @@ fn row_of( let tr = |key| i18n::translate(language, key, &[]); let mut changed = false; if !blank { - let label = i18n::translate( - language, - keys::http::table::ENABLE, - &[("key", part.key.as_str().into())], - ); + let label = + i18n::translate(language, keys::http::table::ENABLE, &[("key", part.key.as_str().into())]); let rect = table::slot(columns.check, top); changed |= table::tick(ui, rect, &mut part.enabled, &label, "http-part-enabled"); } - let ink = if part.enabled || blank { - p.text_0 - } else { - p.text_2 - }; - let hint = if blank { - tr(keys::http::table::NEW_KEY) - } else { - String::new() - }; + let ink = if part.enabled || blank { p.text_0 } else { p.text_2 }; + let hint = if blank { tr(keys::http::table::NEW_KEY) } else { String::new() }; changed |= table::text_cell( ui, (table::slot(columns.key, top), id.with("key")), @@ -127,18 +106,9 @@ fn row_of( (&hint, ink, true, false), ) .changed(); - let kind = tr(if part.file { - keys::http::body::PART_FILE - } else { - keys::http::body::PART_TEXT - }); + let kind = tr(if part.file { keys::http::body::PART_FILE } else { keys::http::body::PART_TEXT }); let rect = table::slot(columns.kind, top); - if cell_button( - ui, - rect, - (&kind, "http-part-kind"), - FontFamily::Proportional, - ) { + if cell_button(ui, rect, (&kind, "http-part-kind"), FontFamily::Proportional) { // What was typed is no path, and a path is no text: it is let go. part.file = !part.file; part.value.clear(); @@ -146,28 +116,16 @@ fn row_of( } let rect = table::slot(columns.value, top); if part.file { - let chosen = if part.value.is_empty() { - tr(keys::http::body::CHOOSE_FILE) - } else { - part.value.clone() - }; - if cell_button( - ui, - rect, - (&chosen, "http-part-choose"), - FontFamily::Monospace, - ) { + let chosen = + if part.value.is_empty() { tr(keys::http::body::CHOOSE_FILE) } else { part.value.clone() }; + if cell_button(ui, rect, (&chosen, "http-part-choose"), FontFamily::Monospace) { return Some(Row::Pick); } } else { changed |= table::text_cell( ui, (rect, id.with("value")), - ( - &mut part.value, - &tr(keys::http::table::VALUE), - "http-part-value", - ), + (&mut part.value, &tr(keys::http::table::VALUE), "http-part-value"), ("", ink, true, false), ) .changed(); @@ -180,12 +138,7 @@ fn row_of( } /// A cell that answers a click, its words cut at its edge. -fn cell_button( - ui: &mut Ui, - rect: Rect, - (words, author_id): (&str, &str), - family: FontFamily, -) -> bool { +fn cell_button(ui: &mut Ui, rect: Rect, (words, author_id): (&str, &str), family: FontFamily) -> bool { let p = palette(ui.ctx()); let mut over = ui.new_child(UiBuilder::new().max_rect(rect)); let response = interact( @@ -204,7 +157,6 @@ fn cell_button( }; let galley = widgets::text(ui, words, font::LABEL, 400.0, family, ink); let at = pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0); - ui.painter_at(rect.shrink2(Vec2::new(8.0, 0.0))) - .galley(at, galley, ink); + ui.painter_at(rect.shrink2(Vec2::new(8.0, 0.0))).galley(at, galley, ink); response.clicked() } diff --git a/crates/ui/src/http/request/settings_tests.rs b/crates/ui/src/http/request/settings_tests.rs index d787ee0ce..8cc33a203 100644 --- a/crates/ui/src/http/request/settings_tests.rs +++ b/crates/ui/src/http/request/settings_tests.rs @@ -9,8 +9,7 @@ use engine::http::model::{ }; use crate::http::tests::{ - active, answered, click_id, click_named, collection, editing, request, said_by, sending_to, - values, + active, answered, click_id, click_named, collection, editing, request, said_by, sending_to, values, }; use crate::notes::bench::{Bench, area_of, remembered, settle, until}; use crate::state::Area; @@ -29,10 +28,7 @@ fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { /// What the first label wearing `author_id` says. fn first_said(harness: &Harness<'_, Bench>, author_id: &str) -> String { - let node = harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .next() - .unwrap(); + let node = harness.query_all_by(|node| node.author_id() == Some(author_id)).next().unwrap(); let node = node.accesskit_node(); node.label().or(node.value()).unwrap_or_default() } @@ -76,33 +72,21 @@ fn pick(harness: &mut Harness<'_, Bench>, menu: &str, label: &str) { fn an_auth_inherited_says_what_it_is_and_from_where_its_secret_masked() { let (backend, profile) = testing::unlocked(); let api = collection(&backend, "Paiements"); - request( - &backend, - (&api, None), - "Login", - (RequestKind::Http, HttpMethod::Post), - ); + request(&backend, (&api, None), "Login", (RequestKind::Http, HttpMethod::Post)); let id = api.id.clone(); engine::db::run_here(backend.engine(), move |engine| { let settings = ContainerSettings { - auth: RequestAuth::Bearer { - token: "s3cret".to_owned(), - }, + auth: RequestAuth::Bearer { token: "s3cret".to_owned() }, ..ContainerSettings::default() }; - let item = HttpItem { - kind: HttpItemKind::Collection, - id, - }; + let item = HttpItem { kind: HttpItemKind::Collection, id }; engine::http::save_http_settings(engine, &item, settings) }) .unwrap(); let mut harness = area_of(Area::Http, backend, profile); harness.set_size(TALL); click_named(&mut harness, "http-node-name", "POST Login"); - until(&mut harness, "the request is open", |harness| { - has(harness, "http-section-auth") - }); + until(&mut harness, "the request is open", |harness| has(harness, "http-section-auth")); click_id(&mut harness, "http-section-auth"); until(&mut harness, "the origin is said", |harness| { @@ -117,20 +101,10 @@ fn an_auth_inherited_says_what_it_is_and_from_where_its_secret_masked() { fn an_auth_of_its_own_keeps_its_secret_masked_until_asked() { let mut harness = section("auth"); pick(&mut harness, "http-auth-kind", "Bearer"); - assert_eq!( - active(&harness).document.auth, - RequestAuth::Bearer { - token: String::new() - } - ); + assert_eq!(active(&harness).document.auth, RequestAuth::Bearer { token: String::new() }); type_in(&mut harness, "http-auth-secret", 0, "abc"); - assert_eq!( - active(&harness).document.auth, - RequestAuth::Bearer { - token: "abc".to_owned() - } - ); + assert_eq!(active(&harness).document.auth, RequestAuth::Bearer { token: "abc".to_owned() }); assert_ne!(values(&harness, "http-auth-secret"), ["abc"]); click_id(&mut harness, "http-auth-reveal"); @@ -167,10 +141,7 @@ fn a_variable_is_typed_a_fault_said_and_a_secret_masked() { name: "token".to_owned(), value: "abc".to_owned(), kind: VariableKind::Secret, - filled_by: Some(FilledBy { - request_id: None, - name: "Login".to_owned(), - }), + filled_by: Some(FilledBy { request_id: None, name: "Login".to_owned() }), ..Variable::default() }]), ); @@ -191,9 +162,7 @@ fn a_value_of_the_answer_becomes_a_rule_named_by_the_core() { click_id(&mut harness, "http-send"); answered(&mut harness); click_id(&mut harness, "http-response-view-3"); - until(&mut harness, "the tree is shown", |harness| { - has(harness, "json-line") - }); + until(&mut harness, "the tree is shown", |harness| has(harness, "json-line")); harness .query_all_by(|node| node.author_id() == Some("json-line")) .nth(1) @@ -224,10 +193,7 @@ fn a_rule_is_read_and_removed_under_the_scripts() { }]), ); click_id(&mut harness, "http-script-phase-1"); - assert_eq!( - said_by(&harness, "http-extraction").as_deref(), - Some("body.token") - ); + assert_eq!(said_by(&harness, "http-extraction").as_deref(), Some("body.token")); click_id(&mut harness, "http-extraction-remove"); assert!(active(&harness).document.extractions.is_empty()); @@ -241,12 +207,7 @@ fn the_environment_chosen_is_the_library_s_and_a_deleted_one_is_none() { }) .unwrap(); let api = collection(&backend, "Paiements"); - request( - &backend, - (&api, None), - "Login", - (RequestKind::Http, HttpMethod::Post), - ); + request(&backend, (&api, None), "Login", (RequestKind::Http, HttpMethod::Post)); let mut harness = area_of(Area::Http, backend, profile); click_named(&mut harness, "http-node-name", "POST Login"); until(&mut harness, "the sets are read", |harness| { @@ -268,15 +229,50 @@ fn the_environment_chosen_is_the_library_s_and_a_deleted_one_is_none() { #[test] fn a_request_offers_its_parts() { let harness = editing(); - for part in [ - "params", - "headers", - "auth", - "body", - "variables", - "scripts", - "settings", - ] { + for part in ["params", "headers", "auth", "body", "variables", "scripts", "settings"] { assert!(has(&harness, &format!("http-section-{part}")), "{part}"); } } + +#[test] +fn a_switch_is_above_on_or_off() { + for (words, value) in [("Yes", Some(true)), ("No", Some(false))] { + let mut harness = section("settings"); + pick(&mut harness, "http-transport-followRedirects", words); + assert_eq!(active(&harness).document.transport.follow_redirects, value); + let first = harness + .query_all_by(|node| node.author_id() == Some("http-transport-followRedirects")) + .next() + .unwrap(); + first.click(); + settle(&mut harness); + click_id(&mut harness, "http-transport-followRedirects-0"); + assert_eq!(active(&harness).document.transport.follow_redirects, None, "{words}"); + } +} + +#[test] +fn an_extraction_given_up_adds_no_rule() { + for by_escape in [false, true] { + let mut harness = sending_to("/json"); + click_id(&mut harness, "http-send"); + answered(&mut harness); + click_id(&mut harness, "http-response-view-3"); + until(&mut harness, "the tree is shown", |harness| has(harness, "json-line")); + harness + .query_all_by(|node| node.author_id() == Some("json-line")) + .nth(1) + .unwrap() + .click(); + settle(&mut harness); + click_id(&mut harness, "json-extract"); + if by_escape { + harness.key_press(egui::Key::Escape); + settle(&mut harness); + } else { + click_id(&mut harness, "http-extract-cancel"); + } + assert!(active(&harness).document.extractions.is_empty()); + assert!(!has(&harness, "http-extract-dialog"), "by Escape: {by_escape}"); + } +} diff --git a/crates/ui/src/http/request/table.rs b/crates/ui/src/http/request/table.rs index 16e91fc86..3500a0b36 100644 --- a/crates/ui/src/http/request/table.rs +++ b/crates/ui/src/http/request/table.rs @@ -6,8 +6,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, Event, FontFamily, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, - TextEdit, Ui, Vec2, WidgetInfo, pos2, + Color32, CornerRadius, Event, FontFamily, FontId, Id, Rect, Role, Sense, Stroke, StrokeKind, TextEdit, + Ui, Vec2, WidgetInfo, pos2, }; use engine::http::model::{HeaderFault, KeyValue}; use i18n::keys; @@ -46,11 +46,7 @@ pub(crate) fn show( ) -> Option> { let p = palette(ui.ctx()); let id = ui.scope_id().with(("http-table", table.kind)); - let faults = if table.headers { - api::http::header_faults(rows) - } else { - Vec::new() - }; + let faults = if table.headers { api::http::header_faults(rows) } else { Vec::new() }; let mut edited: Option> = None; let address = format!("http-{}-table", table.kind); let frame = self::frame(ui, rows.len(), table.label, &address); @@ -61,16 +57,9 @@ pub(crate) fn show( let row = rows.get(at).cloned().unwrap_or_default(); #[expect(clippy::cast_precision_loss, reason = "rows of a table")] let top = frame.top() + (at + 1) as f32 * ROW; - ui.painter() - .hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); let fault = faults.get(at).copied().flatten(); - let cell = Cell { - id: id.with(at), - top, - blank, - fault, - headers: table.headers, - }; + let cell = Cell { id: id.with(at), top, blank, fault, headers: table.headers }; if let Some(changed) = row_of(ui, &columns, &cell, row, language) { let mut all = edited.take().unwrap_or_else(|| rows.to_vec()); match changed { @@ -133,15 +122,8 @@ struct Columns { impl Columns { fn of(frame: Rect) -> Self { let third = (frame.width() - CHECK - REMOVE).max(90.0) / 3.0; - let [check, key, value, description, remove] = - columns(frame, [CHECK, third, third, third, REMOVE]); - Self { - check, - key, - value, - description, - remove, - } + let [check, key, value, description, remove] = columns(frame, [CHECK, third, third, third, REMOVE]); + Self { check, key, value, description, remove } } } @@ -149,8 +131,7 @@ impl Columns { pub(super) fn columns(frame: Rect, widths: [f32; N]) -> [Rect; N] { let mut left = frame.left(); widths.map(|width| { - let column = - Rect::from_min_max(pos2(left, frame.top()), pos2(left + width, frame.bottom())); + let column = Rect::from_min_max(pos2(left, frame.top()), pos2(left + width, frame.bottom())); left += width; column }) @@ -175,35 +156,19 @@ fn head(ui: &Ui, columns: &Columns, top: f32, language: i18n::Language) { pub(crate) fn heading(ui: &Ui, rect: Rect, key: i18n::Key, language: i18n::Language) { let p = palette(ui.ctx()); let words = i18n::translate(language, key, &[]); - let galley = widgets::text( - ui, - &words, - font::CONTROL, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - ui.painter().galley( - pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0), - galley, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::CONTROL, 600.0, FontFamily::Proportional, p.text_2); + ui.painter() + .galley(pos2(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0), galley, p.text_2); } /// The box that says a row is sent; `true` when it changed. -pub(crate) fn tick( - ui: &mut Ui, - rect: Rect, - enabled: &mut bool, - label: &str, - author_id: &str, -) -> bool { - let mut check_ui = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout( - egui::Layout::centered_and_justified(egui::Direction::LeftToRight), - )); - Checkbox::new(enabled, label, author_id) - .show(&mut check_ui) - .changed() +pub(crate) fn tick(ui: &mut Ui, rect: Rect, enabled: &mut bool, label: &str, author_id: &str) -> bool { + let mut check_ui = ui.new_child( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::centered_and_justified(egui::Direction::LeftToRight)), + ); + Checkbox::new(enabled, label, author_id).show(&mut check_ui).changed() } struct Cell { @@ -233,31 +198,15 @@ fn row_of( let mut changed = false; if !cell.blank { let rect = slot(columns.check, cell.top); - let label = i18n::translate( - language, - keys::http::table::ENABLE, - &[("key", row.key.as_str().into())], - ); + let label = i18n::translate(language, keys::http::table::ENABLE, &[("key", row.key.as_str().into())]); changed |= tick(ui, rect, &mut row.enabled, &label, "http-kv-enabled"); } - let ink = if row.enabled || cell.blank { - p.text_0 - } else { - p.text_2 - }; + let ink = if row.enabled || cell.blank { p.text_0 } else { p.text_2 }; if let Some(pasted) = pasted_lines(ui, cell.id.with(Field::Key as u8)) { return Some(Changed::Pasted(pasted)); } - let hint = if cell.blank { - tr(keys::http::table::NEW_KEY) - } else { - String::new() - }; - let key_ink = if cell.fault == Some(HeaderFault::Name) { - p.red - } else { - ink - }; + let hint = if cell.blank { tr(keys::http::table::NEW_KEY) } else { String::new() }; + let key_ink = if cell.fault == Some(HeaderFault::Name) { p.red } else { ink }; let key = text_cell( ui, (slot(columns.key, cell.top), cell.id.with(Field::Key as u8)), @@ -266,22 +215,11 @@ fn row_of( ); changed |= key.changed(); let was_empty = row.value.is_empty(); - let value_ink = if cell.fault == Some(HeaderFault::Value) { - p.red - } else { - ink - }; + let value_ink = if cell.fault == Some(HeaderFault::Value) { p.red } else { ink }; let value = text_cell( ui, - ( - slot(columns.value, cell.top), - cell.id.with(Field::Value as u8), - ), - ( - &mut row.value, - &tr(keys::http::table::VALUE), - "http-kv-value", - ), + (slot(columns.value, cell.top), cell.id.with(Field::Value as u8)), + (&mut row.value, &tr(keys::http::table::VALUE), "http-kv-value"), ("", value_ink, true, false), ); // The space typed after `Name:` lands here once the split has moved the caret: a header's @@ -292,15 +230,8 @@ fn row_of( changed |= value.changed(); let description = text_cell( ui, - ( - slot(columns.description, cell.top), - cell.id.with(Field::Description as u8), - ), - ( - &mut row.description, - &tr(keys::http::table::DESCRIPTION), - "http-kv-description", - ), + (slot(columns.description, cell.top), cell.id.with(Field::Description as u8)), + (&mut row.description, &tr(keys::http::table::DESCRIPTION), "http-kv-description"), ("", ink, false, false), ); changed |= description.changed(); @@ -317,13 +248,8 @@ pub(crate) fn text_cell( (text, name, author_id): (&mut String, &str, &str), (hint, ink, mono, masked): (&str, Color32, bool, bool), ) -> egui::Response { - let family = if mono { - FontFamily::Monospace - } else { - FontFamily::Proportional - }; - let mut cell_ui = - ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(Vec2::new(4.0, 2.0)))); + let family = if mono { FontFamily::Monospace } else { FontFamily::Proportional }; + let mut cell_ui = ui.new_child(egui::UiBuilder::new().max_rect(rect.shrink2(Vec2::new(4.0, 2.0)))); let response = cell_ui.add_sized( cell_ui.available_size(), TextEdit::singleline(text) @@ -359,9 +285,7 @@ fn pasted_lines(ui: &Ui, id: Id) -> Option> { return None; } ui.input_mut(|input| { - input - .events - .retain(|event| !matches!(event, Event::Paste(_))); + input.events.retain(|event| !matches!(event, Event::Paste(_))); }); Some(read) } @@ -373,11 +297,7 @@ pub(crate) fn remove( language: i18n::Language, ) -> bool { let p = palette(ui.ctx()); - let label = i18n::translate( - language, - keys::http::table::REMOVE_ROW, - &[("key", key.into())], - ); + let label = i18n::translate(language, keys::http::table::REMOVE_ROW, &[("key", key.into())]); let square = Rect::from_center_size(rect.center(), Vec2::splat(MIN_TARGET)); let mut over = ui.new_child(egui::UiBuilder::new().max_rect(square)); let response = interact( @@ -389,18 +309,12 @@ pub(crate) fn remove( CornerRadius::same(radius::CONTROL), ); let ink = if response.hovered() { - ui.painter() - .rect_filled(square, CornerRadius::same(radius::CONTROL), p.bg_3); + ui.painter().rect_filled(square, CornerRadius::same(radius::CONTROL), p.bg_3); p.text_0 } else { p.text_2 }; - icons::paint( - ui, - Rect::from_center_size(square.center(), Vec2::splat(14.0)), - Icon::X, - ink, - ); + icons::paint(ui, Rect::from_center_size(square.center(), Vec2::splat(14.0)), Icon::X, ink); response.clicked() } @@ -424,10 +338,7 @@ fn said(ui: &mut Ui, faults: &[Option], language: i18n::Language) { /// `Name: value` in a header's name is what was meant as a name and its value: what follows the /// first colon goes to the value, when there is none yet. `None` when nothing is to be split. -pub(crate) fn split_headers( - before: &[KeyValue], - after: &[KeyValue], -) -> Option<(Vec, usize)> { +pub(crate) fn split_headers(before: &[KeyValue], after: &[KeyValue]) -> Option<(Vec, usize)> { let at = after .iter() .enumerate() diff --git a/crates/ui/src/http/request/tests.rs b/crates/ui/src/http/request/tests.rs index 7fdf27108..382f850dc 100644 --- a/crates/ui/src/http/request/tests.rs +++ b/crates/ui/src/http/request/tests.rs @@ -9,8 +9,7 @@ use engine::http::graphql::GraphqlDocument; use engine::http::model::{HttpMethod, RequestBody, RequestKind}; use crate::http::tests::{ - active, answered, click_id, click_named, collection, editing, request, said_by, sending_to, - values, + active, answered, click_id, click_named, collection, editing, request, said_by, sending_to, values, }; use crate::notes::bench::{Bench, area_of, settle, until}; use crate::state::Area; @@ -27,9 +26,7 @@ const MULTIPART: &str = "http-body-kind-4"; const FILE: &str = "http-body-kind-5"; fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } fn body_of(harness: &Harness<'_, Bench>) -> RequestBody { @@ -42,9 +39,7 @@ fn graphql_of(harness: &Harness<'_, Bench>) -> GraphqlDocument { fn type_in(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { click_id(harness, author_id); - harness - .get_by(|node| node.author_id() == Some(author_id)) - .type_text(words); + harness.get_by(|node| node.author_id() == Some(author_id)).type_text(words); settle(harness); } @@ -69,24 +64,14 @@ fn a_kind_left_comes_back_as_it_was_and_json_and_text_share_their_text() { let mut harness = body(JSON); type_in(&mut harness, "http-body-text", "{\"amount\":4900}"); let typed = "{\"amount\":4900}".to_owned(); - assert_eq!( - body_of(&harness), - RequestBody::Json { - text: typed.clone() - } - ); + assert_eq!(body_of(&harness), RequestBody::Json { text: typed.clone() }); click_id(&mut harness, FORM); assert_eq!(body_of(&harness), RequestBody::Form { fields: Vec::new() }); assert!(has(&harness, "http-form-table")); click_id(&mut harness, TEXT); - assert_eq!( - body_of(&harness), - RequestBody::Text { - text: typed.clone() - } - ); + assert_eq!(body_of(&harness), RequestBody::Text { text: typed.clone() }); click_id(&mut harness, JSON); assert_eq!(body_of(&harness), RequestBody::Json { text: typed }); } @@ -95,31 +80,17 @@ fn a_kind_left_comes_back_as_it_was_and_json_and_text_share_their_text() { fn what_a_body_implies_is_said_and_json_that_does_not_read_is_not_formatted() { let mut harness = body(JSON); type_in(&mut harness, "http-body-text", "{\"a\":"); - until(&mut harness, "the fault is said", |harness| { - has(harness, "http-body-problem") - }); + until(&mut harness, "the fault is said", |harness| has(harness, "http-body-problem")); assert!(!has(&harness, "http-body-valid")); - assert!( - said_by(&harness, "http-body-type").is_some_and(|said| said.contains("application/json")) - ); + assert!(said_by(&harness, "http-body-type").is_some_and(|said| said.contains("application/json"))); let format = harness.get_by(|node| node.author_id() == Some("http-body-format")); assert!(format.accesskit_node().is_disabled()); - edit( - &mut harness, - DraftEdit::Body(RequestBody::Json { - text: "{\"a\":1}".to_owned(), - }), - ); - until(&mut harness, "the body reads", |harness| { - has(harness, "http-body-valid") - }); + edit(&mut harness, DraftEdit::Body(RequestBody::Json { text: "{\"a\":1}".to_owned() })); + until(&mut harness, "the body reads", |harness| has(harness, "http-body-valid")); click_id(&mut harness, "http-body-format"); until(&mut harness, "the body is formatted", |harness| { - body_of(harness) - == RequestBody::Json { - text: "{ \"a\": 1 }".to_owned(), - } + body_of(harness) == RequestBody::Json { text: "{ \"a\": 1 }".to_owned() } }); assert_eq!(values(&harness, "http-body-text"), ["{ \"a\": 1 }"]); } @@ -131,9 +102,7 @@ fn a_get_with_a_body_warns_on_its_tab_and_goes_back_to_none() { assert!(!has(&harness, "http-body-unusual")); edit(&mut harness, DraftEdit::Method(HttpMethod::Get)); - until(&mut harness, "the warning is shown", |harness| { - has(harness, "http-body-unusual") - }); + until(&mut harness, "the warning is shown", |harness| has(harness, "http-body-unusual")); assert!(has(&harness, "http-body-unusual-mark")); click_id(&mut harness, "http-section-params"); @@ -148,12 +117,7 @@ fn a_get_with_a_body_warns_on_its_tab_and_goes_back_to_none() { }); click_id(&mut harness, JSON); - assert_eq!( - body_of(&harness), - RequestBody::Json { - text: "{}".to_owned() - } - ); + assert_eq!(body_of(&harness), RequestBody::Json { text: "{}".to_owned() }); } #[test] @@ -165,23 +129,16 @@ fn a_body_is_a_file_by_its_path() { harness.state_mut().state.dialog = Arc::new(platform::dialog::Fixed(path)); click_id(&mut harness, "http-body-choose"); until(&mut harness, "the path is written", |harness| { - body_of(harness) - == RequestBody::Binary { - path: "facture.pdf".to_owned(), - } + body_of(harness) == RequestBody::Binary { path: "facture.pdf".to_owned() } }); - assert_eq!( - said_by(&harness, "http-body-path").as_deref(), - Some("facture.pdf") - ); + assert_eq!(said_by(&harness, "http-body-path").as_deref(), Some("facture.pdf")); } fn parts_of(harness: &Harness<'_, Bench>) -> Vec<(String, String, bool)> { match body_of(harness) { - RequestBody::Multipart { parts } => parts - .into_iter() - .map(|part| (part.key, part.value, part.file)) - .collect(), + RequestBody::Multipart { parts } => { + parts.into_iter().map(|part| (part.key, part.value, part.file)).collect() + } other => panic!("no parts in {other:?}"), } } @@ -190,14 +147,9 @@ fn parts_of(harness: &Harness<'_, Bench>) -> Vec<(String, String, bool)> { fn a_multipart_row_is_a_text_or_a_file_and_the_blank_row_becomes_a_part() { let mut harness = body(MULTIPART); type_in(&mut harness, "http-part-key", "note"); - assert_eq!( - parts_of(&harness), - [("note".to_owned(), String::new(), false)] - ); + assert_eq!(parts_of(&harness), [("note".to_owned(), String::new(), false)]); - let values_at = harness - .query_all_by(|node| node.author_id() == Some("http-part-value")) - .count(); + let values_at = harness.query_all_by(|node| node.author_id() == Some("http-part-value")).count(); assert_eq!(values_at, 2, "a value for the part and the blank row"); let path = PathBuf::from("photo.png"); @@ -228,12 +180,7 @@ fn ctrl_enter_in_a_body_sends_and_writes_no_line() { harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::Enter); answered(&mut harness); - assert_eq!( - body_of(&harness), - RequestBody::Json { - text: "{}".to_owned() - } - ); + assert_eq!(body_of(&harness), RequestBody::Json { text: "{}".to_owned() }); } /// A GraphQL request, its Query tab in front. @@ -245,9 +192,7 @@ fn graphql() -> Harness<'static, Bench> { let mut harness = area_of(Area::Http, backend, profile); harness.set_size(TALL); click_named(&mut harness, "http-node-name", "GQL Catalogue"); - until(&mut harness, "the query is open", |harness| { - has(harness, "http-graphql-query") - }); + until(&mut harness, "the query is open", |harness| has(harness, "http-graphql-query")); harness } @@ -257,9 +202,7 @@ fn a_query_left_open_is_said_and_stops_nothing() { assert!(has(&harness, "http-graphql-variables-hint")); type_in(&mut harness, "http-graphql-query", "{ products"); - until(&mut harness, "the brace is said", |harness| { - has(harness, "http-graphql-query-problem") - }); + until(&mut harness, "the brace is said", |harness| has(harness, "http-graphql-query-problem")); let format = harness.get_by(|node| node.author_id() == Some("http-graphql-format-query")); assert!(format.accesskit_node().is_disabled()); assert_eq!(graphql_of(&harness).query, "{ products"); @@ -269,28 +212,15 @@ fn a_query_left_open_is_said_and_stops_nothing() { fn a_variable_without_a_value_is_named_and_added() { let mut harness = graphql(); let query = "query One($code: ID!) { product(code: $code) { id } }".to_owned(); - edit( - &mut harness, - DraftEdit::Graphql(GraphqlDocument { - query, - ..GraphqlDocument::default() - }), - ); - until(&mut harness, "the variable is named", |harness| { - has(harness, "http-graphql-missing") - }); - assert_eq!( - said_by(&harness, "http-graphql-variable").as_deref(), - Some("$code") - ); + edit(&mut harness, DraftEdit::Graphql(GraphqlDocument { query, ..GraphqlDocument::default() })); + until(&mut harness, "the variable is named", |harness| has(harness, "http-graphql-missing")); + assert_eq!(said_by(&harness, "http-graphql-variable").as_deref(), Some("$code")); click_id(&mut harness, "http-graphql-add"); until(&mut harness, "the variable is added", |harness| { graphql_of(harness).variables.contains("\"code\": null") }); - until(&mut harness, "nothing lacks", |harness| { - !has(harness, "http-graphql-missing") - }); + until(&mut harness, "nothing lacks", |harness| !has(harness, "http-graphql-missing")); } #[test] @@ -298,16 +228,8 @@ fn the_operation_sent_is_chosen_when_there_are_several_and_a_get_is_ticked() { let mut harness = graphql(); assert!(!has(&harness, "http-graphql-operation")); let query = "query One { a } query Two { b }".to_owned(); - edit( - &mut harness, - DraftEdit::Graphql(GraphqlDocument { - query, - ..GraphqlDocument::default() - }), - ); - until(&mut harness, "the operations are offered", |harness| { - has(harness, "http-graphql-operation") - }); + edit(&mut harness, DraftEdit::Graphql(GraphqlDocument { query, ..GraphqlDocument::default() })); + until(&mut harness, "the operations are offered", |harness| has(harness, "http-graphql-operation")); click_id(&mut harness, "http-graphql-get"); assert!(graphql_of(&harness).as_get); @@ -328,10 +250,7 @@ fn in_the_narrowest_window_the_address_keeps_its_room_and_every_tab_is_in_reach( harness.set_size(egui::vec2(640.0, 480.0)); settle(&mut harness); - assert!( - width_of(&harness, "http-url") >= 150.0, - "the address is read" - ); + assert!(width_of(&harness, "http-url") >= 150.0, "the address is read"); assert_eq!( harness .get_by(|node| node.author_id() == Some("http-save")) @@ -345,16 +264,10 @@ fn in_the_narrowest_window_the_address_keeps_its_room_and_every_tab_is_in_reach( click_id(&mut harness, "http-section-more"); click_id(&mut harness, "http-section-more-settings"); - assert!( - has(&harness, "http-section-settings"), - "the tab chosen is drawn" - ); + assert!(has(&harness, "http-section-settings"), "the tab chosen is drawn"); harness.set_size(egui::vec2(1_400.0, 800.0)); settle(&mut harness); - assert!( - !has(&harness, "http-section-more"), - "nothing left out when all fit" - ); + assert!(!has(&harness, "http-section-more"), "nothing left out when all fit"); } /// The request's URL naming a global, a secret global and a name nothing sets; `name`'s chip @@ -377,10 +290,7 @@ fn pointed_at(name: &str) -> Harness<'static, Bench> { engine::http::save_http_globals(engine, &globals) }) .unwrap(); - edit( - &mut harness, - DraftEdit::Url("{{base}}/s/{{token}}?u={{user}}".to_owned()), - ); + edit(&mut harness, DraftEdit::Url("{{base}}/s/{{token}}?u={{user}}".to_owned())); until(&mut harness, "the three chips", |harness| { harness .query_all_by(|node| node.author_id() == Some("http-used-variable")) @@ -434,3 +344,133 @@ fn a_name_set_nowhere_says_so() { let harness = pointed_at("user"); assert_eq!(card(&harness), ["not found"]); } + +/// Where it breaks, and what it lacks. +#[test] +fn each_fault_of_a_query_has_its_own_words() { + let mut said: Vec = ["{ a", "query Q(", "{ a(b: \"c) }", "{ a } }", "{ a) }"] + .into_iter() + .map(|query| { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { query: query.to_owned(), ..GraphqlDocument::default() }), + ); + until(&mut harness, query, |harness| has(harness, "http-graphql-query-problem")); + let words = said_by(&harness, "http-graphql-query-problem").unwrap_or_default(); + words.split_once(' ').map_or(words.clone(), |(_, rest)| rest.to_owned()) + }) + .collect(); + let count = said.len(); + said.sort(); + said.dedup(); + + assert_eq!(said.len(), count, "{said:?}"); +} + +#[test] +fn the_variables_are_json_and_those_the_query_lacks_are_named() { + let mut harness = graphql(); + let query = "query One($code: ID!) { product(code: $code) { id } }".to_owned(); + let of = |variables: &str| { + DraftEdit::Graphql(GraphqlDocument { + query: query.clone(), + variables: variables.to_owned(), + ..GraphqlDocument::default() + }) + }; + edit(&mut harness, of("{")); + until(&mut harness, "the fault is said", |harness| has(harness, "http-graphql-problem")); + edit(&mut harness, of(r#"{"code":1,"other":2}"#)); + until(&mut harness, "the other is named", |harness| has(harness, "http-graphql-unknown")); + assert!(!has(&harness, "http-graphql-problem")); +} + +#[test] +fn the_query_and_its_variables_are_formatted_by_their_buttons() { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { + query: "query One($code:ID!){a(code:$code)}".to_owned(), + variables: r#"{"code":1}"#.to_owned(), + ..GraphqlDocument::default() + }), + ); + until(&mut harness, "the query is formatted", |harness| { + let button = harness.get_by(|node| node.author_id() == Some("http-graphql-format-query")); + !button.accesskit_node().is_disabled() + }); + click_id(&mut harness, "http-graphql-format-query"); + until(&mut harness, "the query is laid out", |harness| graphql_of(harness).query.contains('\n')); + click_id(&mut harness, "http-graphql-format-variables"); + until(&mut harness, "the variables are laid out", |harness| { + graphql_of(harness).variables.contains(": 1") + }); +} + +#[test] +fn the_operation_chosen_is_the_one_sent() { + let mut harness = graphql(); + edit( + &mut harness, + DraftEdit::Graphql(GraphqlDocument { + query: "query One { a } query Two { b }".to_owned(), + ..GraphqlDocument::default() + }), + ); + until(&mut harness, "the operations are offered", |harness| has(harness, "http-graphql-operation")); + click_id(&mut harness, "http-graphql-operation"); + click_id(&mut harness, "http-graphql-operation-1"); + + assert_eq!(graphql_of(&harness).operation_name.as_deref(), Some("Two")); +} + +#[test] +fn a_form_s_row_is_typed_and_taken_out() { + let mut harness = body(FORM); + type_in(&mut harness, "http-kv-key", "name"); + let fields = |harness: &Harness<'_, Bench>| match body_of(harness) { + RequestBody::Form { fields } => fields, + other => panic!("{other:?}"), + }; + assert_eq!(fields(&harness)[0].key, "name"); + click_id(&mut harness, "http-kv-remove"); + + assert!(fields(&harness).is_empty()); +} + +#[test] +fn a_name_set_nowhere_is_given_a_row_where_the_card_says() { + let mut harness = pointed_at("user"); + harness + .get_by(|node| node.author_id() == Some("http-used-variable-define")) + .click(); + until(&mut harness, "the page is shown", |harness| { + harness.state().state.http.page() == crate::state::http::Page::Environments + }); +} + +/// A secret shown is masked again once its card is left. +#[test] +fn a_card_left_forgets_what_it_showed() { + let mut harness = pointed_at("token"); + harness + .get_by(|node| node.author_id() == Some("http-used-variable-reveal")) + .click(); + harness.run(); + harness.hover_at(egui::pos2(900.0, 1_100.0)); + for _ in 0..10 { + harness.step(); + } + assert!(card(&harness).is_empty(), "{:?}", card(&harness)); + harness + .get_by(|node| { + node.author_id() == Some("http-used-variable") + && node.label().or_else(|| node.value()).as_deref() == Some("{{token}}") + }) + .hover(); + harness.run(); + + assert_eq!(card(&harness), ["globals · secret", "••••••••"]); +} diff --git a/crates/ui/src/http/request/transport.rs b/crates/ui/src/http/request/transport.rs index 47f52a995..2cfb6dbcd 100644 --- a/crates/ui/src/http/request/transport.rs +++ b/crates/ui/src/http/request/transport.rs @@ -72,19 +72,9 @@ pub(crate) fn show( } else { keys::http::transport::INHERITED }); - let yes_no = |value: bool| { - tr(if value { - keys::http::transport::ON - } else { - keys::http::transport::OFF - }) - }; + let yes_no = |value: bool| tr(if value { keys::http::transport::ON } else { keys::http::transport::OFF }); let (on, off) = (yes_no(true), yes_no(false)); - let options = [ - (Switch::Above, inherit.as_str()), - (Switch::On, on.as_str()), - (Switch::Off, off.as_str()), - ]; + let options = [(Switch::Above, inherit.as_str()), (Switch::On, on.as_str()), (Switch::Off, off.as_str())]; let mut settings = field.settings; let mut changed = false; Grid::new("http-transport") @@ -109,24 +99,15 @@ pub(crate) fn show( author_id: "http-transport-followRedirects", above: &above, }; - changed |= switch( - ui, - (&row, language), - &options, - &mut settings.follow_redirects, - ); + changed |= switch(ui, (&row, language), &options, &mut settings.follow_redirects); let above = format!("{inherit} · {}", base.max_redirects); let row = Row { label: keys::http::transport::MAX_REDIRECTS, author_id: "http-transport-maxRedirects", above: &above, }; - changed |= number( - ui, - (&row, language), - (&mut settings.max_redirects, base.max_redirects, 0), - typed, - ); + changed |= + number(ui, (&row, language), (&mut settings.max_redirects, base.max_redirects, 0), typed); let above = format!("{inherit} · {}", yes_no(base.verify_tls)); let row = Row { label: keys::http::transport::VERIFY_TLS, @@ -174,9 +155,7 @@ fn switch( label(ui, row, language); let name = i18n::translate(language, row.label, &[]); let mut chosen = Switch::of(*value); - let changed = ChoiceMenu::new(&name, row.author_id, options) - .show(ui, &mut chosen) - .changed(); + let changed = ChoiceMenu::new(&name, row.author_id, options).show(ui, &mut chosen).changed(); *value = chosen.value(); from(ui, row, value.is_some()); changed @@ -198,10 +177,7 @@ fn number( let response = ui .vertical(|ui| { ui.set_width(NUMBER); - TextField::new(&mut text, &name, row.author_id) - .compact() - .hint(&hint) - .show(ui) + TextField::new(&mut text, &name, row.author_id).compact().hint(&hint).show(ui) }) .inner; if response.changed() { @@ -222,9 +198,7 @@ fn number( fn insecure(ui: &mut Ui, language: i18n::Language) { let p = palette(ui.ctx()); let words = i18n::translate(language, keys::http::transport::INSECURE, &[]); - let words = egui::RichText::new(words) - .size(font::BODY) - .color(p.amber_text); + let words = egui::RichText::new(words).size(font::BODY).color(p.amber_text); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, "http-transport-insecure"); } diff --git a/crates/ui/src/http/request/url.rs b/crates/ui/src/http/request/url.rs index 3ba26ca3b..a7e16ed2a 100644 --- a/crates/ui/src/http/request/url.rs +++ b/crates/ui/src/http/request/url.rs @@ -70,8 +70,7 @@ pub(crate) fn show(ui: &mut Ui, url: &mut String, field: &UrlField<'_>, width: f .layouter(&mut layouter), ); let label = field.label.to_owned(); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); widgets::address(ui, &response, "http-url"); response }) @@ -87,16 +86,15 @@ fn lit(text: &str, scopes: &HashMap>, p: &Palette) for (range, name) in api::http::spans(text) { job.append(&text[last..range.start], 0.0, plain.clone()); // Amber while Rust has not said where it resolves from. - let hue = scopes - .get(&name) - .map_or(p.amber_text, |scope| hue(p, *scope)); - let format = TextFormat { - background: hue.gamma_multiply(0.16), - ..TextFormat::simple(font.clone(), hue) - }; + let hue = scopes.get(&name).map_or(p.amber_text, |scope| hue(p, *scope)); + let format = + TextFormat { background: hue.gamma_multiply(0.16), ..TextFormat::simple(font.clone(), hue) }; job.append(&text[range.clone()], 0.0, format); last = range.end; } job.append(&text[last..], 0.0, plain); job } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/request/url/tests.rs b/crates/ui/src/http/request/url/tests.rs new file mode 100644 index 000000000..738bf7855 --- /dev/null +++ b/crates/ui/src/http/request/url/tests.rs @@ -0,0 +1,20 @@ +//! What a variable of the address wears. + +use super::*; + +#[test] +fn each_scope_has_its_hue_and_nothing_set_is_red() { + let p = palette(&egui::Context::default()); + let hues = [ + None, + Some(VariableScope::Request), + Some(VariableScope::Folder), + Some(VariableScope::Collection), + Some(VariableScope::Environment), + Some(VariableScope::Globals), + Some(VariableScope::Dynamic), + ] + .map(|scope| hue(p, scope)); + + assert_eq!(hues, [p.red, p.green, p.teal, p.blue, p.amber_text, p.pink, p.purple]); +} diff --git a/crates/ui/src/http/response/body.rs b/crates/ui/src/http/response/body.rs index c657342d6..62287df32 100644 --- a/crates/ui/src/http/response/body.rs +++ b/crates/ui/src/http/response/body.rs @@ -59,22 +59,13 @@ impl BodyView { /// The text a view shows, cut into lines once per send and view. fn follow(&mut self, ui: &Ui, (id, response): (&str, &SentResponse)) { let pretty = self.view == View::Pretty; - if self - .cut_for - .as_ref() - .is_some_and(|(cut, was)| cut == id && *was == pretty) - { + if self.cut_for.as_ref().is_some_and(|(cut, was)| cut == id && *was == pretty) { return; } self.cut_for = Some((id.to_owned(), pretty)); - let shown = if pretty { - response.pretty.as_deref().unwrap_or(&response.body) - } else { - &response.body - }; - let syntax = pretty - .then(|| crate::notes::language::syntax(response.language)) - .flatten(); + let shown = + if pretty { response.pretty.as_deref().unwrap_or(&response.body) } else { &response.body }; + let syntax = pretty.then(|| crate::notes::language::syntax(response.language)).flatten(); self.shown = TextLines::new(ui, shown, syntax); } } @@ -89,12 +80,7 @@ pub(crate) struct TextLines { impl Default for TextLines { fn default() -> Self { - Self { - text: Arc::from(""), - lines: Vec::new(), - rope: text::Rope::new(), - colouring: None, - } + Self { text: Arc::from(""), lines: Vec::new(), rope: text::Rope::new(), colouring: None } } } @@ -114,11 +100,7 @@ fn lines_of(text: &str) -> Vec> { let mut lines = Vec::new(); let mut start = 0; for (at, _) in text.match_indices('\n') { - let end = if text[..at].ends_with('\r') { - at - 1 - } else { - at - }; + let end = if text[..at].ends_with('\r') { at - 1 } else { at }; lines.push(start..end); start = at + 1; } @@ -153,11 +135,7 @@ pub(super) fn show( match view.view { View::Pretty | View::Raw => { let pretty = view.view == View::Pretty; - let author_id = if pretty { - "http-response-pretty" - } else { - "http-response-body" - }; + let author_id = if pretty { "http-response-pretty" } else { "http-response-body" }; view.shown.show(ui, author_id, pretty); } View::Graph | View::Tree => explore(ui, state, (id, response), view, actions), @@ -182,10 +160,7 @@ fn views( } ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::INSET; - let options: Vec<(View, &str)> = offered - .iter() - .map(|(view, name)| (*view, name.as_str())) - .collect(); + let options: Vec<(View, &str)> = offered.iter().map(|(view, name)| (*view, name.as_str())).collect(); Segmented::new(&options, "http-response-view").show(ui, &mut view.view); if response.cut { let key = if response.incomplete { @@ -193,9 +168,7 @@ fn views( } else { keys::http::response::CUT }; - let words = egui::RichText::new(tr(key)) - .size(font::CONTROL) - .color(p.text_2); + let words = egui::RichText::new(tr(key)).size(font::CONTROL).color(p.text_2); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-response-cut"); } @@ -211,16 +184,13 @@ impl TextLines { let p = palette(ui.ctx()); let count = self.lines.len(); let digits = count.max(1).ilog10() + 1; - let gutter = widgets::text( - ui, - &"8".repeat(digits as usize), - SIZE, - 400.0, - FontFamily::Monospace, - p.line_no, - ) - .size() - .x + 16.0; + let gutter = + widgets::text(ui, &"8".repeat(digits as usize), SIZE, 400.0, FontFamily::Monospace, p.line_no) + .size() + .x + + 16.0; + // The rows are counted with the spacing around the list, and drawn with the one inside it. + let spacing = std::mem::take(&mut ui.spacing_mut().item_spacing.y); let shown = egui::ScrollArea::both() .id_salt(("http-response-lines", author_id)) .auto_shrink([false, false]) @@ -228,7 +198,7 @@ impl TextLines { if coloured && let Some(colouring) = self.colouring.as_mut() { colouring.window(&self.rope, range.clone()); } - ui.spacing_mut().item_spacing.y = 0.0; + ui.spacing_mut().interact_size.y = LINE; for at in range { let line = &self.text[self.lines[at].clone()]; ui.horizontal(|ui| { @@ -241,31 +211,22 @@ impl TextLines { FontFamily::Monospace, p.line_no, ); - let (cell, _) = - ui.allocate_exact_size(Vec2::new(gutter, LINE), egui::Sense::hover()); + let (cell, _) = ui.allocate_exact_size(Vec2::new(gutter, LINE), egui::Sense::hover()); ui.painter().galley( egui::pos2(cell.right() - 10.0 - number.size().x, cell.top() + 1.0), number, p.line_no, ); - let tokens = self - .colouring - .as_ref() - .and_then(|colouring| colouring.line(at)); + let tokens = self.colouring.as_ref().and_then(|colouring| colouring.line(at)); let job = coloured_line(line, tokens, ui); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); - let (rect, _) = ui.allocate_exact_size( - Vec2::new(galley.size().x, LINE), - egui::Sense::hover(), - ); - ui.painter().galley( - egui::pos2(rect.left(), rect.top() + 1.0), - galley, - p.text_0, - ); + let (rect, _) = + ui.allocate_exact_size(Vec2::new(galley.size().x, LINE), egui::Sense::hover()); + ui.painter().galley(egui::pos2(rect.left(), rect.top() + 1.0), galley, p.text_0); }); } }); + ui.spacing_mut().item_spacing.y = spacing; let region = widgets::region(ui, shown.inner_rect, author_id, egui::Sense::hover()); let label = self.text.chars().take(LABEL_UP_TO).collect::(); region.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Document, true, &label)); @@ -283,16 +244,9 @@ fn coloured_line(line: &str, tokens: Option<&text::highlight::Line>, ui: &Ui) -> if start < last || !line.is_char_boundary(start) || !line.is_char_boundary(end) { continue; } - job.append( - &line[last..start], - 0.0, - TextFormat::simple(font.clone(), p.text_0), - ); + job.append(&line[last..start], 0.0, TextFormat::simple(font.clone(), p.text_0)); let (colour, italics) = highlight::colour(p, *token); - let format = TextFormat { - italics, - ..TextFormat::simple(font.clone(), colour) - }; + let format = TextFormat { italics, ..TextFormat::simple(font.clone(), colour) }; job.append(&line[start..end], 0.0, format); last = end; } @@ -308,21 +262,12 @@ fn explore( view: &mut BodyView, actions: &mut Actions, ) { - let query = view - .explorer - .query(response.body.clone(), StructureFormat::Json); - actions.push(Asked::Http(Action::Explore { - send_id: id.to_owned(), - query, - })); + let query = view.explorer.query(response.body.clone(), StructureFormat::Json); + actions.push(Asked::Http(Action::Explore { send_id: id.to_owned(), query })); let Some((explored, text)) = state.http.explored(id) else { return; }; - let mode = if view.view == View::Tree { - Mode::Tree - } else { - Mode::Graph - }; + let mode = if view.view == View::Tree { Mode::Tree } else { Mode::Graph }; // Its own room: the explorer fills the rectangle it is given. let room = ui.available_rect_before_wrap(); let mut inside = ui.new_child(egui::UiBuilder::new().max_rect(room)); @@ -342,12 +287,7 @@ fn explore( } /// An image answer, shown when Rust kept its bytes; any other binary said by its type. -fn image( - ui: &mut Ui, - state: &AppState, - (id, response): (&str, &SentResponse), - actions: &mut Actions, -) { +fn image(ui: &mut Ui, state: &AppState, (id, response): (&str, &SentResponse), actions: &mut Actions) { let p = palette(ui.ctx()); let kind = super::content_type(response).unwrap_or("?"); if kind.to_ascii_lowercase().starts_with("image/") { @@ -357,23 +297,46 @@ fn image( let room = ui.available_size(); let scale = (room.x / size.x).min(room.y / size.y).min(1.0); let shown = ui.add(egui::Image::new(texture).fit_to_exact_size(size * scale)); - let alt = i18n::translate( - state.language, - keys::http::response::IMAGE_ALT, - &[("type", kind.into())], - ); + let alt = + i18n::translate(state.language, keys::http::response::IMAGE_ALT, &[("type", kind.into())]); shown.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, &alt)); widgets::address(ui, &shown, "http-response-image"); return; } } - let words = i18n::translate( - state.language, - keys::http::response::BINARY, - &[("type", kind.into())], - ); - let said = ui.add(egui::Label::new( - egui::RichText::new(words).size(font::BODY).color(p.text_2), - )); + let words = i18n::translate(state.language, keys::http::response::BINARY, &[("type", kind.into())]); + let said = ui.add(egui::Label::new(egui::RichText::new(words).size(font::BODY).color(p.text_2))); widgets::address(ui, &said, "http-response-binary"); } + +#[cfg(test)] +mod row_tests { + use super::TextLines; + use crate::testing; + use crate::theme::tokens::gap; + + /// Drawn closer than they are counted, the rows in view left the end of the pane empty. + #[test] + fn the_rows_in_view_fill_the_pane() { + let rows: Vec = (0..300).map(|n| format!("row {n}")).collect(); + let text = rows.join("\n"); + let harness = testing::harness().with_size(egui::vec2(600.0, 400.0)).build_ui(move |ui| { + ui.spacing_mut().item_spacing.y = gap::INSET; + TextLines::new(ui, &text, None).show(ui, "lines", false); + }); + let mut tops: Vec = harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text().starts_with("row") => Some(text.pos.y), + _ => None, + }) + .collect(); + tops.sort_by(f32::total_cmp); + + let gaps: Vec = tops.windows(2).map(|pair| pair[1] - pair[0]).collect(); + assert!(gaps.iter().all(|gap| (gap - super::LINE).abs() < 0.01), "{gaps:?}"); + assert!(tops[tops.len() - 1] + super::LINE >= 390.0, "{tops:?}"); + } +} diff --git a/crates/ui/src/http/response/mod.rs b/crates/ui/src/http/response/mod.rs index 681f1fe2c..d6d8eaef3 100644 --- a/crates/ui/src/http/response/mod.rs +++ b/crates/ui/src/http/response/mod.rs @@ -3,6 +3,8 @@ //! a failure or a cancelled send stays on screen as an answer does, and goes the same way. pub(crate) mod body; +#[cfg(test)] +mod pane_tests; mod stop; mod tests_view; @@ -35,13 +37,7 @@ enum Section { } impl Section { - const ALL: [Self; 5] = [ - Self::Body, - Self::Tests, - Self::Headers, - Self::Cookies, - Self::Timeline, - ]; + const ALL: [Self; 5] = [Self::Body, Self::Tests, Self::Headers, Self::Cookies, Self::Timeline]; fn id(self) -> &'static str { match self { @@ -99,62 +95,33 @@ pub(crate) fn show( ui.set_min_size(ui.available_size()); ui.spacing_mut().item_spacing.y = gap::INSET; match state.http.sends().of(&tab.key) { - None => placeholder( - ui, - keys::http::response::IDLE, - "http-response-idle", - language, - ), - Some(Sent { - phase: Phase::Sending { started }, - .. - }) => sending(ui, *started, language), - Some(Sent { - phase: Phase::Cancelled, - .. - }) => { - placeholder( - ui, - keys::http::response::CANCELLED, - "http-response-cancelled", - language, - ); + None => placeholder(ui, keys::http::response::IDLE, "http-response-idle", language), + Some(Sent { phase: Phase::Sending { started }, .. }) => sending(ui, *started, language), + Some(Sent { phase: Phase::Cancelled, .. }) => { + placeholder(ui, keys::http::response::CANCELLED, "http-response-cancelled", language); clear(ui, tab, actions, language); } - Some(Sent { - phase: Phase::Failed(error), - .. - }) if error.code == ErrorCode::HttpScript => { + Some(Sent { phase: Phase::Failed(error), .. }) if error.code == ErrorCode::HttpScript => { let stopped = ScriptStop::of_params(&error.params); if stop::show(ui, &stopped, true, language) { open_script(actions, tab, stopped); } clear(ui, tab, actions, language); } - Some(Sent { - phase: Phase::Failed(error), - .. - }) if error.code == ErrorCode::HttpScriptFile => { + Some(Sent { phase: Phase::Failed(error), .. }) if error.code == ErrorCode::HttpScriptFile => { script_file(ui, &tab.key, error, actions, language); } - Some(Sent { - phase: Phase::Failed(error), - .. - }) => { + Some(Sent { phase: Phase::Failed(error), .. }) => { let message = crate::services::errors::message_of(error) .unwrap_or_else(|| i18n::Message::new(keys::http::send::FAILED)); - let words = egui::RichText::new(message.text(language)) - .size(font::READING) - .color(p.red); + let words = egui::RichText::new(message.text(language)).size(font::READING).color(p.red); let said = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &said, "http-response-failure"); clear(ui, tab, actions, language); } - Some(Sent { - id, - phase: Phase::Answered(response), - .. - }) => answered(ui, state, (tab, id, response), view, actions), + Some(Sent { id, phase: Phase::Answered(response), .. }) => { + answered(ui, state, (tab, id, response), view, actions); + } } }); } @@ -176,18 +143,11 @@ fn sending(ui: &mut Ui, started: f64, language: i18n::Language) { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let words = i18n::translate(language, keys::http::response::SENDING, &[]); widgets::spinner(ui, 14.0, &words); - let said = ui.add(egui::Label::new( - egui::RichText::new(&words) - .size(font::READING) - .color(p.text_2), - )); + let said = ui.add(egui::Label::new(egui::RichText::new(&words).size(font::READING).color(p.text_2))); widgets::address(ui, &said, "http-response-sending"); let elapsed = format!("{:.1} s", (now - started).max(0.0)); let ticking = ui.add(egui::Label::new( - egui::RichText::new(elapsed) - .monospace() - .size(font::LABEL) - .color(p.text_2), + egui::RichText::new(elapsed).monospace().size(font::LABEL).color(p.text_2), )); widgets::address(ui, &ticking, "http-response-elapsed"); }); @@ -195,26 +155,12 @@ fn sending(ui: &mut Ui, started: f64, language: i18n::Language) { } /// A file a script asked to send, named before anything leaves: a yes sends again with it. -fn script_file( - ui: &mut Ui, - key: &str, - error: &AppError, - actions: &mut Actions, - language: i18n::Language, -) { +fn script_file(ui: &mut Ui, key: &str, error: &AppError, actions: &mut Actions, language: i18n::Language) { let path = error.params.get("path").cloned().unwrap_or_default(); - let question = i18n::translate( - language, - keys::http::send::ASK_FILE, - &[("path", path.as_str().into())], - ); + let question = i18n::translate(language, keys::http::send::ASK_FILE, &[("path", path.as_str().into())]); let go = i18n::translate(language, keys::http::send::SEND_FILE, &[]); let cancel = i18n::translate(language, keys::http::rail::CANCEL, &[]); - let ids = ( - "http-script-file-confirm", - "http-script-file-send", - "http-script-file-cancel", - ); + let ids = ("http-script-file-confirm", "http-script-file-send", "http-script-file-cancel"); match super::request::protected_question(ui, (&question, &go, &cancel), ids) { Some(true) => actions.push(Asked::Http(Action::SendFile(key.to_owned(), path))), Some(false) => actions.push(Asked::Http(Action::ClearResponse(key.to_owned()))), @@ -224,10 +170,7 @@ fn script_file( fn clear(ui: &mut Ui, tab: &Tab, actions: &mut Actions, language: i18n::Language) { let words = i18n::translate(language, keys::http::response::CLEAR, &[]); - if Button::new(&words, "http-response-clear") - .show(ui) - .clicked() - { + if Button::new(&words, "http-response-clear").show(ui).clicked() { actions.push(Asked::Http(Action::ClearResponse(tab.key.clone()))); } } @@ -290,10 +233,7 @@ fn stop_of(test: &TestResult) -> ScriptStop { } fn open_script(actions: &mut Actions, tab: &Tab, stop: ScriptStop) { - actions.push(Asked::Http(Action::OpenScript { - key: tab.key.clone(), - stop: Box::new(stop), - })); + actions.push(Asked::Http(Action::OpenScript { key: tab.key.clone(), stop: Box::new(stop) })); } fn section_of( @@ -310,10 +250,7 @@ fn section_of( Section::Headers => rows( ui, "http-response-headers", - response - .headers - .iter() - .map(|row| (row.key.as_str(), row.value.as_str())), + response.headers.iter().map(|row| (row.key.as_str(), row.value.as_str())), ), Section::Cookies => cookies(ui, response, state.language), Section::Timeline => timeline(ui, response, state.language), @@ -343,14 +280,9 @@ fn figures(ui: &mut Ui, response: &SentResponse, language: i18n::Language) { let millis = i18n::translate( language, keys::http::response::MILLIS, - &[( - "value", - i18n::format::at_most(f64::from(response.millis), 0, language).into(), - )], + &[("value", i18n::format::at_most(f64::from(response.millis), 0, language).into())], ); - let time = ui.add(egui::Label::new( - egui::RichText::new(millis).size(font::BODY).color(p.text_1), - )); + let time = ui.add(egui::Label::new(egui::RichText::new(millis).size(font::BODY).color(p.text_1))); widgets::address(ui, &time, "http-response-time"); let size = ui.add(egui::Label::new( egui::RichText::new(size_of(response.size, language)) @@ -375,24 +307,14 @@ fn section_words(section: Section, response: &SentResponse, language: i18n::Lang let redirects = i18n::translate( language, keys::http::response::REDIRECTS, - &[( - "count", - u32::try_from(response.redirects.len()) - .unwrap_or(u32::MAX) - .into(), - )], + &[("count", u32::try_from(response.redirects.len()).unwrap_or(u32::MAX).into())], ); return format!("{name} · {redirects}"); } name } -fn section_tabs( - ui: &mut Ui, - response: &SentResponse, - view: &mut ResponseView, - language: i18n::Language, -) { +fn section_tabs(ui: &mut Ui, response: &SentResponse, view: &mut ResponseView, language: i18n::Language) { if response.scripts.tests.is_empty() && view.section == Section::Tests { view.section = Section::Body; } @@ -406,8 +328,7 @@ fn section_tabs( .kind(widgets::Kind::Quiet) .armed(on) .show(ui); - ui.ctx() - .accesskit_node_builder(pressed.id, |node| node.set_selected(on)); + ui.ctx().accesskit_node_builder(pressed.id, |node| node.set_selected(on)); if pressed.clicked() { view.section = section; } @@ -424,20 +345,10 @@ fn note_of( ResponseNote { send_id: send_id.map(str::to_owned), exchange: Box::new(response.exchange.clone()), - text: response - .pretty - .clone() - .unwrap_or_else(|| response.body.clone()), - title: i18n::translate( - language, - keys::http::response::NOTE_TITLE, - &[("name", name.into())], - ), + text: response.pretty.clone().unwrap_or_else(|| response.body.clone()), + title: i18n::translate(language, keys::http::response::NOTE_TITLE, &[("name", name.into())]), language: response.language, - source: format!( - "{} / {name}", - i18n::translate(language, keys::areas::HTTP, &[]) - ), + source: format!("{} / {name}", i18n::translate(language, keys::areas::HTTP, &[])), } } @@ -449,10 +360,7 @@ fn ends( language: i18n::Language, ) { let tr = |key| i18n::translate(language, key, &[]); - let (copy, clear_words) = ( - tr(keys::http::response::COPY), - tr(keys::http::response::CLEAR), - ); + let (copy, clear_words) = (tr(keys::http::response::COPY), tr(keys::http::response::CLEAR)); let note = tr(keys::tools::save_as_note::OPEN); let file = tr(keys::http::response::SAVE_FILE); let cut = response.cut && send_id.is_some(); @@ -461,11 +369,7 @@ fn ends( + Button::width(ui, ¬e) + gap + tab.map_or(0.0, |_| Button::width(ui, &clear_words) + gap) - + if cut { - Button::width(ui, &file) + gap - } else { - 0.0 - } + + if cut { Button::width(ui, &file) + gap } else { 0.0 } + gap + 1.0; let room = ui.available_size_before_wrap().x - ends; @@ -481,11 +385,7 @@ fn ends( name: "response.txt".to_owned(), })); } - if Button::new(©, "http-response-copy") - .enabled(has_text) - .show(ui) - .clicked() - { + if Button::new(©, "http-response-copy").enabled(has_text).show(ui).clicked() { actions.push(Asked::Http(Action::Copy(response.body.clone()))); } if Button::new(¬e, "http-response-save-note") @@ -510,9 +410,7 @@ fn status(ui: &mut Ui, response: &SentResponse) { 4 => p.amber_text, _ => p.red, }; - let words = format!("{} {}", response.status, response.reason) - .trim() - .to_owned(); + let words = format!("{} {}", response.status, response.reason).trim().to_owned(); let galley = widgets::text(ui, &words, font::BODY, 700.0, FontFamily::Monospace, hue); let size = galley.size() + Vec2::new(16.0, 8.0); let response = interact( @@ -523,13 +421,9 @@ fn status(ui: &mut Ui, response: &SentResponse) { || WidgetInfo::labeled(Role::Label, true, &words), CornerRadius::same(radius::CONTROL), ); - ui.painter().rect_filled( - response.rect, - CornerRadius::same(radius::CONTROL), - hue.gamma_multiply(0.16), - ); ui.painter() - .galley(response.rect.center() - galley.size() / 2.0, galley, hue); + .rect_filled(response.rect, CornerRadius::same(radius::CONTROL), hue.gamma_multiply(0.16)); + ui.painter().galley(response.rect.center() - galley.size() / 2.0, galley, hue); } /// Bytes, kilobytes or megabytes, as the reference wrote them. @@ -558,18 +452,10 @@ fn rows<'a>(ui: &mut Ui, author_id: &str, rows: impl Iterator(ui: &mut Ui, author_id: &str, rows: impl Iterator {}", redirect.status, redirect.url); - let shown = ui.label( - egui::RichText::new(line) - .monospace() - .size(font::BODY) - .color(p.text_0), - ); + let shown = + ui.label(egui::RichText::new(line).monospace().size(font::BODY).color(p.text_0)); widgets::address(ui, &shown, "http-response-redirect"); } } heading(ui, keys::http::response::timeline::REQUEST); let exchange = &response.exchange; let mut head = vec![format!("{} {}", exchange.method, exchange.url)]; - head.extend( - exchange - .headers - .iter() - .map(|row| format!("{}: {}", row.key, row.value)), - ); + head.extend(exchange.headers.iter().map(|row| format!("{}: {}", row.key, row.value))); exchange_text(ui, &head.join("\n"), "http-response-sent"); match &exchange.body { SentBody::None => {} @@ -701,17 +554,8 @@ fn timeline(ui: &mut Ui, response: &SentResponse, language: i18n::Language) { } } heading(ui, keys::http::response::timeline::RESPONSE); - let mut received = vec![ - format!("{} {}", response.status, response.reason) - .trim() - .to_owned(), - ]; - received.extend( - response - .headers - .iter() - .map(|row| format!("{}: {}", row.key, row.value)), - ); + let mut received = vec![format!("{} {}", response.status, response.reason).trim().to_owned()]; + received.extend(response.headers.iter().map(|row| format!("{}: {}", row.key, row.value))); exchange_text(ui, &received.join("\n"), "http-response-received"); }); } @@ -726,13 +570,8 @@ fn exchange_text(ui: &mut Ui, text: &str, author_id: &str) { .show(ui, |ui| { ui.set_width(ui.available_width()); ui.add( - egui::Label::new( - egui::RichText::new(text) - .monospace() - .size(font::LABEL) - .color(p.text_0), - ) - .wrap(), + egui::Label::new(egui::RichText::new(text).monospace().size(font::LABEL).color(p.text_0)) + .wrap(), ) }) .inner; @@ -765,8 +604,7 @@ pub(crate) fn split_handle(ui: &mut Ui, rect: Rect, language: i18n::Language) -> ); let lit = response.hovered() || response.dragged() || response.has_focus(); let ink = if lit { p.amber_dim } else { p.line_soft }; - ui.painter() - .hline(rect.x_range(), rect.center().y, Stroke::new(1.0, ink)); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, ink)); if response.hovered() || response.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical); } @@ -795,9 +633,7 @@ mod file_tests { let question = harness.get_by(|node| node.author_id() == Some("http-script-file-confirm")); let said = question.accesskit_node().value().unwrap_or_default(); assert!(said.contains("/home/me/.ssh/id_ed25519"), "{said}"); - harness - .get_by(|node| node.author_id() == Some("http-script-file-send")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-script-file-send")).click(); harness.run(); let asked: Vec = harness.state_mut().drain().collect(); diff --git a/crates/ui/src/http/response/pane_tests.rs b/crates/ui/src/http/response/pane_tests.rs new file mode 100644 index 000000000..e495d3fdf --- /dev/null +++ b/crates/ui/src/http/response/pane_tests.rs @@ -0,0 +1,63 @@ +//! What an answer shows, part by part. + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; + +use crate::http::tests::{answered, click_id, said_by, sending_to}; +use crate::notes::bench::{Bench, until}; + +fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn sent(path: &str) -> Harness<'static, Bench> { + let mut harness = sending_to(path); + click_id(&mut harness, "http-send"); + answered(&mut harness); + harness +} + +#[test] +fn an_answer_with_no_body_says_so() { + let mut harness = sent("/empty"); + until(&mut harness, "it is said", |harness| has(harness, "http-response-empty")); + let copy = harness.get_by(|node| node.author_id() == Some("http-response-copy")); + assert!(copy.accesskit_node().is_disabled()); +} + +/// Counted on the tab, then each with its status. +#[test] +fn the_redirects_followed_are_in_the_timeline() { + let mut harness = sent("/redirect"); + let tab = said_by(&harness, "http-response-section-timeline").unwrap_or_default(); + assert!(tab.contains('1'), "{tab}"); + click_id(&mut harness, "http-response-section-timeline"); + let painted = crate::testing::painted(&harness); + + assert!(painted.iter().any(|text| text.contains("302")), "{painted:?}"); +} + +#[test] +fn the_view_of_a_json_answer_is_kept_for_the_next_and_leaves_with_it() { + let mut harness = sent("/json"); + click_id(&mut harness, "http-response-view-3"); + until(&mut harness, "the tree is shown", |harness| has(harness, "json-line")); + click_id(&mut harness, "http-response-view-2"); + until(&mut harness, "the graph is shown", |harness| has(harness, "json-node-head")); +} + +#[test] +fn a_picture_answered_is_drawn() { + let mut harness = sent("/image"); + until(&mut harness, "it is drawn", |harness| has(harness, "http-response-image")); +} + +#[test] +fn a_size_is_written_in_the_unit_it_reaches() { + for (bytes, words) in [(12, "12 B"), (1_023, "1,023 B"), (1_536, "1.5 KB"), (1_572_864, "1.5 MB")] { + assert_eq!(super::size_of(bytes, i18n::Language::En), words); + } +} diff --git a/crates/ui/src/http/response/stop.rs b/crates/ui/src/http/response/stop.rs index 8d972d8fa..c2c6b8fd6 100644 --- a/crates/ui/src/http/response/stop.rs +++ b/crates/ui/src/http/response/stop.rs @@ -62,22 +62,13 @@ fn where_words(stop: &ScriptStop, language: i18n::Language) -> Option { let Some(line) = stop.line else { return before.then(|| i18n::translate(language, words::NOT_SENT, &[])); }; - let key = if before { - words::LINE_NOT_SENT - } else { - words::LINE - }; + let key = if before { words::LINE_NOT_SENT } else { words::LINE }; Some(i18n::translate(language, key, &[("line", line.into())])) } /// `true` on « Open the script »; `openable` is off under the history, whose request may have /// changed since. -pub(super) fn show( - ui: &mut Ui, - stop: &ScriptStop, - openable: bool, - language: i18n::Language, -) -> bool { +pub(super) fn show(ui: &mut Ui, stop: &ScriptStop, openable: bool, language: i18n::Language) -> bool { let p = palette(ui.ctx()); let title = i18n::translate( language, @@ -91,10 +82,7 @@ pub(super) fn show( .inner_margin(gap::margin(gap::GROUPS, gap::INSET)) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = gap::SNUG; - let words = egui::RichText::new(title) - .size(font::READING) - .strong() - .color(p.text_0); + let words = egui::RichText::new(title).size(font::READING).strong().color(p.text_0); let said = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &said, "http-script-stop"); let words = egui::RichText::new(message(stop, language)) @@ -155,11 +143,7 @@ mod tests { fn each_script_that_stops_is_named_for_whose_it_is() { let mut said = Vec::new(); for kind in [FailureKind::Error, FailureKind::Syntax] { - for level in [ - ScriptLevel::Request, - ScriptLevel::Folder, - ScriptLevel::Collection, - ] { + for level in [ScriptLevel::Request, ScriptLevel::Folder, ScriptLevel::Collection] { for script in [ScriptKind::Before, ScriptKind::After, ScriptKind::Tests] { said.push(title_key(&stopped(kind, level, script)).path()); } @@ -195,10 +179,7 @@ mod tests { fn before_the_send_it_says_nothing_left() { let mut before = stopped(FailureKind::Error, ScriptLevel::Request, ScriptKind::Before); let mut after = stopped(FailureKind::Error, ScriptLevel::Request, ScriptKind::After); - assert_ne!( - where_words(&before, Language::En), - where_words(&after, Language::En) - ); + assert_ne!(where_words(&before, Language::En), where_words(&after, Language::En)); before.line = None; after.line = None; @@ -210,9 +191,7 @@ mod tests { fn the_script_opens_unless_the_history_shows_it() { let stop = || stopped(FailureKind::Error, ScriptLevel::Request, ScriptKind::After); let mut harness = drawn(stop(), true); - harness - .get_by(|node| node.author_id() == Some("http-script-open")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-script-open")).click(); harness.run(); assert!(*harness.state()); diff --git a/crates/ui/src/http/response/tests_view.rs b/crates/ui/src/http/response/tests_view.rs index 6845ab090..7eaef5982 100644 --- a/crates/ui/src/http/response/tests_view.rs +++ b/crates/ui/src/http/response/tests_view.rs @@ -58,20 +58,13 @@ fn summary(ui: &mut Ui, passed: u32, failed: u32, language: i18n::Language) { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::INSET; let (words, hue, author_id) = if failed > 0 { - let words = i18n::translate( - language, - keys::http::tests::FAILED, - &[("count", failed.into())], - ); + let words = i18n::translate(language, keys::http::tests::FAILED, &[("count", failed.into())]); (words, p.red, "http-tests-failed") } else { let words = i18n::translate(language, keys::http::tests::ALL_PASSED, &[]); (words, p.green, "http-tests-passed") }; - let words = egui::RichText::new(words) - .size(font::BODY) - .strong() - .color(hue); + let words = egui::RichText::new(words).size(font::BODY).strong().color(hue); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, author_id); let ratio = i18n::translate( @@ -84,18 +77,14 @@ fn summary(ui: &mut Ui, passed: u32, failed: u32, language: i18n::Language) { widgets::address(ui, &said, "http-tests-ratio"); }); let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), BAR), Sense::hover()); - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::TAG), - p.red.gamma_multiply(0.5), - ); + ui.painter() + .rect_filled(rect, CornerRadius::same(radius::TAG), p.red.gamma_multiply(0.5)); if total > 0 { let share = f32::from(u16::try_from(passed).unwrap_or(u16::MAX)) / f32::from(u16::try_from(total).unwrap_or(u16::MAX)); let right = rect.left() + rect.width() * share; let done = Rect::from_min_max(rect.min, pos2(right, rect.bottom())); - ui.painter() - .rect_filled(done, CornerRadius::same(radius::TAG), p.green); + ui.painter().rect_filled(done, CornerRadius::same(radius::TAG), p.green); } } @@ -108,10 +97,7 @@ fn heading(ui: &mut Ui, test: &TestResult, request: &str, language: i18n::Langua ScriptLevel::Collection => (keys::http::tests::groups::COLLECTION, holder), }; let words = i18n::translate(language, key, &[("name", name.into())]); - let words = egui::RichText::new(words) - .size(font::LABEL) - .strong() - .color(p.text_2); + let words = egui::RichText::new(words).size(font::LABEL).strong().color(p.text_2); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-tests-group"); } @@ -149,10 +135,7 @@ fn row(ui: &mut Ui, test: &TestResult, openable: bool, language: i18n::Language) tr(keys::http::tests::ACTUAL), test.actual.as_ref().unwrap_or(&dash), ); - let words = egui::RichText::new(words) - .monospace() - .size(font::LABEL) - .color(p.text_1); + let words = egui::RichText::new(words).monospace().size(font::LABEL).color(p.text_1); let said = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &said, "http-test-versus"); } else if let Some(message) = &test.message { @@ -164,16 +147,12 @@ fn row(ui: &mut Ui, test: &TestResult, openable: bool, language: i18n::Language) ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; if let Some(code) = &test.code { - let words = egui::RichText::new(code) - .monospace() - .size(font::LABEL) - .color(p.text_2); + let words = egui::RichText::new(code).monospace().size(font::LABEL).color(p.text_2); let said = ui.add(egui::Label::new(words).truncate()); widgets::address(ui, &said, "http-test-code"); } if let Some(line) = test.line.filter(|_| openable) { - let words = - i18n::translate(language, keys::http::tests::LINE, &[("line", line.into())]); + let words = i18n::translate(language, keys::http::tests::LINE, &[("line", line.into())]); opened = Button::new(&words, "http-test-line") .kind(widgets::Kind::Quiet) .show(ui) @@ -219,15 +198,8 @@ mod tests { actual: Some("200".to_owned()), ..failed("it was created") }, - TestResult { - message: Some("boom".to_owned()), - ..failed("it threw") - }, - TestResult { - passed: false, - skipped: true, - ..test("later") - }, + TestResult { message: Some("boom".to_owned()), ..failed("it threw") }, + TestResult { passed: false, skipped: true, ..test("later") }, TestResult { level: Some(ScriptLevel::Folder), holder: Some("Auth".to_owned()), @@ -244,25 +216,21 @@ mod tests { } fn drawn(tests: Vec, openable: bool) -> Harness<'static, Option> { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(640.0, 480.0)) - .build_ui_state( - move |ui, opened: &mut Option| { - let asked = show(ui, &tests, ("Ping", openable), Language::En); - if let Some(test) = asked { - *opened = Some(test.name.clone()); - } - }, - None, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(640.0, 480.0)).build_ui_state( + move |ui, opened: &mut Option| { + let asked = show(ui, &tests, ("Ping", openable), Language::En); + if let Some(test) = asked { + *opened = Some(test.name.clone()); + } + }, + None, + ); harness.run(); harness } fn count(harness: &Harness<'_, Option>, author_id: &str) -> usize { - harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .count() + harness.query_all_by(|node| node.author_id() == Some(author_id)).count() } #[test] @@ -287,9 +255,7 @@ mod tests { fn a_failed_test_leads_to_its_line_unless_the_history_shows_it() { let tests = vec![failed("it was created")]; let mut harness = drawn(tests.clone(), true); - harness - .get_by(|node| node.author_id() == Some("http-test-line")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-test-line")).click(); harness.run(); assert_eq!(harness.state().as_deref(), Some("it was created")); diff --git a/crates/ui/src/http/runner/mod.rs b/crates/ui/src/http/runner/mod.rs index 5898b79e1..bd20cc928 100644 --- a/crates/ui/src/http/runner/mod.rs +++ b/crates/ui/src/http/runner/mod.rs @@ -36,10 +36,7 @@ fn ask(actions: &mut Actions, asked: Ask) { actions.push(Asked::Http(Action::Runner(asked))); } -fn badge_of( - kind: engine::http::model::RequestKind, - method: engine::http::model::HttpMethod, -) -> Badge { +fn badge_of(kind: engine::http::model::RequestKind, method: engine::http::model::HttpMethod) -> Badge { use engine::http::model::RequestKind; match kind { RequestKind::Http => Badge::Method(method), @@ -69,8 +66,7 @@ pub(super) fn show( let mut top = ui.new_child(UiBuilder::new().max_rect(inset)); head(&mut top, state, actions); let soft = Stroke::new(1.0, p.line_soft); - ui.painter() - .hline(region.x_range(), head_rect.bottom() - 0.5, soft); + ui.painter().hline(region.x_range(), head_rect.bottom() - 0.5, soft); let side_width = SIDE.min(region.width() * 0.5); let side_rect = Rect::from_min_max( pos2(region.left(), head_rect.bottom()), @@ -82,8 +78,7 @@ pub(super) fn show( .max_rect(side_rect.shrink2(Vec2::new(16.0, 12.0))), ); side(&mut side_ui, state, view, actions); - ui.painter() - .vline(side_rect.right(), side_rect.y_range(), soft); + ui.painter().vline(side_rect.right(), side_rect.y_range(), soft); let rest = Rect::from_min_max(side_rect.right_top(), region.max); report(ui, rest, state, view, actions); } @@ -123,9 +118,7 @@ fn environment(ui: &mut Ui, state: &AppState) { let hue = active.map_or(p.text_2, |active| folder_hue(ui, active.colour)); let (dot, _) = ui.allocate_exact_size(Vec2::splat(8.0), Sense::hover()); ui.painter().circle_filled(dot.center(), 4.0, hue); - let words = egui::RichText::new(environment_name(state)) - .size(font::BODY) - .color(p.text_1); + let words = egui::RichText::new(environment_name(state)).size(font::BODY).color(p.text_1); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-runner-environment"); } @@ -136,11 +129,8 @@ fn head_actions(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let tr = |key| i18n::translate(language, key, &[]); let runner = state.http.runner(); if !runner.is_running() { - let key = if runner.results().is_empty() { - keys::http::runner::START - } else { - keys::http::runner::AGAIN - }; + let key = + if runner.results().is_empty() { keys::http::runner::START } else { keys::http::runner::AGAIN }; if Button::new(&tr(key), "http-runner-start") .kind(Kind::Filled) .enabled(runner.enabled_count() > 0) @@ -188,11 +178,7 @@ fn number( ui.add(egui::Label::new(words)); let mut text = typed.clone().unwrap_or_else(|| value.to_string()); let response = ui - .add_enabled_ui(enabled, |ui| { - TextField::new(&mut text, label, author_id) - .compact() - .show(ui) - }) + .add_enabled_ui(enabled, |ui| TextField::new(&mut text, label, author_id).compact().show(ui)) .inner; let changed = response.changed(); if changed { @@ -258,9 +244,7 @@ fn side(ui: &mut Ui, state: &AppState, view: &mut RunnerView, actions: &mut Acti let label = tr(key); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::TIGHT; - let shown = Checkbox::new(&mut on, &label, author_id) - .enabled(!running) - .show(ui); + let shown = Checkbox::new(&mut on, &label, author_id).enabled(!running).show(ui); if shown.changed() { ask(actions, asked(on)); } @@ -269,8 +253,7 @@ fn side(ui: &mut Ui, state: &AppState, view: &mut RunnerView, actions: &mut Acti }); } let line = ui.available_rect_before_wrap(); - ui.painter() - .hline(line.x_range(), line.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(line.x_range(), line.top(), Stroke::new(1.0, p.line_soft)); ui.add_space(gap::CONTROLS); order::show(ui, state, &mut view.order, actions); } @@ -282,13 +265,10 @@ fn data(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let runner = state.http.runner(); let running = runner.is_running(); let Some(file) = runner.data() else { - if Button::new( - &tr(keys::http::runner::DATA_CHOOSE), - "http-runner-data-choose", - ) - .enabled(!running) - .show(ui) - .clicked() + if Button::new(&tr(keys::http::runner::DATA_CHOOSE), "http-runner-data-choose") + .enabled(!running) + .show(ui) + .clicked() { ask(actions, Ask::ChooseData); } @@ -310,10 +290,7 @@ fn data(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let words = format!("{} · {rows} · {columns}", file.name); let words = egui::RichText::new(words).size(font::BODY).color(p.text_1); let width = (ui.available_width() - widgets::MIN_TARGET - 8.0).max(0.0); - let said = ui.add_sized( - Vec2::new(width, widgets::MIN_TARGET), - egui::Label::new(words).truncate(), - ); + let said = ui.add_sized(Vec2::new(width, widgets::MIN_TARGET), egui::Label::new(words).truncate()); widgets::address(ui, &said, "http-runner-data"); let clear = tr(keys::http::runner::DATA_CLEAR); if widgets::IconButton::new(Icon::X, &clear, "http-runner-data-clear") @@ -337,15 +314,8 @@ fn report(ui: &mut Ui, rect: Rect, state: &AppState, view: &mut RunnerView, acti }; above.max.y = rect.bottom() - held; let pane = Rect::from_min_max(pos2(rect.left(), above.bottom()), rect.max); - let mut lines = ui.new_child( - UiBuilder::new() - .id_salt("http-runner-console") - .max_rect(pane), - ); - let of = console::Of { - key: &key, - name: "", - }; + let mut lines = ui.new_child(UiBuilder::new().id_salt("http-runner-console").max_rect(pane)); + let of = console::Of { key: &key, name: "" }; console::show(&mut lines, state, (of, &mut view.console), actions); } let mut body = ui.new_child( @@ -378,21 +348,14 @@ fn asking(ui: &mut Ui, state: &AppState, actions: &mut Actions) { keys::http::runner::PROTECTED, &[ ("name", environment_name(state).into()), - ( - "count", - u32::try_from(changing.len()).unwrap_or(u32::MAX).into(), - ), + ("count", u32::try_from(changing.len()).unwrap_or(u32::MAX).into()), ("total", runner.enabled_count().into()), ("requests", changing.join(", ").into()), ], ); let go = i18n::translate(language, keys::http::runner::START_ANYWAY, &[]); let cancel = i18n::translate(language, keys::http::rail::CANCEL, &[]); - let ids = ( - "http-runner-protected", - "http-runner-protected-go", - "http-runner-protected-cancel", - ); + let ids = ("http-runner-protected", "http-runner-protected-go", "http-runner-protected-cancel"); match super::request::protected_question(ui, (&question, &go, &cancel), ids) { Some(true) => ask(actions, Ask::StartAnyway), Some(false) => ask(actions, Ask::StopAsking), @@ -404,28 +367,15 @@ fn empty(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; let runner = state.http.runner(); - let requests = i18n::translate( - language, - keys::http::runner::REQUESTS, - &[("count", runner.enabled_count().into())], - ); - let iterations = i18n::translate( - language, - keys::http::runner::ITERATIONS_COUNT, - &[("count", runner.runs().into())], - ); - let of_file = runner - .data() - .map_or_else(String::new, |file| format!(" ({})", file.name)); - let ready = format!( - "{requests} · {iterations}{of_file} · {}", - environment_name(state) - ); + let requests = + i18n::translate(language, keys::http::runner::REQUESTS, &[("count", runner.enabled_count().into())]); + let iterations = + i18n::translate(language, keys::http::runner::ITERATIONS_COUNT, &[("count", runner.runs().into())]); + let of_file = runner.data().map_or_else(String::new, |file| format!(" ({})", file.name)); + let ready = format!("{requests} · {iterations}{of_file} · {}", environment_name(state)); ui.vertical_centered(|ui| { ui.add_space((ui.available_height() / 2.0 - 40.0).max(0.0)); - let words = egui::RichText::new(ready) - .size(font::READING) - .color(p.text_1); + let words = egui::RichText::new(ready).size(font::READING).color(p.text_1); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-runner-ready"); let word = i18n::translate(language, keys::http::runner::START, &[]); diff --git a/crates/ui/src/http/runner/order.rs b/crates/ui/src/http/runner/order.rs index 2d4241f7c..52120c931 100644 --- a/crates/ui/src/http/runner/order.rs +++ b/crates/ui/src/http/runner/order.rs @@ -1,9 +1,7 @@ //! The run's order: dragged by its grip, or moved with Alt + ↑ ↓ on a row; Space leaves a row out. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - CornerRadius, FontFamily, Key, Modifiers, Rect, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2, -}; +use egui::{CornerRadius, FontFamily, Key, Modifiers, Rect, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2}; use i18n::keys; use super::{Ask, ask, badge_of}; @@ -42,48 +40,31 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut OrderView, actions: keys::http::runner::ORDER, &[ ("running", runner.enabled_count().into()), - ( - "count", - u32::try_from(rows.len()).unwrap_or(u32::MAX).into(), - ), + ("count", u32::try_from(rows.len()).unwrap_or(u32::MAX).into()), ], ); - let caption = egui::RichText::new(caption) - .size(font::LABEL) - .color(p.text_2); + let caption = egui::RichText::new(caption).size(font::LABEL).color(p.text_2); let said = ui.add(egui::Label::new(caption)); widgets::address(ui, &said, "http-runner-order"); let room = ui.available_rect_before_wrap(); let list = Rect::from_min_max(room.min, pos2(room.right(), room.bottom() - HINT)); - let mut inside = ui.new_child( - egui::UiBuilder::new() - .id_salt("http-runner-rows") - .max_rect(list), - ); + let mut inside = ui.new_child(egui::UiBuilder::new().id_salt("http-runner-rows").max_rect(list)); inside.spacing_mut().item_spacing.y = 0.0; let disabled = runner.is_running(); // Taken before the rows: one set while they are drawn is for the order of the next frame. let focus = view.focus.take(); - virtual_list( - &mut inside, - "http-runner-rows", - ROW, - rows.len(), - |ui, at| { - let id = rows[at].id.as_str(); - ui.push_id(id, |ui| { - let response = row(ui, (rows, at, disabled), view, language, actions); - if focus == Some(at) { - response.request_focus(); - } - }); - }, - ); + virtual_list(&mut inside, "http-runner-rows", ROW, rows.len(), |ui, at| { + let id = rows[at].id.as_str(); + ui.push_id(id, |ui| { + let response = row(ui, (rows, at, disabled), view, language, actions); + if focus == Some(at) { + response.request_focus(); + } + }); + }); ui.advance_cursor_after_rect(list); let hint = i18n::translate(language, keys::http::runner::ORDER_HINT, &[]); - let hint = egui::RichText::new(hint) - .size(font::CONTROL) - .color(p.text_2); + let hint = egui::RichText::new(hint).size(font::CONTROL).color(p.text_2); ui.add(egui::Label::new(hint).wrap()); } @@ -113,17 +94,9 @@ fn row( keys_of(ui, &response, (rows.len(), at), view, actions); } let rect = response.rect; - if view - .dragging - .is_some_and(|drag| drag.to == at && drag.from != at) - { - let line = if view.dragging.is_some_and(|drag| drag.from < at) { - rect.bottom() - } else { - rect.top() - }; - ui.painter() - .hline(rect.x_range(), line, Stroke::new(2.0, p.amber_edge)); + if view.dragging.is_some_and(|drag| drag.to == at && drag.from != at) { + let line = if view.dragging.is_some_and(|drag| drag.from < at) { rect.bottom() } else { rect.top() }; + ui.painter().hline(rect.x_range(), line, Stroke::new(2.0, p.amber_edge)); } let mut inside = ui.new_child( egui::UiBuilder::new() @@ -131,11 +104,7 @@ fn row( .layout(egui::Layout::left_to_right(egui::Align::Center)), ); inside.spacing_mut().item_spacing.x = gap::TIGHT; - let label = i18n::translate( - language, - keys::http::runner::INCLUDE, - &[("name", name.into())], - ); + let label = i18n::translate(language, keys::http::runner::INCLUDE, &[("name", name.into())]); let mut enabled = shown.enabled; let checked = Checkbox::new(&mut enabled, &label, "http-runner-row-enabled") .enabled(!disabled) @@ -158,10 +127,7 @@ fn keys_of( if !widgets::takes_keys(ui, row) { return; } - let arrows = egui::EventFilter { - vertical_arrows: true, - ..Default::default() - }; + let arrows = egui::EventFilter { vertical_arrows: true, ..Default::default() }; ui.memory_mut(|memory| memory.set_focus_lock_filter(row.id, arrows)); let (space, up, down) = ui.input_mut(|input| { ( @@ -175,23 +141,11 @@ fn keys_of( } if up && at > 0 { view.focus = Some(at - 1); - ask( - actions, - Ask::Move { - from: at, - to: at - 1, - }, - ); + ask(actions, Ask::Move { from: at, to: at - 1 }); } if down && at + 1 < count { view.focus = Some(at + 1); - ask( - actions, - Ask::Move { - from: at, - to: at + 1, - }, - ); + ask(actions, Ask::Move { from: at, to: at + 1 }); } } @@ -234,13 +188,7 @@ fn grip( && let Some(drag) = view.dragging.take() && drag.from != drag.to { - ask( - actions, - Ask::Move { - from: drag.from, - to: drag.to, - }, - ); + ask(actions, Ask::Move { from: drag.from, to: drag.to }); } } @@ -249,14 +197,7 @@ fn words(ui: &mut Ui, shown: &Row) { let ink = if shown.enabled { p.text_0 } else { p.text_2 }; let badge = badge_of(shown.kind, shown.method); let hue = badge_hue(ui, badge); - let mark = widgets::text( - ui, - badge.short(), - font::META, - 600.0, - FontFamily::Monospace, - hue, - ); + let mark = widgets::text(ui, badge.short(), font::META, 600.0, FontFamily::Monospace, hue); let (rect, _) = ui.allocate_exact_size(Vec2::new(32.0, mark.size().y), Sense::hover()); ui.painter().galley(rect.min, mark, hue); let mut name = shown.path.iter().fold(String::new(), |mut name, folder| { diff --git a/crates/ui/src/http/runner/results.rs b/crates/ui/src/http/runner/results.rs index a92438250..d503c1b0a 100644 --- a/crates/ui/src/http/runner/results.rs +++ b/crates/ui/src/http/runner/results.rs @@ -4,9 +4,7 @@ use crate::theme::tokens::{font, gap, radius}; use std::fmt::Write as _; -use egui::{ - Color32, CornerRadius, FontFamily, Rect, Role, Sense, Ui, UiBuilder, Vec2, WidgetInfo, pos2, -}; +use egui::{Color32, CornerRadius, FontFamily, Rect, Role, Sense, Ui, UiBuilder, Vec2, WidgetInfo, pos2}; use engine::error::AppError; use engine::http::runner::{RunError, RunResult}; use engine::http::scripts::model::TestResult; @@ -36,11 +34,7 @@ enum Line<'a> { } fn error_words(error: &RunError, language: i18n::Language) -> String { - let error = AppError { - code: error.code, - params: error.params.clone(), - detail: String::new(), - }; + let error = AppError { code: error.code, params: error.params.clone(), detail: String::new() }; crate::services::errors::message_of(&error) .unwrap_or_else(|| i18n::Message::new(keys::http::send::FAILED)) .text(language) @@ -78,12 +72,7 @@ fn lines(runner: &Runner, language: i18n::Language) -> Vec> { lines } -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - view: &mut response::ResponseView, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut response::ResponseView, actions: &mut Actions) { let language = state.language; let runner = state.http.runner(); summary(ui, runner, language); @@ -99,22 +88,12 @@ pub(super) fn show( let lines = lines(runner, language); let mut inside = ui.new_child(UiBuilder::new().id_salt("http-runner-lines").max_rect(list)); inside.spacing_mut().item_spacing.y = 0.0; - virtual_list( - &mut inside, - "http-runner-lines", - ROW, - lines.len(), - |ui, at| { - ui.push_id(at, |ui| line(ui, &lines[at], state, actions)); - }, - ); + virtual_list(&mut inside, "http-runner-lines", ROW, lines.len(), |ui, at| { + ui.push_id(at, |ui| line(ui, &lines[at], state, actions)); + }); if let Some((at, response)) = answer { let rect = Rect::from_min_max(pos2(room.left(), list.bottom() + 8.0), room.max); - let mut below = ui.new_child( - UiBuilder::new() - .id_salt("http-runner-answer") - .max_rect(rect), - ); + let mut below = ui.new_child(UiBuilder::new().id_salt("http-runner-answer").max_rect(rect)); let id = format!("run-{at}"); response::recorded(&mut below, state, (&id, response), view, actions); } @@ -126,10 +105,7 @@ fn pill(ui: &mut Ui, words: &str, hue: Color32, author_id: &str) { .corner_radius(CornerRadius::same(radius::CARD)) .inner_margin(gap::margin(gap::CONTROLS, gap::LINE)) .show(ui, |ui| { - let words = egui::RichText::new(words) - .size(font::LABEL) - .strong() - .color(hue); + let words = egui::RichText::new(words).size(font::LABEL).strong().color(hue); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, author_id); }); @@ -145,10 +121,7 @@ fn summary(ui: &mut Ui, runner: &Runner, language: i18n::Language) { let words = i18n::translate( language, keys::http::runner::CANCELLED, - &[ - ("done", said.requests.into()), - ("count", runner.planned().into()), - ], + &[("done", said.requests.into()), ("count", runner.planned().into())], ); pill(ui, &words, p.text_1, "http-runner-cancelled"); } @@ -161,21 +134,15 @@ fn summary(ui: &mut Ui, runner: &Runner, language: i18n::Language) { pill(ui, &words, p.amber_text, "http-runner-capped"); } if said.failures > 0 { - let words = i18n::translate( - language, - keys::http::runner::FAILURES, - &[("count", said.failures.into())], - ); + let words = + i18n::translate(language, keys::http::runner::FAILURES, &[("count", said.failures.into())]); pill(ui, &words, p.red, "http-runner-failures"); } else if !cancelled { let words = i18n::translate(language, keys::http::runner::ALL_PASSED, &[]); pill(ui, &words, p.green, "http-runner-passed"); } - let requests = i18n::translate( - language, - keys::http::runner::REQUESTS, - &[("count", said.requests.into())], - ); + let requests = + i18n::translate(language, keys::http::runner::REQUESTS, &[("count", said.requests.into())]); let ratio = i18n::translate( language, keys::http::tests::RATIO, @@ -186,9 +153,7 @@ fn summary(ui: &mut Ui, runner: &Runner, language: i18n::Language) { let seconds = i18n::format::at_most(f64::from(ended.millis) / 1000.0, 1, language); let _ = write!(figures, " · {seconds} s"); } - let figures = egui::RichText::new(figures) - .size(font::BODY) - .color(p.text_1); + let figures = egui::RichText::new(figures).size(font::BODY).color(p.text_1); let shown = ui.add(egui::Label::new(figures)); widgets::address(ui, &shown, "http-runner-figures"); }); @@ -196,17 +161,13 @@ fn summary(ui: &mut Ui, runner: &Runner, language: i18n::Language) { return; } let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), BAR), Sense::hover()); - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::TAG), - p.red.gamma_multiply(0.5), - ); + ui.painter() + .rect_filled(rect, CornerRadius::same(radius::TAG), p.red.gamma_multiply(0.5)); let share = f64::from(said.passed) / f64::from(said.tests); #[expect(clippy::cast_possible_truncation, reason = "a share of a width")] let right = rect.left() + rect.width() * share as f32; let done = Rect::from_min_max(rect.min, pos2(right, rect.bottom())); - ui.painter() - .rect_filled(done, CornerRadius::same(radius::TAG), p.green); + ui.painter().rect_filled(done, CornerRadius::same(radius::TAG), p.green); } fn filters(ui: &mut Ui, runner: &Runner, language: i18n::Language, actions: &mut Actions) { @@ -216,21 +177,14 @@ fn filters(ui: &mut Ui, runner: &Runner, language: i18n::Language, actions: &mut for filter in Filter::ALL { let (key, id) = match filter { Filter::All => (keys::http::runner::filters::ALL, "http-runner-filter-all"), - Filter::Passed => ( - keys::http::runner::filters::PASSED, - "http-runner-filter-passed", - ), - Filter::Failed => ( - keys::http::runner::filters::FAILED, - "http-runner-filter-failed", - ), + Filter::Passed => (keys::http::runner::filters::PASSED, "http-runner-filter-passed"), + Filter::Failed => (keys::http::runner::filters::FAILED, "http-runner-filter-failed"), }; let count = results.iter().filter(|it| filter.holds(it)).count(); let words = format!("{} {count}", i18n::translate(language, key, &[])); let on = runner.filter() == filter; let pressed = Button::new(&words, id).kind(Kind::Quiet).armed(on).show(ui); - ui.ctx() - .accesskit_node_builder(pressed.id, |node| node.set_selected(on)); + ui.ctx().accesskit_node_builder(pressed.id, |node| node.set_selected(on)); if pressed.clicked() { ask(actions, Ask::Filter(filter)); } @@ -247,17 +201,9 @@ fn line(ui: &mut Ui, line: &Line<'_>, state: &AppState, actions: &mut Actions) { Line::Bad(words) => text_line(ui, words, p.red, "http-runner-why"), Line::Test(test) => test_line(ui, test, language), Line::Code(code) => { - let (rect, _) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); + let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); let at = pos2(rect.left() + INDENT + 18.0, rect.center().y); - let galley = widgets::text( - ui, - code, - font::LABEL, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let galley = widgets::text(ui, code, font::LABEL, 400.0, FontFamily::Monospace, p.text_2); let at = pos2(at.x, at.y - galley.size().y / 2.0); ui.painter_at(rect).galley(at, galley, p.text_2); } @@ -265,15 +211,11 @@ fn line(ui: &mut Ui, line: &Line<'_>, state: &AppState, actions: &mut Actions) { } fn text_line(ui: &mut Ui, words: &str, ink: Color32, author_id: &str) { - let (rect, response) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); widgets::address(ui, &response, author_id); let galley = widgets::text(ui, words, font::BODY, 400.0, FontFamily::Proportional, ink); - let at = pos2( - rect.left() + INDENT, - rect.center().y - galley.size().y / 2.0, - ); + let at = pos2(rect.left() + INDENT, rect.center().y - galley.size().y / 2.0); ui.painter_at(rect).galley(at, galley, ink); widgets::tooltip(response, words); } @@ -284,46 +226,23 @@ fn iteration_line(ui: &mut Ui, iteration: u32, state: &AppState) { let words = i18n::translate( state.language, keys::http::runner::ITERATION, - &[ - ("iteration", (iteration + 1).into()), - ("count", runner.runs().into()), - ], + &[("iteration", (iteration + 1).into()), ("count", runner.runs().into())], ); - let row = runner - .data() - .and_then(|file| file.data.rows.get(iteration as usize)); + let row = runner.data().and_then(|file| file.data.rows.get(iteration as usize)); let values: Vec = row .into_iter() .flatten() .map(|(key, value)| format!("{key} = {value}")) .collect(); - let (rect, response) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Heading, true, &words)); widgets::address(ui, &response, "http-runner-iteration"); - let galley = widgets::text( - ui, - &words, - font::LABEL, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::LABEL, 600.0, FontFamily::Proportional, p.text_2); let left = rect.left() + galley.size().x + 12.0; let middle = rect.center().y; - ui.painter().galley( - pos2(rect.left(), middle - galley.size().y / 2.0), - galley, - p.text_2, - ); - let row = widgets::text( - ui, - &values.join(" · "), - font::LABEL, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + ui.painter() + .galley(pos2(rect.left(), middle - galley.size().y / 2.0), galley, p.text_2); + let row = widgets::text(ui, &values.join(" · "), font::LABEL, 400.0, FontFamily::Monospace, p.text_2); let at = pos2(left, middle - row.size().y / 2.0); ui.painter_at(rect).galley(at, row, p.text_2); } @@ -338,12 +257,7 @@ fn status_words(result: &RunResult, language: i18n::Language) -> String { } } -fn result_line( - ui: &mut Ui, - (at, result): (usize, &RunResult), - state: &AppState, - actions: &mut Actions, -) { +fn result_line(ui: &mut Ui, (at, result): (usize, &RunResult), state: &AppState, actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; let failed = result.failed(); @@ -369,50 +283,29 @@ fn result_line( CornerRadius::same(radius::CONTROL), ); let open = state.http.runner().is_open(at); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_expanded(open)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_expanded(open)); if response.clicked() { ask(actions, Ask::Fold(at)); } let rect = response.rect; if failed { - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::CONTROL), - p.red.gamma_multiply(0.08), - ); - } else if response.hovered() { ui.painter() - .rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_1); + .rect_filled(rect, CornerRadius::same(radius::CONTROL), p.red.gamma_multiply(0.08)); + } else if response.hovered() { + ui.painter().rect_filled(rect, CornerRadius::same(radius::CONTROL), p.bg_1); } - let glyph = - Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), Vec2::splat(14.0)); + let glyph = Rect::from_center_size(pos2(rect.left() + 12.0, rect.center().y), Vec2::splat(14.0)); mark(ui, glyph, result.skipped, !failed); let badge = badge_of(result.kind, result.method); let hue = badge_hue(ui, badge); let mut left = rect.left() + INDENT; - let galley = widgets::text( - ui, - badge.short(), - font::META, - 600.0, - FontFamily::Monospace, - hue, - ); + let galley = widgets::text(ui, badge.short(), font::META, 600.0, FontFamily::Monospace, hue); let middle = rect.center().y; - ui.painter() - .galley(pos2(left, middle - galley.size().y / 2.0), galley, hue); + ui.painter().galley(pos2(left, middle - galley.size().y / 2.0), galley, hue); left += 38.0; let figures = figures_of(result, language); let right = figures_at(ui, rect, &figures); - let galley = widgets::text( - ui, - &name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, &name, font::BODY, 400.0, FontFamily::Proportional, p.text_0); let clip = Rect::from_min_max(pos2(left, rect.top()), pos2(right - 12.0, rect.bottom())); let at = pos2(left, middle - galley.size().y / 2.0); ui.painter_at(clip).galley(at, galley, p.text_0); @@ -425,9 +318,8 @@ fn figures_of(result: &RunResult, language: i18n::Language) -> String { let _ = write!(figures, " {} ms", result.millis); } let ran = result.tests.iter().filter(|test| !test.skipped); - let (passed, total) = ran.fold((0, 0), |(passed, total), test| { - (passed + u32::from(test.passed), total + 1) - }); + let (passed, total) = + ran.fold((0, 0), |(passed, total), test| (passed + u32::from(test.passed), total + 1)); if total > 0 { let _ = write!(figures, " {passed}/{total}"); } @@ -436,14 +328,7 @@ fn figures_of(result: &RunResult, language: i18n::Language) -> String { fn figures_at(ui: &Ui, rect: Rect, figures: &str) -> f32 { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - figures, - font::LABEL, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let galley = widgets::text(ui, figures, font::LABEL, 400.0, FontFamily::Monospace, p.text_2); let left = rect.right() - galley.size().x - 8.0; let at = pos2(left, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_2); @@ -480,21 +365,14 @@ fn test_line(ui: &mut Ui, test: &TestResult, language: i18n::Language) { } else if let Some(message) = test.message.as_deref().filter(|_| bad) { let _ = write!(words, " · {message}"); } - let (rect, response) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "http-runner-test"); - let glyph = Rect::from_center_size( - pos2(rect.left() + INDENT + 7.0, rect.center().y), - Vec2::splat(12.0), - ); + let glyph = Rect::from_center_size(pos2(rect.left() + INDENT + 7.0, rect.center().y), Vec2::splat(12.0)); mark(ui, glyph, test.skipped, test.passed); let ink = if bad { p.red } else { p.text_1 }; let galley = widgets::text(ui, &words, font::BODY, 400.0, FontFamily::Proportional, ink); - let at = pos2( - rect.left() + INDENT + 18.0, - rect.center().y - galley.size().y / 2.0, - ); + let at = pos2(rect.left() + INDENT + 18.0, rect.center().y - galley.size().y / 2.0); ui.painter_at(rect).galley(at, galley, ink); widgets::tooltip(response, &words); } diff --git a/crates/ui/src/http/runner_tests.rs b/crates/ui/src/http/runner_tests.rs index 990d8181b..ae212c52e 100644 --- a/crates/ui/src/http/runner_tests.rs +++ b/crates/ui/src/http/runner_tests.rs @@ -29,9 +29,7 @@ fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { } fn count(harness: &Harness<'_, Bench>, author_id: &str) -> usize { - harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .count() + harness.query_all_by(|node| node.author_id() == Some(author_id)).count() } fn labels(harness: &Harness<'_, Bench>, author_id: &str) -> Vec { @@ -78,9 +76,7 @@ fn runner_on(port: u16, path: &str) -> Harness<'static, Bench> { fn open(harness: &mut Harness<'_, Bench>) { choose(harness, "Local", &["http-node-run"]); - until(harness, "the order is read", |harness| { - count(harness, "http-runner-row") == 2 - }); + until(harness, "the order is read", |harness| count(harness, "http-runner-row") == 2); } fn phase(harness: &Harness<'_, Bench>) -> Phase { @@ -107,11 +103,7 @@ fn result(iteration: u32, name: &str, tests: Vec) -> RunResult { } fn passed(name: &str) -> TestResult { - TestResult { - name: name.to_owned(), - passed: true, - ..TestResult::default() - } + TestResult { name: name.to_owned(), passed: true, ..TestResult::default() } } fn failed(name: &str) -> TestResult { @@ -125,10 +117,7 @@ fn failed(name: &str) -> TestResult { } fn say(harness: &mut Harness<'_, Bench>, step: RunStep) { - let event = RunEvent { - id: "1".to_owned(), - step, - }; + let event = RunEvent { id: "1".to_owned(), step }; harness.state_mut().state.http.receive_run(event); settle(harness); } @@ -140,9 +129,7 @@ fn ended(harness: &mut Harness<'_, Bench>, result: RunResult) { fn run(harness: &mut Harness<'_, Bench>) { click_id(harness, "http-runner-start-empty"); - until(harness, "the run is over", |harness| { - phase(harness) == Phase::Done - }); + until(harness, "the run is over", |harness| phase(harness) == Phase::Done); } #[test] @@ -183,10 +170,7 @@ fn an_order_read_before_a_move_does_not_undo_it() { let bench = harness.state_mut(); let dialog = Arc::clone(&bench.state.dialog); let target = bench.state.http.runner().target().unwrap().clone(); - bench - .state - .http - .ask_runner(&bench.backend, &dialog, Asked::Open(target)); + bench.state.http.ask_runner(&bench.backend, &dialog, Asked::Open(target)); // Not settled: the order is being read again as the row moves. harness.step(); let bench = harness.state_mut(); @@ -238,9 +222,7 @@ fn a_data_file_gives_an_iteration_a_row_until_it_is_taken_away() { std::fs::write(&csv, "customer\ncus_1\ncus_2\n").unwrap(); harness.state_mut().state.dialog = Arc::new(platform::dialog::Fixed(csv)); click_id(&mut harness, "http-runner-data-choose"); - until(&mut harness, "the file is read", |harness| { - has(harness, "http-runner-data") - }); + until(&mut harness, "the file is read", |harness| has(harness, "http-runner-data")); assert_eq!(harness.state().state.http.runner().runs(), 2); click_id(&mut harness, "http-runner-data-clear"); @@ -256,9 +238,7 @@ fn a_file_that_is_no_data_is_said_and_nothing_is_chosen() { std::fs::write(&prose, "neither a CSV with a header nor a JSON array\n").unwrap(); harness.state_mut().state.dialog = Arc::new(platform::dialog::Fixed(prose)); click_id(&mut harness, "http-runner-data-choose"); - until(&mut harness, "the error is said", |harness| { - harness.state().state.errors.notice().is_some() - }); + until(&mut harness, "the error is said", |harness| harness.state().state.errors.notice().is_some()); assert!(harness.state().state.http.runner().data().is_none()); } @@ -268,14 +248,7 @@ fn the_report_sums_the_run_up_and_a_failure_opens_on_its_assertion() { run(&mut harness); ended(&mut harness, result(0, "Login", vec![passed("found")])); ended(&mut harness, result(0, "Orders", vec![failed("listed")])); - say( - &mut harness, - RunStep::Finished { - cancelled: false, - millis: 1_200, - capped: false, - }, - ); + say(&mut harness, RunStep::Finished { cancelled: false, millis: 1_200, capped: false }); assert!(has(&harness, "http-runner-failures")); let figures = said_by(&harness, "http-runner-figures").unwrap(); @@ -295,6 +268,19 @@ fn the_report_sums_the_run_up_and_a_failure_opens_on_its_assertion() { assert_eq!(labels(&harness, "http-runner-test"), ["found"]); } +#[test] +fn a_run_started_again_forgets_the_report_before_it() { + let mut harness = runner("/json"); + run(&mut harness); + ended(&mut harness, result(1, "Login", vec![passed("is there")])); + let reported = |harness: &Harness<'_, Bench>| harness.state().state.http.runner().results().len(); + assert_eq!(reported(&harness), 1); + + click_id(&mut harness, "http-runner-start"); + until(&mut harness, "the next run is over", |harness| phase(harness) == Phase::Done); + assert_eq!(reported(&harness), 0); +} + #[test] fn what_kept_a_request_from_its_answer_is_said_under_it() { let mut harness = runner("/json"); @@ -309,11 +295,7 @@ fn what_kept_a_request_from_its_answer_is_said_under_it() { }; ended(&mut harness, refused); assert!(has(&harness, "http-runner-why")); - let skipped = RunResult { - skipped: true, - status: None, - ..result(0, "Orders", Vec::new()) - }; + let skipped = RunResult { skipped: true, status: None, ..result(0, "Orders", Vec::new()) }; ended(&mut harness, skipped); assert!(has(&harness, "http-runner-result-skipped")); } @@ -329,10 +311,7 @@ fn the_iterations_of_a_report_stand_apart() { run(&mut harness); ended(&mut harness, result(0, "Login", Vec::new())); ended(&mut harness, result(1, "Login", Vec::new())); - assert_eq!( - labels(&harness, "http-runner-iteration"), - ["Iteration 1 / 2", "Iteration 2 / 2"] - ); + assert_eq!(labels(&harness, "http-runner-iteration"), ["Iteration 1 / 2", "Iteration 2 / 2"]); } #[test] @@ -348,11 +327,7 @@ fn a_run_cancelled_says_how_far_it_went() { assert_eq!(phase(&harness), Phase::Running); harness.state_mut().state.http.receive_run(RunEvent { id: "1".to_owned(), - step: RunStep::Started { - iteration: 0, - index: 0, - name: "Login".to_owned(), - }, + step: RunStep::Started { iteration: 0, index: 0, name: "Login".to_owned() }, }); harness.step(); harness.step(); @@ -364,36 +339,15 @@ fn a_run_cancelled_says_how_far_it_went() { harness.step(); } assert!(testing::slow_arrived(port), "the send reached the server"); - harness - .get_by(|node| node.author_id() == Some("http-runner-cancel")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-runner-cancel")).click(); harness.step(); harness.step(); - until(&mut harness, "the run stops", |harness| { - phase(harness) == Phase::Done - }); + until(&mut harness, "the run stops", |harness| phase(harness) == Phase::Done); ended(&mut harness, result(0, "Login", Vec::new())); - say( - &mut harness, - RunStep::Finished { - cancelled: false, - millis: 40, - capped: true, - }, - ); + say(&mut harness, RunStep::Finished { cancelled: false, millis: 40, capped: true }); let capped = said_by(&harness, "http-runner-capped").unwrap(); - assert!( - capped.contains("1,000") || capped.contains("1000") || capped.contains("1 000"), - "{capped}" - ); - say( - &mut harness, - RunStep::Finished { - cancelled: true, - millis: 40, - capped: false, - }, - ); + assert!(capped.contains("1,000") || capped.contains("1000") || capped.contains("1 000"), "{capped}"); + say(&mut harness, RunStep::Finished { cancelled: true, millis: 40, capped: false }); let said = said_by(&harness, "http-runner-cancelled").unwrap(); assert_eq!(said, "Cancelled · 1 of 2 requests"); } @@ -411,10 +365,7 @@ fn a_kept_answer_reads_under_the_report() { panic!("the send is answered"); }; let response: SentResponse = response.as_ref().clone(); - let with_answer = RunResult { - response: Some(response), - ..result(0, "Login", Vec::new()) - }; + let with_answer = RunResult { response: Some(response), ..result(0, "Login", Vec::new()) }; ended(&mut harness, with_answer); click_id(&mut harness, "http-runner-result-passed"); assert!(has(&harness, "http-response-status")); @@ -445,9 +396,7 @@ fn a_protected_environment_asks_once_before_the_run() { click_id(&mut harness, "http-runner-start"); click_id(&mut harness, "http-runner-protected-go"); - until(&mut harness, "the run is over", |harness| { - phase(harness) == Phase::Done - }); + until(&mut harness, "the run is over", |harness| phase(harness) == Phase::Done); } #[test] @@ -459,11 +408,7 @@ fn the_console_of_a_run_hears_its_sends_and_the_next_run_forgets_it() { at: Utc::now(), request: "Login".to_owned(), iteration: None, - line: ConsoleLine::Log { - level: LogLevel::default(), - text: "heard".to_owned(), - by: None, - }, + line: ConsoleLine::Log { level: LogLevel::default(), text: "heard".to_owned(), by: None }, }; harness.state_mut().state.http.receive_console(line); settle(&mut harness); @@ -471,9 +416,7 @@ fn the_console_of_a_run_hears_its_sends_and_the_next_run_forgets_it() { assert_eq!(count(&harness, "http-console-line"), 1); click_id(&mut harness, "http-runner-start-empty"); - until(&mut harness, "the next run is over", |harness| { - phase(harness) == Phase::Done - }); + until(&mut harness, "the next run is over", |harness| phase(harness) == Phase::Done); assert_eq!(count(&harness, "http-console-line"), 0); } @@ -484,13 +427,58 @@ fn a_summary_counts_what_ran() { result(0, "Orders", vec![passed("found")]), ]; let said = RunSummary::of(&results); - assert_eq!( - said, - RunSummary { - failures: 1, - requests: 2, - passed: 2, - tests: 3, + assert_eq!(said, RunSummary { failures: 1, requests: 2, passed: 2, tests: 3 }); +} + +/// Let go a row further, or back: the keys' twin. +#[test] +fn a_row_dragged_by_its_grip_lands_where_it_is_let_go() { + let mut harness = runner("/json"); + let grip = |harness: &Harness<'_, Bench>, rank: usize| { + harness + .query_all_by(|node| node.author_id() == Some("http-runner-row-grip")) + .nth(rank) + .unwrap() + .rect() + .center() + }; + let drag = |harness: &mut Harness<'_, Bench>, from: egui::Pos2, to: egui::Pos2| { + let button = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.step(); + for part in 1..=4_u8 { + harness.event(egui::Event::PointerMoved(from.lerp(to, f32::from(part) / 4.0))); + harness.step(); } - ); + harness.event(button(to, false)); + settle(harness); + }; + let (first, second) = (grip(&harness, 0), grip(&harness, 1)); + drag(&mut harness, first, second); + assert_eq!(labels(&harness, "http-runner-row"), ["Orders", "Login"]); + drag(&mut harness, second, first); + assert_eq!(labels(&harness, "http-runner-row"), ["Login", "Orders"]); + drag(&mut harness, first, first + egui::vec2(3.0, 2.0)); + assert_eq!(labels(&harness, "http-runner-row"), ["Login", "Orders"]); +} + +#[test] +fn alt_and_up_moves_a_row_back() { + let mut harness = runner("/json"); + harness + .get_by(|node| { + node.author_id() == Some("http-runner-row") && node.label().as_deref() == Some("Orders") + }) + .focus(); + settle(&mut harness); + harness.key_press_modifiers(egui::Modifiers::ALT, egui::Key::ArrowUp); + settle(&mut harness); + + assert_eq!(labels(&harness, "http-runner-row"), ["Orders", "Login"]); } diff --git a/crates/ui/src/http/save_as_note.rs b/crates/ui/src/http/save_as_note.rs index bd22d4918..64f156c6e 100644 --- a/crates/ui/src/http/save_as_note.rs +++ b/crates/ui/src/http/save_as_note.rs @@ -27,16 +27,8 @@ impl NoteForm { fn of(asked: &NoteAsked, state: &AppState) -> Self { let spaces = state.spaces.spaces(); let active = state.spaces.active_space(); - let space = spaces - .iter() - .position(|space| Some(space.id.as_str()) == active) - .unwrap_or(0); - Self { - title: asked.title.clone(), - tags: asked.tags.clone(), - space, - folder: 0, - } + let space = spaces.iter().position(|space| Some(space.id.as_str()) == active).unwrap_or(0); + Self { title: asked.title.clone(), tags: asked.tags.clone(), space, folder: 0 } } } @@ -59,10 +51,7 @@ pub(crate) fn show(ui: &Ui, state: &AppState, form: &mut Option, actio ui, ( "save-as-note", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "save-as-note-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "save-as-note-cross"), ), |ui| body(ui, state, asked, open), ); @@ -89,10 +78,8 @@ fn placement(state: &AppState, form: &NoteForm) -> Option { .folder .checked_sub(1) .and_then(|at| folders_of(state, &space.id).get(at).copied()); - let place = folder.map_or_else( - || space.name.clone(), - |folder| format!("{} › {}", space.name, folder.name), - ); + let place = + folder.map_or_else(|| space.name.clone(), |folder| format!("{} › {}", space.name, folder.name)); Some(Placement { title: form.title.trim().to_owned(), space_id: space.id.clone(), @@ -111,11 +98,7 @@ fn body(ui: &mut Ui, state: &AppState, asked: &NoteAsked, form: &mut NoteForm) - ui.spacing_mut().item_spacing.y = gap::INSET; let title = tr(keys::tools::save_as_note::TITLE); crate::widgets::dialog_title(ui, &title, "save-as-note"); - let what = i18n::translate( - language, - asked.what, - &[("language", asked.language.as_str().into())], - ); + let what = i18n::translate(language, asked.what, &[("language", asked.language.as_str().into())]); let what = egui::RichText::new(what).size(font::BODY).color(p.text_2); let said = ui.add(egui::Label::new(what).wrap()); widgets::address(ui, &said, "save-as-note-what"); @@ -129,9 +112,7 @@ fn body(ui: &mut Ui, state: &AppState, asked: &NoteAsked, form: &mut NoteForm) - .hint(&tr(keys::tools::save_as_note::TAGS_PLACEHOLDER)) .show(ui); if let Some(warning) = asked.warning { - let warning = egui::RichText::new(tr(warning)) - .size(font::BODY) - .color(p.red); + let warning = egui::RichText::new(tr(warning)).size(font::BODY).color(p.red); let said = ui.add(egui::Label::new(warning).wrap()); widgets::address(ui, &said, "save-as-note-warning"); } @@ -174,11 +155,8 @@ fn place(ui: &mut Ui, state: &AppState, form: &mut NoteForm) { let spaces = state.spaces.spaces(); let label = tr(keys::tools::save_as_note::SPACE); caption(ui, &label); - let options: Vec<(usize, &str)> = spaces - .iter() - .enumerate() - .map(|(at, space)| (at, space.name.as_str())) - .collect(); + let options: Vec<(usize, &str)> = + spaces.iter().enumerate().map(|(at, space)| (at, space.name.as_str())).collect(); let menu = ChoiceMenu::new(&label, "save-as-note-space", &options).show(ui, &mut form.space); if menu.changed() { form.folder = 0; @@ -191,11 +169,6 @@ fn place(ui: &mut Ui, state: &AppState, form: &mut NoteForm) { let none = tr(keys::tools::save_as_note::NO_FOLDER); let folders = folders_of(state, &space.id); let mut options: Vec<(usize, &str)> = vec![(0, none.as_str())]; - options.extend( - folders - .iter() - .enumerate() - .map(|(at, folder)| (at + 1, folder.name.as_str())), - ); + options.extend(folders.iter().enumerate().map(|(at, folder)| (at + 1, folder.name.as_str()))); ChoiceMenu::new(&label, "save-as-note-folder", &options).show(ui, &mut form.folder); } diff --git a/crates/ui/src/http/save_request.rs b/crates/ui/src/http/save_request.rs index f9b7e8546..d8ddca06c 100644 --- a/crates/ui/src/http/save_request.rs +++ b/crates/ui/src/http/save_request.rs @@ -93,10 +93,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, form: &mut Option, actio ui, ( "http-save-dialog", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "http-save-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "http-save-cross"), ), |ui| body(ui, open, &places, state.language), ); @@ -113,12 +110,7 @@ pub(super) fn show(ui: &Ui, state: &AppState, form: &mut Option, actio } /// `true` on « Save », `false` on « Cancel ». -fn body( - ui: &mut Ui, - form: &mut SaveForm, - places: &[SavePlace], - language: i18n::Language, -) -> Option { +fn body(ui: &mut Ui, form: &mut SaveForm, places: &[SavePlace], language: i18n::Language) -> Option { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); ui.set_width(WIDTH.min(ui.ctx().content_rect().width() * 0.9)); @@ -170,11 +162,8 @@ fn caption(ui: &mut Ui, words: &str) { fn place(ui: &mut Ui, form: &mut SaveForm, places: &[SavePlace], language: i18n::Language) { let tr = |key| i18n::translate(language, key, &[]); let new_collection = tr(keys::http::save::NEW_COLLECTION); - let mut options: Vec<(usize, &str)> = places - .iter() - .enumerate() - .map(|(at, place)| (at, place.path.as_str())) - .collect(); + let mut options: Vec<(usize, &str)> = + places.iter().enumerate().map(|(at, place)| (at, place.path.as_str())).collect(); options.push((places.len(), &new_collection)); form.place = form.place.min(places.len()); if !places.is_empty() { @@ -202,9 +191,7 @@ fn place(ui: &mut Ui, form: &mut SaveForm, places: &[SavePlace], language: i18n: return; }; let label = tr(keys::http::save::FOLDER_NAME); - TextField::new(folder, &label, "http-save-folder") - .hint(&label) - .show(ui); + TextField::new(folder, &label, "http-save-folder").hint(&label).show(ui); if Button::new(&tr(keys::http::save::NO_FOLDER), "http-save-folder-cancel") .show(ui) .clicked() @@ -212,3 +199,6 @@ fn place(ui: &mut Ui, form: &mut SaveForm, places: &[SavePlace], language: i18n: form.folder = None; } } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/save_request/tests.rs b/crates/ui/src/http/save_request/tests.rs new file mode 100644 index 000000000..0ae66b91b --- /dev/null +++ b/crates/ui/src/http/save_request/tests.rs @@ -0,0 +1,48 @@ +//! What a first save asks for, or lacks. + +use super::*; + +fn form(name: &str, place: usize) -> SaveForm { + SaveForm { + key: "key".to_owned(), + name: name.to_owned(), + place, + collection: String::new(), + folder: None, + missing: None, + } +} + +fn places() -> Vec { + let place = |folder: Option<&str>| SavePlace { + collection_id: "c".to_owned(), + folder_id: folder.map(str::to_owned), + path: "API".to_owned(), + }; + vec![place(None), place(Some("f"))] +} + +#[test] +fn a_request_needs_a_name_and_a_place_that_has_one() { + let new = places().len(); + let blank = SaveForm { folder: Some(" ".to_owned()), ..form("Login", 0) }; + for (form, missing) in + [(form(" ", 0), Missing::Name), (form("Login", new), Missing::Collection), (blank, Missing::Folder)] + { + assert_eq!(form.target(&places()).err(), Some(missing)); + } +} + +#[test] +fn it_goes_where_the_form_says_under_its_name_trimmed() { + let target = |form: SaveForm| form.target(&places()).ok().unwrap(); + let in_folder = target(form(" Login ", 1)); + assert_eq!(in_folder.name, "Login"); + assert_eq!((in_folder.collection_id.as_str(), in_folder.folder_id.as_deref()), ("c", Some("f"))); + assert!(matches!(in_folder.create, ToCreate::Nothing)); + + let made = target(SaveForm { folder: Some(" Auth ".to_owned()), ..form("Login", 0) }); + assert!(matches!(made.create, ToCreate::Folder(name) if name == "Auth")); + let first = target(SaveForm { collection: " API ".to_owned(), ..form("Login", 2) }); + assert!(matches!(first.create, ToCreate::Collection(name) if name == "API")); +} diff --git a/crates/ui/src/http/scripts.rs b/crates/ui/src/http/scripts.rs index d99658e4e..209c27180 100644 --- a/crates/ui/src/http/scripts.rs +++ b/crates/ui/src/http/scripts.rs @@ -4,9 +4,7 @@ use crate::theme::tokens::{font, gap, radius}; use std::ops::Range; -use egui::{ - Color32, CornerRadius, FontFamily, FontId, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, -}; +use egui::{Color32, CornerRadius, FontFamily, FontId, Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2}; use engine::http::model::RequestScripts; use engine::http::scripts::model::ScriptKind; use engine::http::settings::{HttpOrigin, InheritedScripts}; @@ -24,40 +22,18 @@ const NAMES: &str = "req · res · env · pm · require('lodash')…"; /// Five, so the menu stays short; each says the API it shows. const EXAMPLES: [(&str, i18n::Key, &str); 5] = [ - ( - "http-script-example-read", - keys::http::scripts::examples::READ_RESPONSE, - "res.json()", - ), - ( - "http-script-example-variable", - keys::http::scripts::examples::SET_VARIABLE, - "env.set", - ), - ( - "http-script-example-header", - keys::http::scripts::examples::ADD_HEADER, - "req.headers", - ), - ( - "http-script-example-send", - keys::http::scripts::examples::SEND_REQUEST, - "pm.sendRequest", - ), - ( - "http-script-example-test", - keys::http::scripts::examples::TEST_STATUS, - "test", - ), + ("http-script-example-read", keys::http::scripts::examples::READ_RESPONSE, "res.json()"), + ("http-script-example-variable", keys::http::scripts::examples::SET_VARIABLE, "env.set"), + ("http-script-example-header", keys::http::scripts::examples::ADD_HEADER, "req.headers"), + ("http-script-example-send", keys::http::scripts::examples::SEND_REQUEST, "pm.sendRequest"), + ("http-script-example-test", keys::http::scripts::examples::TEST_STATUS, "test"), ]; fn example_code(author_id: &str, test_name: &str) -> String { match author_id { "http-script-example-read" => "const body = res.json();\nconsole.log(body);".to_owned(), "http-script-example-variable" => "env.set('name', 'value');".to_owned(), - "http-script-example-header" => { - "req.headers.set('X-Request-Id', crypto.randomUUID());".to_owned() - } + "http-script-example-header" => "req.headers.set('X-Request-Id', crypto.randomUUID());".to_owned(), "http-script-example-send" => { "const answer = await pm.sendRequest({ url: env.get('baseUrl'), method: 'GET' });\n\ console.log(answer.code);" @@ -197,10 +173,7 @@ pub(crate) fn show( changed = Some(typed); } let p = palette(ui.ctx()); - let hint = format!( - "{NAMES} · {}", - i18n::translate(language, keys::http::scripts::HINT, &[]) - ); + let hint = format!("{NAMES} · {}", i18n::translate(language, keys::http::scripts::HINT, &[])); let hint = egui::RichText::new(hint).size(font::LABEL).color(p.text_2); ui.add(egui::Label::new(hint).wrap()); changed @@ -223,10 +196,7 @@ fn toolbar( ui.horizontal(|ui| { if options.len() > 1 { let mut phase = view.phase; - if Segmented::new(&options, "http-script-phase") - .show(ui, &mut phase) - .changed() - { + if Segmented::new(&options, "http-script-phase").show(ui, &mut phase).changed() { view.phase = phase; view.line = None; } @@ -247,15 +217,8 @@ fn examples( language: i18n::Language, ) -> Option { let tr = |key| i18n::translate(language, key, &[]); - let anchor = Button::new( - &tr(keys::http::scripts::examples::OPEN), - "http-script-examples", - ) - .show(ui); - let words: Vec = EXAMPLES - .iter() - .map(|(_, key, api)| format!("{} · {api}", tr(*key))) - .collect(); + let anchor = Button::new(&tr(keys::http::scripts::examples::OPEN), "http-script-examples").show(ui); + let words: Vec = EXAMPLES.iter().map(|(_, key, api)| format!("{} · {api}", tr(*key))).collect(); let items: Vec> = EXAMPLES .iter() .zip(&words) @@ -265,17 +228,9 @@ fn examples( let name = tr(keys::http::scripts::examples::TEST_NAME); let block = example_code(chosen, &name); let current = source(field.scripts, view.phase).trim_end(); - let text = if current.is_empty() { - format!("{block}\n") - } else { - format!("{current}\n\n{block}\n") - }; + let text = if current.is_empty() { format!("{block}\n") } else { format!("{current}\n\n{block}\n") }; view.line = None; - Some(Changed::Scripts(with_source( - field.scripts, - view.phase, - text, - ))) + Some(Changed::Scripts(with_source(field.scripts, view.phase, text))) } /// Before the send from the collection down; after the answer, back up. A level above is a click @@ -297,45 +252,29 @@ fn order( let mut opened = None; ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; - let words = egui::RichText::new(tr(order_words(phase))) - .size(font::LABEL) - .color(p.text_2); + let words = egui::RichText::new(tr(order_words(phase))).size(font::LABEL).color(p.text_2); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-script-order-label"); for (at, level) in levels.iter().enumerate() { if at > 0 { - ui.add(egui::Label::new( - egui::RichText::new("›").size(font::LABEL).color(p.text_2), - )); + ui.add(egui::Label::new(egui::RichText::new("›").size(font::LABEL).color(p.text_2))); } let Some(level) = level else { - let here = format!( - "{} {}", - tr(keys::http::scripts::levels::REQUEST), - field.request_name - ); + let here = format!("{} {}", tr(keys::http::scripts::levels::REQUEST), field.request_name); let words = egui::RichText::new(here).size(font::LABEL).color(p.text_0); let said = ui.add(egui::Label::new(words)); widgets::address(ui, &said, "http-script-level"); continue; }; - let kind = tr( - if level.from.kind == engine::http::model::HttpItemKind::Folder { - keys::http::scripts::levels::FOLDER - } else { - keys::http::scripts::levels::COLLECTION - }, - ); - let written = !source(&level.scripts, phase).trim().is_empty(); - let none = if written { - String::new() + let kind = tr(if level.from.kind == engine::http::model::HttpItemKind::Folder { + keys::http::scripts::levels::FOLDER } else { - format!(" · {}", tr(keys::http::scripts::NONE)) - }; + keys::http::scripts::levels::COLLECTION + }); + let written = !source(&level.scripts, phase).trim().is_empty(); + let none = if written { String::new() } else { format!(" · {}", tr(keys::http::scripts::NONE)) }; let words = format!("{kind} {}{none}", level.from.name); - let pressed = Button::new(&words, "http-script-level") - .kind(widgets::Kind::Quiet) - .show(ui); + let pressed = Button::new(&words, "http-script-level").kind(widgets::Kind::Quiet).show(ui); let pressed = widgets::tooltip(pressed, &tr(keys::http::scripts::OPEN_LEVEL)); if pressed.clicked() { opened = Some(level.from.clone()); @@ -369,8 +308,8 @@ fn code( } } if document.colouring.is_none() && text::highlight::is_ready() { - document.colouring = crate::notes::language::syntax(Language::Js) - .and_then(|syntax| Colouring::new(ui.ctx(), syntax)); + document.colouring = + crate::notes::language::syntax(Language::Js).and_then(|syntax| Colouring::new(ui.ctx(), syntax)); } let size = Vec2::new(ui.available_width(), CODE_HEIGHT); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); diff --git a/crates/ui/src/http/scripts_tests.rs b/crates/ui/src/http/scripts_tests.rs index 2c6401c02..e90b30673 100644 --- a/crates/ui/src/http/scripts_tests.rs +++ b/crates/ui/src/http/scripts_tests.rs @@ -69,10 +69,7 @@ fn an_example_is_written_at_the_end_of_the_script() { click_id(&mut harness, "http-script-examples"); click_id(&mut harness, "http-script-example-variable"); - assert_eq!( - scripts_of(&harness).before, - "const a = 1;\n\nenv.set('name', 'value');\n" - ); + assert_eq!(scripts_of(&harness).before, "const a = 1;\n\nenv.set('name', 'value');\n"); } #[test] @@ -82,11 +79,7 @@ fn the_tests_are_counted_by_what_they_declare() { click_id(&mut harness, "http-script-examples"); click_id(&mut harness, "http-script-example-test"); - assert!( - scripts_of(&harness) - .tests - .starts_with("test(\"The status is 200\"") - ); + assert!(scripts_of(&harness).tests.starts_with("test(\"The status is 200\"")); assert_eq!(said_count(&harness), ["1"]); } @@ -100,14 +93,8 @@ fn the_order_names_the_levels_and_one_opens_on_the_script_in_view() { == 3 }); - click_named( - &mut harness, - "http-script-level", - "collection Paiements · none", - ); - until(&mut harness, "its settings are open", |harness| { - has(harness, "http-settings-dialog") - }); + click_named(&mut harness, "http-script-level", "collection Paiements · none"); + until(&mut harness, "its settings are open", |harness| has(harness, "http-settings-dialog")); let form = harness.state().state.http.container().unwrap(); assert_eq!(form.focus, Some((ScriptKind::Before, None))); } @@ -118,13 +105,11 @@ fn a_rule_stands_among_the_scripts_after_the_answer() { let tabs = harness.state_mut().state.http.tabs_mut(); let key = tabs.active().unwrap().key.clone(); tabs.edit(&key, |draft| { - draft.apply(DraftEdit::Extractions(vec![ - engine::http::model::Extraction { - path: "body.id".to_owned(), - variable: "id".to_owned(), - secret: false, - }, - ])); + draft.apply(DraftEdit::Extractions(vec![engine::http::model::Extraction { + path: "body.id".to_owned(), + variable: "id".to_owned(), + secret: false, + }])); }); settle(&mut harness); assert!(!has(&harness, "http-extraction")); @@ -150,15 +135,7 @@ fn stop(level: ScriptLevel, script: ScriptKind, owner: Option) -> Script #[test] fn open_the_script_leads_to_the_request_s_own_on_the_line_that_stopped() { let mut harness = editing(); - let key = harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .key - .clone(); + let key = harness.state().state.http.tabs().active().unwrap().key.clone(); let stopped = stop(ScriptLevel::Request, ScriptKind::Tests, None); let bench = harness.state_mut(); bench.state.http.open_script(&bench.backend, key, &stopped); @@ -186,17 +163,9 @@ fn open_the_script_of_a_collection_opens_its_settings_on_the_phase() { let bench = harness.state_mut(); let key = "any".to_owned(); bench.state.http.open_script(&bench.backend, key, &stopped); - until(&mut harness, "the settings are open", |harness| { - harness.state().state.http.container().is_some() - }); + until(&mut harness, "the settings are open", |harness| harness.state().state.http.container().is_some()); let form = harness.state().state.http.container().unwrap(); assert_eq!(form.focus, Some((ScriptKind::After, Some(2)))); - assert_eq!( - form.container.item, - HttpItem { - kind: HttpItemKind::Collection, - id - } - ); + assert_eq!(form.container.item, HttpItem { kind: HttpItemKind::Collection, id }); } diff --git a/crates/ui/src/http/socket_log.rs b/crates/ui/src/http/socket_log.rs index 17001b9d1..6ac8fe60e 100644 --- a/crates/ui/src/http/socket_log.rs +++ b/crates/ui/src/http/socket_log.rs @@ -44,12 +44,7 @@ fn text_of(entry: &SocketEntry) -> &str { } } -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - (tab, view): (&Tab, &mut LogView), - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, (tab, view): (&Tab, &mut LogView), actions: &mut Actions) { let p = palette(ui.ctx()); let pane = ui.max_rect(); ui.painter().rect_filled(pane, CornerRadius::ZERO, p.bg_0); @@ -63,12 +58,7 @@ pub(super) fn show( ui.set_min_size(ui.available_size()); ui.spacing_mut().item_spacing.y = gap::INSET; bar(ui, state, (tab, view), actions); - if let Some(notice) = state - .http - .sockets() - .of(&tab.key) - .and_then(|it| it.notice.as_ref()) - { + if let Some(notice) = state.http.sockets().of(&tab.key).and_then(|it| it.notice.as_ref()) { failure(ui, tab, notice, state.language, actions); } entries(ui, state, tab, (&view.filter, &mut view.kept)); @@ -93,10 +83,7 @@ fn bar(ui: &mut Ui, state: &AppState, (tab, view): (&Tab, &mut LogView), actions if phase == Phase::Connecting { widgets::spinner(ui, 14.0, &tr(key)); } - let words = egui::RichText::new(tr(key)) - .size(font::LABEL) - .strong() - .color(p.text_1); + let words = egui::RichText::new(tr(key)).size(font::LABEL).strong().color(p.text_1); let said = egui::Frame::new() .fill(hue.gamma_multiply(0.15)) .corner_radius(egui::CornerRadius::same(radius::CONTROL)) @@ -105,11 +92,8 @@ fn bar(ui: &mut Ui, state: &AppState, (tab, view): (&Tab, &mut LogView), actions .inner; widgets::address(ui, &said, "http-socket-phase"); if let Some(protocol) = socket.and_then(|socket| socket.protocol.as_deref()) { - let words = i18n::translate( - language, - keys::http::socket::PROTOCOL, - &[("protocol", protocol.into())], - ); + let words = + i18n::translate(language, keys::http::socket::PROTOCOL, &[("protocol", protocol.into())]); let words = egui::RichText::new(words).size(font::LABEL).color(p.text_2); ui.add(egui::Label::new(words)); } @@ -138,21 +122,13 @@ fn bar(ui: &mut Ui, state: &AppState, (tab, view): (&Tab, &mut LogView), actions } /// « Network error » alone tells nothing: the cause's own words go with it. -fn failure( - ui: &mut Ui, - tab: &Tab, - notice: &AppError, - language: i18n::Language, - actions: &mut Actions, -) { +fn failure(ui: &mut Ui, tab: &Tab, notice: &AppError, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); let message = crate::services::errors::message_of(notice) .unwrap_or_else(|| i18n::Message::new(keys::http::socket::FAILED)); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; - let words = egui::RichText::new(message.text(language)) - .size(font::BODY) - .color(p.red); + let words = egui::RichText::new(message.text(language)).size(font::BODY).color(p.red); let said = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &said, "http-socket-failure"); if let Some(cause) = notice.params.get("cause") { @@ -161,11 +137,8 @@ fn failure( widgets::address(ui, &said, "http-socket-cause"); } if let Some(twin) = notice.params.get("twin") { - let words = i18n::translate( - language, - keys::http::socket::USE_TWIN, - &[("url", twin.as_str().into())], - ); + let words = + i18n::translate(language, keys::http::socket::USE_TWIN, &[("url", twin.as_str().into())]); if Button::new(&words, "http-socket-twin").show(ui).clicked() { actions.push(Asked::Http(Action::Edit { key: tab.key.clone(), @@ -188,9 +161,7 @@ fn entries(ui: &mut Ui, state: &AppState, tab: &Tab, (filter, kept): (&str, &mut if kept.of != of { let places = log.into_iter().flatten().enumerate(); kept.places = places - .filter(|(_, entry)| { - wanted.is_empty() || text_of(entry).to_lowercase().contains(&wanted) - }) + .filter(|(_, entry)| wanted.is_empty() || text_of(entry).to_lowercase().contains(&wanted)) .map(|(at, _)| at) .collect(); kept.of = of; @@ -215,11 +186,9 @@ fn entries(ui: &mut Ui, state: &AppState, tab: &Tab, (filter, kept): (&str, &mut fn words_of(entry: &SocketEntry, language: i18n::Language) -> String { let tr = |key| i18n::translate(language, key, &[]); match &entry.event { - SocketEvent::Opened { url, .. } => i18n::translate( - language, - keys::http::socket::OPENED, - &[("url", url.as_str().into())], - ), + SocketEvent::Opened { url, .. } => { + i18n::translate(language, keys::http::socket::OPENED, &[("url", url.as_str().into())]) + } SocketEvent::Closed { code, reason } => { let code = code.map_or_else(String::new, |code| code.to_string()); format!("{} {code} {reason}", tr(keys::http::socket::CLOSED)) @@ -235,11 +204,7 @@ fn words_of(entry: &SocketEntry, language: i18n::Language) -> String { fn size_of(entry: &SocketEntry, language: i18n::Language) -> Option { match entry.event { SocketEvent::Sent { size, .. } | SocketEvent::Received { size, .. } => { - Some(i18n::translate( - language, - keys::http::response::BYTES, - &[("value", size.into())], - )) + Some(i18n::translate(language, keys::http::response::BYTES, &[("value", size.into())])) } _ => None, } @@ -253,25 +218,11 @@ fn row(ui: &mut Ui, entry: &SocketEntry, language: i18n::Language) { response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "http-socket-entry"); let middle = rect.center().y; - let time = entry - .at - .with_timezone(&Local) - .format("%H:%M:%S%.3f") - .to_string(); - let galley = widgets::text( - ui, - &time, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let time = entry.at.with_timezone(&Local).format("%H:%M:%S%.3f").to_string(); + let galley = widgets::text(ui, &time, font::META, 400.0, FontFamily::Monospace, p.text_2); let width = galley.size().x; - ui.painter().galley( - pos2(rect.left(), middle - galley.size().y / 2.0), - galley, - p.text_2, - ); + ui.painter() + .galley(pos2(rect.left(), middle - galley.size().y / 2.0), galley, p.text_2); let glyph = Rect::from_center_size(pos2(rect.left() + width + 16.0, middle), Vec2::splat(12.0)); match entry.event { SocketEvent::Sent { .. } => icons::paint(ui, glyph, Icon::ArrowUp, p.amber_text), @@ -283,14 +234,7 @@ fn row(ui: &mut Ui, entry: &SocketEntry, language: i18n::Language) { let size_words = size_of(entry, language); let right = rect.right() - size_words.as_ref().map_or(0.0, |words| { - let galley = widgets::text( - ui, - words, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, words, font::META, 400.0, FontFamily::Proportional, p.text_2); let width = galley.size().x; let at = pos2(rect.right() - width, middle - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_2); @@ -298,14 +242,13 @@ fn row(ui: &mut Ui, entry: &SocketEntry, language: i18n::Language) { }); let left = glyph.right() + 8.0; let line = words.replace(['\n', '\r'], " "); - let ink = if matches!(entry.event, SocketEvent::Failed { .. }) { - p.red - } else { - p.text_0 - }; + let ink = if matches!(entry.event, SocketEvent::Failed { .. }) { p.red } else { p.text_0 }; let galley = widgets::text(ui, &line, font::LABEL, 400.0, FontFamily::Monospace, ink); let clip = Rect::from_min_max(pos2(left, rect.top()), pos2(right, rect.bottom())); let at = pos2(left, middle - galley.size().y / 2.0); ui.painter_at(clip).galley(at, galley, ink); widgets::tooltip(response, &words); } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/socket_log/tests.rs b/crates/ui/src/http/socket_log/tests.rs new file mode 100644 index 000000000..53ff95b43 --- /dev/null +++ b/crates/ui/src/http/socket_log/tests.rs @@ -0,0 +1,20 @@ +//! What a line of a socket's log says. + +use super::*; + +fn entry(event: SocketEvent) -> SocketEntry { + SocketEntry { event, at: chrono::Utc::now() } +} + +#[test] +fn each_event_says_what_happened() { + let got = + |text: &str, binary| SocketEvent::Received { text: text.to_owned(), binary, cut: false, size: 4 }; + let closed = |code, reason: &str| SocketEvent::Closed { code, reason: reason.to_owned() }; + let words = |event| words_of(&entry(event), i18n::Language::En); + assert_eq!(words(got("hello", false)), "hello"); + assert_ne!(words(got("hello", true)), "hello"); + assert!(words(closed(Some(1_000), "bye")).ends_with("1000 bye")); + let bare = words(closed(None, "")); + assert_eq!(bare, bare.trim_end()); +} diff --git a/crates/ui/src/http/socket_tests.rs b/crates/ui/src/http/socket_tests.rs index e09d1a884..97c0d8e24 100644 --- a/crates/ui/src/http/socket_tests.rs +++ b/crates/ui/src/http/socket_tests.rs @@ -29,9 +29,7 @@ fn socket() -> Harness<'static, Bench> { harness.set_size(egui::vec2(1_100.0, 900.0)); settle(&mut harness); click_named(&mut harness, "http-node-name", "WS Prix"); - until(&mut harness, "the composer is open", |harness| { - has(harness, "http-socket-message") - }); + until(&mut harness, "the composer is open", |harness| has(harness, "http-socket-message")); harness } @@ -79,14 +77,9 @@ fn active_key(harness: &Harness<'_, Bench>) -> String { fn an_address_a_socket_cannot_open_says_so_and_offers_its_twin() { let mut harness = socket(); click_id(&mut harness, "http-socket-connect"); - until(&mut harness, "the refusal is said", |harness| { - has(harness, "http-socket-twin") - }); + until(&mut harness, "the refusal is said", |harness| has(harness, "http-socket-twin")); assert!(has(&harness, "http-socket-failure")); - assert_eq!( - said_by(&harness, "http-socket-phase").as_deref(), - Some("Disconnected") - ); + assert_eq!(said_by(&harness, "http-socket-phase").as_deref(), Some("Disconnected")); click_id(&mut harness, "http-socket-twin"); assert!(active(&harness).document.url.starts_with("wss://")); @@ -94,11 +87,7 @@ fn an_address_a_socket_cannot_open_says_so_and_offers_its_twin() { /// An event under the id the tab's socket was connected with. fn event(id: &str, event: SocketEvent) -> WebsocketEvent { - WebsocketEvent { - id: id.to_owned(), - at: Utc::now(), - event, - } + WebsocketEvent { id: id.to_owned(), at: Utc::now(), event } } /// A connection left under way, its id known from its first event. @@ -112,15 +101,8 @@ fn connected(harness: &mut Harness<'_, Bench>) -> String { settle(harness); click_id(harness, "http-socket-connect"); let id = format!("{key}#1"); - let opened = SocketEvent::Opened { - url: "ws://local".to_owned(), - protocol: Some("chat".to_owned()), - }; - harness - .state_mut() - .state - .http - .receive_socket(event(&id, opened)); + let opened = SocketEvent::Opened { url: "ws://local".to_owned(), protocol: Some("chat".to_owned()) }; + harness.state_mut().state.http.receive_socket(event(&id, opened)); settle(harness); id } @@ -129,27 +111,13 @@ fn connected(harness: &mut Harness<'_, Bench>) -> String { fn what_went_each_way_is_logged_and_filtered() { let mut harness = socket(); let id = connected(&mut harness); - assert_eq!( - said_by(&harness, "http-socket-phase").as_deref(), - Some("Connected") - ); + assert_eq!(said_by(&harness, "http-socket-phase").as_deref(), Some("Connected")); let http = &mut harness.state_mut().state.http; + http.receive_socket(event(&id, SocketEvent::Sent { text: "ping".to_owned(), size: 4 })); http.receive_socket(event( &id, - SocketEvent::Sent { - text: "ping".to_owned(), - size: 4, - }, - )); - http.receive_socket(event( - &id, - SocketEvent::Received { - text: "pong".to_owned(), - size: 4, - binary: false, - cut: false, - }, + SocketEvent::Received { text: "pong".to_owned(), size: 4, binary: false, cut: false }, )); settle(&mut harness); let rows = |harness: &Harness<'_, Bench>| { @@ -169,12 +137,7 @@ fn what_went_each_way_is_logged_and_filtered() { // What arrives under a typed filter is sorted as it comes. let http = &mut harness.state_mut().state.http; for text in ["ping again", "PONG again"] { - let received = SocketEvent::Received { - text: text.to_owned(), - size: 10, - binary: false, - cut: false, - }; + let received = SocketEvent::Received { text: text.to_owned(), size: 10, binary: false, cut: false }; http.receive_socket(event(&id, received)); } settle(&mut harness); @@ -212,21 +175,52 @@ fn a_log_keeps_the_last_entries_and_an_old_socket_s_events_are_dropped() { let key = active_key(&harness); let http = &mut harness.state_mut().state.http; for _ in 0..LOG_KEPT + 3 { - http.receive_socket(event( - &id, - SocketEvent::Sent { - text: "x".to_owned(), - size: 1, - }, - )); + http.receive_socket(event(&id, SocketEvent::Sent { text: "x".to_owned(), size: 1 })); } - let closed = SocketEvent::Closed { - code: None, - reason: String::new(), - }; + let closed = SocketEvent::Closed { code: None, reason: String::new() }; http.receive_socket(event("replaced#9", closed)); let state = http.sockets().of(&key).unwrap(); assert_eq!(state.log.len(), LOG_KEPT); assert_eq!(state.phase, Phase::Open); } + +#[test] +fn a_kept_message_is_put_back_in_the_box() { + let mut harness = socket(); + type_message(&mut harness, "ping"); + click_id(&mut harness, "http-socket-keep"); + click_id(&mut harness, "http-socket-message"); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness + .get_by(|node| node.author_id() == Some("http-socket-message")) + .type_text("other"); + settle(&mut harness); + click_id(&mut harness, "http-socket-saved"); + + let text = harness.get_by(|node| node.author_id() == Some("http-socket-message")).value(); + assert_eq!(text.as_deref(), Some("ping")); +} + +/// Written once the field is left, the blanks between two names left out. +#[test] +fn the_subprotocols_asked_for_are_written_once_left() { + let mut harness = socket(); + click_id(&mut harness, "http-section-protocols"); + let field = |harness: &Harness<'_, Bench>| { + harness + .query_by(|node| node.author_id() == Some("http-socket-protocols")) + .is_some() + }; + assert!(field(&harness)); + click_id(&mut harness, "http-socket-protocols"); + harness + .get_by(|node| node.author_id() == Some("http-socket-protocols")) + .type_text("chat, , json "); + settle(&mut harness); + assert!(active(&harness).document.websocket.protocols.is_empty()); + harness.key_press(egui::Key::Enter); + settle(&mut harness); + + assert_eq!(active(&harness).document.websocket.protocols, ["chat", "json"]); +} diff --git a/crates/ui/src/http/tabs.rs b/crates/ui/src/http/tabs.rs index 845778d14..3cb3c7d64 100644 --- a/crates/ui/src/http/tabs.rs +++ b/crates/ui/src/http/tabs.rs @@ -4,8 +4,8 @@ use crate::theme::tokens::{BAR_HEIGHT, BAR_INSET, BAR_TOGGLE, Palette, font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Key, Modifiers, PointerButton, Popup, PopupCloseBehavior, - Rect, RectAlign, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2, + Color32, CornerRadius, FontFamily, Key, Modifiers, PointerButton, Popup, PopupCloseBehavior, Rect, + RectAlign, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2, }; use engine::http::model::{HttpMethod, RequestKind}; use i18n::keys; @@ -23,11 +23,8 @@ use crate::widgets::{self, SplitButton, SplitKind, interact}; pub(super) const HEIGHT: f32 = BAR_HEIGHT; /// The three a request is created as, in the order they are offered: HTTP first. -pub(super) const KINDS: [(RequestKind, &str); 3] = [ - (RequestKind::Http, "http"), - (RequestKind::Graphql, "graphql"), - (RequestKind::Websocket, "websocket"), -]; +pub(super) const KINDS: [(RequestKind, &str); 3] = + [(RequestKind::Http, "http"), (RequestKind::Graphql, "graphql"), (RequestKind::Websocket, "websocket")]; /// The other tabs, while one is dragged. const DIMMED: f32 = 0.55; @@ -52,11 +49,8 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut TabsView, actions: let language = state.language; let region = ui.max_rect(); let bar = Rect::from_min_size(region.min, Vec2::new(region.width(), HEIGHT)); - ui.painter().hline( - bar.x_range(), - bar.bottom() - 0.5, - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .hline(bar.x_range(), bar.bottom() - 0.5, Stroke::new(1.0, p.line_soft)); let end_width = end_width(ui, state); let toggle_rect = Rect::from_center_size( pos2(bar.left() + BAR_INSET + BAR_TOGGLE / 2.0, bar.center().y), @@ -65,12 +59,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut TabsView, actions: let mut toggle_ui = ui.new_child(egui::UiBuilder::new().max_rect(toggle_rect)); let toggle = i18n::translate(language, keys::sidebar::TOGGLE, &[]); if widgets::SquareButton::new(Icon::Sidebar, &toggle, "http-rail-toggle") - .keys( - state - .settings - .bindings - .of(crate::services::shortcuts::RAIL_ACTION), - ) + .keys(state.settings.bindings.of(crate::services::shortcuts::RAIL_ACTION)) .pressed(state.settings.rail_shown) .show(&mut toggle_ui) .clicked() @@ -81,10 +70,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut TabsView, actions: egui::UiBuilder::new() .max_rect(Rect::from_min_max( pos2(toggle_rect.right() + 8.0, bar.top()), - pos2( - bar.right() - end_width - BAR_INSET - gap::INSET, - bar.bottom(), - ), + pos2(bar.right() - end_width - BAR_INSET - gap::INSET, bar.bottom()), )) .layout(egui::Layout::left_to_right(egui::Align::Min)), ); @@ -116,10 +102,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut TabsView, actions: } drawn.push(whole); } - let at = tabs - .tabs() - .iter() - .position(|tab| view.dragging.as_ref() == Some(&tab.key)); + let at = tabs.tabs().iter().position(|tab| view.dragging.as_ref() == Some(&tab.key)); drop_dragged(ui, view, (&drawn, at), actions); }); }); @@ -155,22 +138,9 @@ fn tab_of( let badge = badge_of(tab); let dirty = tab.is_dirty(); let name = &tab.draft.name; - let method = widgets::text( - ui, - badge.short(), - font::CAPTION, - 700.0, - FontFamily::Monospace, - Color32::WHITE, - ); - let words = widgets::text( - ui, - name, - font::READING, - 400.0, - FontFamily::Proportional, - Color32::WHITE, - ); + let method = + widgets::text(ui, badge.short(), font::CAPTION, 700.0, FontFamily::Monospace, Color32::WHITE); + let words = widgets::text(ui, name, font::READING, 400.0, FontFamily::Proportional, Color32::WHITE); let dot = if dirty { 8.0 + 7.0 } else { 0.0 }; let width = (14.0 + method.size().x + 8.0 + words.size().x + dot + 4.0).min(240.0 - 34.0); let modified = i18n::translate(language, keys::http::tabs::MODIFIED, &[]); @@ -190,11 +160,7 @@ fn tab_of( || WidgetInfo::selected(Role::Tab, true, active, &label), CornerRadius::ZERO, ); - let close_label = i18n::translate( - language, - keys::http::tabs::CLOSE, - &[("name", name.as_str().into())], - ); + let close_label = i18n::translate(language, keys::http::tabs::CLOSE, &[("name", name.as_str().into())]); let close = close_button(ui, &close_label); ui.add_space(gap::SNUG); let whole = open.rect.union(close.rect); @@ -202,35 +168,22 @@ fn tab_of( ui.painter().set(fill, ground(whole, (active, dragged), p)); if active && !dragged { let edge = Rect::from_min_max(pos2(whole.left(), whole.bottom() - 2.0), whole.max); - ui.painter() - .rect_filled(edge, CornerRadius::ZERO, p.amber_fill); + ui.painter().rect_filled(edge, CornerRadius::ZERO, p.amber_fill); } - ui.painter().vline( - whole.right() - 0.5, - whole.y_range(), - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .vline(whole.right() - 0.5, whole.y_range(), Stroke::new(1.0, p.line_soft)); let middle = open.rect.center().y; let mut left = open.rect.left() + 14.0; let hue = badge_hue(ui, badge); - let method = widgets::text( - ui, - badge.short(), - font::CAPTION, - 700.0, - FontFamily::Monospace, - hue, - ); + let method = widgets::text(ui, badge.short(), font::CAPTION, 700.0, FontFamily::Monospace, hue); let method_width = method.size().x; - ui.painter() - .galley(pos2(left, middle - method.size().y / 2.0), method, hue); + ui.painter().galley(pos2(left, middle - method.size().y / 2.0), method, hue); left += method_width + 8.0; let ink = if active { p.text_0 } else { p.text_1 }; let room = open.rect.right() - 4.0 - dot - left; let words = widgets::one_line(ui, name, (font::READING, 400.0), ink, room); let words_width = words.size().x; - ui.painter() - .galley(pos2(left, middle - words.size().y / 2.0), words, ink); + ui.painter().galley(pos2(left, middle - words.size().y / 2.0), words, ink); if dirty { let centre = pos2(left + words_width + 8.0 + 3.5, middle); ui.painter().circle_filled(centre, 3.5, p.amber_text); @@ -246,8 +199,7 @@ fn ground(whole: Rect, (active, dragged): (bool, bool), p: &Palette) -> egui::Sh let lifted = whole.shrink2(vec2(1.0, 2.0)); let corner = CornerRadius::same(radius::CONTROL); let outline = Stroke::new(1.0, p.amber_fill); - return egui::epaint::RectShape::new(lifted, corner, p.bg_2, outline, StrokeKind::Inside) - .into(); + return egui::epaint::RectShape::new(lifted, corner, p.bg_2, outline, StrokeKind::Inside).into(); } if active { return egui::Shape::rect_filled(whole, CornerRadius::ZERO, p.bg_1); @@ -328,12 +280,9 @@ fn mark_gap(ui: &Ui, drawn: &[Rect], gap: usize) { }; let x = drawn.get(gap).map_or(last.right(), Rect::left); let p = palette(ui.ctx()); - let bar = Rect::from_min_max( - pos2(x - 1.0, first.top() + gap::SNUG), - pos2(x + 1.0, first.bottom() - gap::SNUG), - ); - ui.painter() - .rect_filled(bar, CornerRadius::same(radius::MARK), p.amber_text); + let bar = + Rect::from_min_max(pos2(x - 1.0, first.top() + gap::SNUG), pos2(x + 1.0, first.bottom() - gap::SNUG)); + ui.painter().rect_filled(bar, CornerRadius::same(radius::MARK), p.amber_text); } fn badge_of(tab: &Tab) -> Badge { @@ -359,8 +308,7 @@ fn close_glyph(ui: &Ui, close: &Response) { let p = palette(ui.ctx()); let square = Rect::from_center_size(close.rect.center(), Vec2::splat(widgets::MIN_TARGET)); let ink = if close.hovered() { - ui.painter() - .rect_filled(square, CornerRadius::same(radius::CONTROL), p.bg_3); + ui.painter().rect_filled(square, CornerRadius::same(radius::CONTROL), p.bg_3); p.text_0 } else { p.text_2 @@ -380,11 +328,7 @@ fn new_request_width(ui: &Ui, language: i18n::Language) -> f32 { } fn split<'a>(label: &'a str, kinds: &'a str) -> SplitButton<'a> { - SplitButton::new( - (label, "http-tab-new"), - (kinds, "http-tab-new-kind"), - SplitKind::Neutral, - ) + SplitButton::new((label, "http-tab-new"), (kinds, "http-tab-new-kind"), SplitKind::Neutral) } /// « + New request », split: an HTTP request in one click, the other kinds in two. @@ -404,16 +348,8 @@ fn new_request(ui: &mut Ui, actions: &mut Actions, language: i18n::Language) { ui.spacing_mut().item_spacing.y = gap::LINE; let p = palette(ui.ctx()); let title = tr(keys::http::kinds::MENU_TITLE).to_uppercase(); - let galley = widgets::text( - ui, - &title, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, _) = - ui.allocate_exact_size(Vec2::new(galley.size().x, 22.0), Sense::hover()); + let galley = widgets::text(ui, &title, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); + let (rect, _) = ui.allocate_exact_size(Vec2::new(galley.size().x, 22.0), Sense::hover()); ui.painter() .galley(pos2(rect.left() + 10.0, rect.top() + 6.0), galley, p.text_2); for (kind, id) in KINDS { @@ -452,38 +388,13 @@ fn kind_item(ui: &mut Ui, kind: RequestKind, id: &str, language: i18n::Language) RequestKind::Websocket => Badge::Websocket, }; let hue = badge_hue(ui, badge); - let glyph = widgets::text( - ui, - badge.short(), - font::CAPTION, - 700.0, - FontFamily::Monospace, - hue, - ); - ui.painter().galley( - pos2(rect.left() + 10.0, rect.center().y - glyph.size().y / 2.0), - glyph, - hue, - ); - let left = rect.left() + 54.0; - let name = widgets::text( - ui, - &name, - font::BODY, - 600.0, - FontFamily::Proportional, - p.text_0, - ); - ui.painter() - .galley(pos2(left, rect.top() + 6.0), name, p.text_0); - let line = widgets::one_line( - ui, - &line, - (font::META, 400.0), - p.text_2, - rect.right() - 10.0 - left, - ); + let glyph = widgets::text(ui, badge.short(), font::CAPTION, 700.0, FontFamily::Monospace, hue); ui.painter() - .galley(pos2(left, rect.top() + 24.0), line, p.text_2); + .galley(pos2(rect.left() + 10.0, rect.center().y - glyph.size().y / 2.0), glyph, hue); + let left = rect.left() + 54.0; + let name = widgets::text(ui, &name, font::BODY, 600.0, FontFamily::Proportional, p.text_0); + ui.painter().galley(pos2(left, rect.top() + 6.0), name, p.text_0); + let line = widgets::one_line(ui, &line, (font::META, 400.0), p.text_2, rect.right() - 10.0 - left); + ui.painter().galley(pos2(left, rect.top() + 24.0), line, p.text_2); response } diff --git a/crates/ui/src/http/tests.rs b/crates/ui/src/http/tests.rs index 124dfef83..6c53d514c 100644 --- a/crates/ui/src/http/tests.rs +++ b/crates/ui/src/http/tests.rs @@ -3,8 +3,7 @@ use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use engine::http::model::{ - HttpCollection, HttpFolder, HttpMethod, HttpRequest, HttpRequestDraft, RequestDocument, - RequestKind, + HttpCollection, HttpFolder, HttpMethod, HttpRequest, HttpRequestDraft, RequestDocument, RequestKind, }; use crate::backend::Backend; @@ -15,10 +14,8 @@ use crate::testing; pub(crate) fn collection(backend: &Backend, name: &str) -> HttpCollection { let name = name.to_owned(); - engine::db::run_here(backend.engine(), move |engine| { - engine::http::create_http_collection(engine, &name) - }) - .unwrap() + engine::db::run_here(backend.engine(), move |engine| engine::http::create_http_collection(engine, &name)) + .unwrap() } pub(crate) fn folder(backend: &Backend, collection: &HttpCollection, name: &str) -> HttpFolder { @@ -46,10 +43,8 @@ pub(crate) fn request( ..RequestDocument::default() }, }; - engine::db::run_here(backend.engine(), move |engine| { - engine::http::create_http_request(engine, &draft) - }) - .unwrap() + engine::db::run_here(backend.engine(), move |engine| engine::http::create_http_request(engine, &draft)) + .unwrap() } /// `Paiements[Auth[Login] Socket]`, the HTTP area shown. @@ -75,21 +70,14 @@ pub(crate) fn click_named(harness: &mut Harness<'_, Bench>, author_id: &str, nam fn the_rail_lays_the_tree_flat_with_each_request_after_its_method() { let harness = paiements(); - assert_eq!( - names(&harness, "http-node-name"), - ["Paiements", "Auth", "POST Login", "WS Socket"] - ); + assert_eq!(names(&harness, "http-node-name"), ["Paiements", "Auth", "POST Login", "WS Socket"]); assert_eq!( harness .query_all_by(|node| node.author_id() == Some("http-node-twisty")) .count(), 2 ); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-rail-empty")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-rail-empty")).is_none()); } #[test] @@ -98,13 +86,9 @@ fn a_folder_folds_on_its_twisty_and_on_its_name_and_is_remembered() { click_named(&mut harness, "http-node-twisty", "Collapse Auth"); - assert_eq!( - names(&harness, "http-node-name"), - ["Paiements", "Auth", "WS Socket"] - ); - let folded = harness.get_by(|node| { - node.author_id() == Some("http-node-name") && node.label().as_deref() == Some("Auth") - }); + assert_eq!(names(&harness, "http-node-name"), ["Paiements", "Auth", "WS Socket"]); + let folded = harness + .get_by(|node| node.author_id() == Some("http-node-name") && node.label().as_deref() == Some("Auth")); assert_eq!(folded.accesskit_node().data().is_expanded(), Some(false)); let auth = engine::db::run_here(harness.state().backend.engine(), engine::http::http_tree) .unwrap() @@ -117,10 +101,7 @@ fn a_folder_folds_on_its_twisty_and_on_its_name_and_is_remembered() { }) .unwrap(); settle(&mut harness); - assert_eq!( - remembered(&harness, COLLAPSED_KEY), - Some(format!(r#"["{auth}"]"#)) - ); + assert_eq!(remembered(&harness, COLLAPSED_KEY), Some(format!(r#"["{auth}"]"#))); click_named(&mut harness, "http-node-name", "Paiements"); assert_eq!(names(&harness, "http-node-name"), ["Paiements"]); @@ -131,11 +112,7 @@ fn an_empty_library_says_it_has_no_collection() { let (backend, profile) = testing::unlocked(); let harness = area_of(Area::Http, backend, profile); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-rail-empty")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-rail-empty")).is_some()); assert_eq!(names(&harness, "http-node-name"), Vec::::new()); } @@ -145,11 +122,7 @@ fn ctrl_b_puts_the_rail_away_and_brings_it_back() { harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::B); settle(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-node-name")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-node-name")).is_none()); harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::B); settle(&mut harness); @@ -163,12 +136,7 @@ fn thousands(backend: &Backend) { let folder = folder(backend, &api, &format!("folder {at}")); for index in 0..50 { let name = format!("request {at}-{index}"); - request( - backend, - (&api, Some(&folder)), - &name, - (RequestKind::Http, HttpMethod::Get), - ); + request(backend, (&api, Some(&folder)), &name, (RequestKind::Http, HttpMethod::Get)); } } } @@ -179,9 +147,7 @@ fn only_the_rows_in_view_of_two_thousand_requests_are_drawn() { thousands(&backend); let harness = area_of(Area::Http, backend, profile); - let drawn = harness - .query_all_by(|node| node.author_id() == Some("http-node-name")) - .count(); + let drawn = harness.query_all_by(|node| node.author_id() == Some("http-node-name")).count(); assert!(drawn > 10 && drawn < 60, "{drawn} rows drawn"); assert_eq!(harness.state().state.http.rows().len(), 2_041); } @@ -196,11 +162,7 @@ fn http_rail_budget() { let started = std::time::Instant::now(); let tree = engine::db::run_here(backend.engine(), engine::http::http_tree).unwrap(); let rows = crate::state::http::tree::rail_rows(&tree, &std::collections::BTreeSet::new()); - println!( - "2,000 requests: read and laid out in {:?} ({} rows)", - started.elapsed(), - rows.len() - ); + println!("2,000 requests: read and laid out in {:?} ({} rows)", started.elapsed(), rows.len()); let mut harness = area_of(Area::Http, backend, profile); let started = std::time::Instant::now(); click_named(&mut harness, "http-node-name", "folder 0"); @@ -226,10 +188,7 @@ fn http_rail_budget() { frames.push(started.elapsed()); } frames.sort(); - println!( - "scrolling p50 {:?}, p95 {:?}, p99 {:?}", - frames[100], frames[190], frames[198] - ); + println!("scrolling p50 {:?}, p95 {:?}, p99 {:?}", frames[100], frames[190], frames[198]); } pub(crate) fn click_id(harness: &mut Harness<'_, Bench>, author_id: &str) { @@ -257,9 +216,7 @@ fn said(harness: &Harness<'_, Bench>) -> String { fn focus_row(harness: &mut Harness<'_, Bench>, name: &str) { harness - .get_by(|node| { - node.author_id() == Some("http-node-name") && node.label().as_deref() == Some(name) - }) + .get_by(|node| node.author_id() == Some("http-node-name") && node.label().as_deref() == Some(name)) .focus(); settle(harness); } @@ -273,11 +230,7 @@ fn the_first_collection_is_offered_from_the_empty_rail() { crate::notes::bench::type_and_enter(&mut harness, "http-create-input", "API"); assert_eq!(names(&harness, "http-node-name"), ["API"]); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-rail-empty")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-rail-empty")).is_none()); } #[test] @@ -286,23 +239,12 @@ fn a_folder_and_a_request_are_made_from_a_row_s_menu() { choose(&mut harness, "Paiements", &["http-node-new-folder"]); crate::notes::bench::type_and_enter(&mut harness, "http-create-input", "Factures"); - choose( - &mut harness, - "Factures", - &["http-node-new", "http-node-new-graphql"], - ); + choose(&mut harness, "Factures", &["http-node-new", "http-node-new-graphql"]); crate::notes::bench::type_and_enter(&mut harness, "http-create-input", "Lister"); assert_eq!( names(&harness, "http-node-name"), - [ - "Paiements", - "Auth", - "POST Login", - "WS Socket", - "Factures", - "GQL Lister" - ] + ["Paiements", "Auth", "POST Login", "WS Socket", "Factures", "GQL Lister"] ); assert_eq!(harness.state().state.http.tabs().tabs().len(), 1); } @@ -330,11 +272,7 @@ fn a_name_left_is_kept_and_escape_writes_nothing() { harness.key_press(egui::Key::Escape); settle(&mut harness); assert!(names(&harness, "http-node-name").contains(&"Auth".to_owned())); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-rename-input")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-rename-input")).is_none()); } #[test] @@ -342,26 +280,16 @@ fn a_deletion_says_what_goes_with_it_and_cancel_keeps_it() { let mut harness = paiements(); choose(&mut harness, "Paiements", &["http-node-delete"]); - assert_eq!( - text(&harness, "http-delete-count"), - "1 folder and 2 requests go with it." - ); + assert_eq!(text(&harness, "http-delete-count"), "1 folder and 2 requests go with it."); click_id(&mut harness, "http-delete-cancel"); assert_eq!(names(&harness, "http-node-name").len(), 4); focus_row(&mut harness, "POST Login"); harness.key_press(egui::Key::Delete); settle(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-delete-count")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-delete-count")).is_none()); click_id(&mut harness, "http-delete-submit"); - assert_eq!( - names(&harness, "http-node-name"), - ["Paiements", "Auth", "WS Socket"] - ); + assert_eq!(names(&harness, "http-node-name"), ["Paiements", "Auth", "WS Socket"]); } #[test] @@ -383,10 +311,7 @@ fn a_move_with_the_keys_is_made_shown_and_said() { crate::notes::bench::until(&mut harness, "the move is said", |harness| { said(harness) == "Socket is now in Auth." }); - assert_eq!( - names(&harness, "http-node-name"), - ["Paiements", "Auth", "POST Login", "WS Socket"] - ); + assert_eq!(names(&harness, "http-node-name"), ["Paiements", "Auth", "POST Login", "WS Socket"]); assert!( harness .get_by(|node| node.author_id() == Some("http-node-name") @@ -467,13 +392,10 @@ fn a_request_opens_in_its_tab_and_its_row_is_lit() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); - crate::notes::bench::until(&mut harness, "the tab opens", |harness| { - tab_names(harness) == ["POST Login"] - }); + crate::notes::bench::until(&mut harness, "the tab opens", |harness| tab_names(harness) == ["POST Login"]); let lit = harness .get_by(|node| { - node.author_id() == Some("http-node-name") - && node.label().as_deref() == Some("POST Login") + node.author_id() == Some("http-node-name") && node.label().as_deref() == Some("POST Login") }) .accesskit_node() .toggled(); @@ -487,16 +409,7 @@ fn a_request_opens_in_its_tab_and_its_row_is_lit() { click_named(&mut harness, "http-node-name", "WS Socket"); click_named(&mut harness, "http-node-name", "POST Login"); assert_eq!(tab_names(&harness), ["POST Login", "WS Socket"]); - assert_eq!( - harness - .state() - .state - .http - .tabs() - .active() - .map(|tab| tab.draft.name.as_str()), - Some("Login") - ); + assert_eq!(harness.state().state.http.tabs().active().map(|tab| tab.draft.name.as_str()), Some("Login")); } #[test] @@ -506,10 +419,7 @@ fn a_new_request_is_begun_from_the_empty_workspace_and_the_tabs() { click_id(&mut harness, "http-workspace-new-graphql"); click_id(&mut harness, "http-tab-new"); - assert_eq!( - tab_names(&harness), - ["GQL New request, modified", "GET New request, modified"] - ); + assert_eq!(tab_names(&harness), ["GQL New request, modified", "GET New request, modified"]); click_id(&mut harness, "http-tab-new-kind"); click_id(&mut harness, "http-new-kind-websocket"); assert_eq!(tab_names(&harness).len(), 3); @@ -521,21 +431,12 @@ fn a_modified_tab_asks_before_closing_and_a_clean_one_does_not() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); click_named(&mut harness, "http-node-name", "WS Socket"); - crate::notes::bench::until(&mut harness, "two tabs", |harness| { - tab_names(harness).len() == 2 - }); + crate::notes::bench::until(&mut harness, "two tabs", |harness| tab_names(harness).len() == 2); click_named(&mut harness, "http-tab-close", "Close Socket"); assert_eq!(tab_names(&harness), ["POST Login"]); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); harness .state_mut() .state @@ -585,21 +486,12 @@ fn the_middle_button_closes_a_clean_tab_and_asks_for_a_modified_one() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); click_named(&mut harness, "http-node-name", "WS Socket"); - crate::notes::bench::until(&mut harness, "two tabs", |harness| { - tab_names(harness).len() == 2 - }); + crate::notes::bench::until(&mut harness, "two tabs", |harness| tab_names(harness).len() == 2); middle_click_named(&mut harness, "http-tab-open", "WS Socket"); assert_eq!(tab_names(&harness), ["POST Login"]); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); harness .state_mut() .state @@ -608,11 +500,7 @@ fn the_middle_button_closes_a_clean_tab_and_asks_for_a_modified_one() { .edit(&key, |draft| draft.method = HttpMethod::Put); settle(&mut harness); middle_click_named(&mut harness, "http-tab-open", "PUT Login, modified"); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-close-dialog")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-close-dialog")).is_some()); assert_eq!(tab_names(&harness), ["PUT Login, modified"]); click_id(&mut harness, "http-close-discard"); assert!(tab_names(&harness).is_empty()); @@ -622,40 +510,25 @@ fn two_tabs() -> Harness<'static, Bench> { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); click_named(&mut harness, "http-node-name", "WS Socket"); - crate::notes::bench::until(&mut harness, "two tabs", |harness| { - tab_names(harness).len() == 2 - }); + crate::notes::bench::until(&mut harness, "two tabs", |harness| tab_names(harness).len() == 2); harness } fn tab_rect(harness: &Harness<'_, Bench>, name: &str) -> egui::Rect { harness - .get_by(|node| { - node.author_id() == Some("http-tab-open") && node.label().as_deref() == Some(name) - }) + .get_by(|node| node.author_id() == Some("http-tab-open") && node.label().as_deref() == Some(name)) .rect() } /// A press, the pointer moved there in ten steps, a release. -fn drag( - harness: &mut Harness<'_, Bench>, - button: egui::PointerButton, - from: egui::Pos2, - to: egui::Pos2, -) { - let press = |pos, pressed| egui::Event::PointerButton { - pos, - button, - pressed, - modifiers: egui::Modifiers::NONE, - }; +fn drag(harness: &mut Harness<'_, Bench>, button: egui::PointerButton, from: egui::Pos2, to: egui::Pos2) { + let press = + |pos, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }; harness.event(egui::Event::PointerMoved(from)); harness.event(press(from, true)); harness.step(); for step in 1..=10_u8 { - harness.event(egui::Event::PointerMoved( - from + (to - from) * (f32::from(step) / 10.0), - )); + harness.event(egui::Event::PointerMoved(from + (to - from) * (f32::from(step) / 10.0))); harness.step(); } harness.event(press(to, false)); @@ -671,18 +544,7 @@ fn a_tab_dragged_past_another_takes_its_place_and_is_remembered() { drag(&mut harness, egui::PointerButton::Primary, from, to); assert_eq!(tab_names(&harness), ["WS Socket", "POST Login"]); - assert_eq!( - harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .draft - .name, - "Socket" - ); + assert_eq!(harness.state().state.http.tabs().active().unwrap().draft.name, "Socket"); let ids: Vec = harness .state() .state @@ -709,9 +571,7 @@ fn a_dragged_tab_closes_the_hand_and_is_raised_over_the_others() { let accent = crate::theme::palette(&harness.ctx).amber_fill; let mut shapes = harness.output().shapes.iter(); shapes.find_map(|clipped| match &clipped.shape { - egui::Shape::Rect(rect) - if rect.stroke.color == accent && rect.rect.intersects(login) => - { + egui::Shape::Rect(rect) if rect.stroke.color == accent && rect.rect.intersects(login) => { Some(rect.rect) } _ => None, @@ -724,9 +584,7 @@ fn a_dragged_tab_closes_the_hand_and_is_raised_over_the_others() { harness.drag_at(login.center()); harness.run(); - harness.event(egui::Event::PointerMoved( - login.center() + egui::vec2(30.0, 0.0), - )); + harness.event(egui::Event::PointerMoved(login.center() + egui::vec2(30.0, 0.0))); harness.run(); harness.run(); assert_eq!(cursor(&harness), egui::CursorIcon::Grabbing); @@ -777,17 +635,8 @@ fn a_middle_press_that_moves_still_closes_the_tab_and_drags_nothing() { fn ctrl_s_saves_the_tab_in_front_and_the_rail_reads_it_back() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); - crate::notes::bench::until(&mut harness, "the tab opens", |harness| { - tab_names(harness).len() == 1 - }); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); + crate::notes::bench::until(&mut harness, "the tab opens", |harness| tab_names(harness).len() == 1); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); harness .state_mut() .state @@ -808,14 +657,11 @@ fn the_tabs_left_open_are_reopened_and_a_deleted_request_closes_its_tab() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); click_named(&mut harness, "http-node-name", "WS Socket"); - crate::notes::bench::until(&mut harness, "two tabs", |harness| { - tab_names(harness).len() == 2 - }); + crate::notes::bench::until(&mut harness, "two tabs", |harness| tab_names(harness).len() == 2); click_named(&mut harness, "http-tab-open", "POST Login"); let stored = remembered(&harness, crate::state::http::tabs::TABS_KEY).unwrap(); - let mut state = - crate::state::AppState::new(crate::services::preferences::Preferences::default(), true); + let mut state = crate::state::AppState::new(crate::services::preferences::Preferences::default(), true); let mut preferences = crate::services::preferences::Preferences::default(); preferences.set(crate::state::http::tabs::TABS_KEY, &stored); state.http.restore(&preferences); @@ -823,16 +669,7 @@ fn the_tabs_left_open_are_reopened_and_a_deleted_request_closes_its_tab() { crate::notes::bench::until(&mut harness, "the tabs are reopened", |harness| { tab_names(harness) == ["POST Login", "WS Socket"] }); - assert_eq!( - harness - .state() - .state - .http - .tabs() - .active() - .map(|tab| tab.draft.name.as_str()), - Some("Login") - ); + assert_eq!(harness.state().state.http.tabs().active().map(|tab| tab.draft.name.as_str()), Some("Login")); choose(&mut harness, "Socket", &["http-node-delete"]); click_id(&mut harness, "http-delete-submit"); @@ -845,17 +682,8 @@ fn the_tabs_left_open_are_reopened_and_a_deleted_request_closes_its_tab() { fn a_deletion_names_the_open_tabs_it_would_lose() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); - crate::notes::bench::until(&mut harness, "the tab opens", |harness| { - tab_names(harness).len() == 1 - }); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); + crate::notes::bench::until(&mut harness, "the tab opens", |harness| tab_names(harness).len() == 1); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); harness .state_mut() .state @@ -875,9 +703,7 @@ pub(crate) fn editing() -> Harness<'static, Bench> { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "POST Login"); crate::notes::bench::until(&mut harness, "the editor is open", |harness| { - harness - .query_by(|node| node.author_id() == Some("http-url")) - .is_some() + harness.query_by(|node| node.author_id() == Some("http-url")).is_some() }); harness } @@ -891,15 +717,7 @@ pub(crate) fn values(harness: &Harness<'_, Bench>, author_id: &str) -> Vec) -> crate::state::http::tabs::Draft { - harness - .state() - .state - .http - .tabs() - .active() - .unwrap() - .draft - .clone() + harness.state().state.http.tabs().active().unwrap().draft.clone() } fn type_into(harness: &mut Harness<'_, Bench>, author_id: &str, nth: usize, words: &str) { @@ -923,10 +741,7 @@ fn the_url_and_the_parameters_follow_each_other() { type_into(&mut harness, "http-url", 0, "?page=2&q=x"); let draft = active(&harness); - assert_eq!( - draft.document.url, - "https://api.example.com/Login?page=2&q=x" - ); + assert_eq!(draft.document.url, "https://api.example.com/Login?page=2&q=x"); assert_eq!(values(&harness, "http-kv-key"), ["page", "q", ""]); harness @@ -935,10 +750,7 @@ fn the_url_and_the_parameters_follow_each_other() { .unwrap() .click(); settle(&mut harness); - assert_eq!( - active(&harness).document.url, - "https://api.example.com/Login?q=x" - ); + assert_eq!(active(&harness).document.url, "https://api.example.com/Login?q=x"); assert!(names(&harness, "http-tab-open")[0].ends_with("modified")); } @@ -959,11 +771,7 @@ fn a_header_typed_with_its_value_is_split_and_a_bad_name_is_said() { assert_eq!(headers[0].value, "application/json"); type_into(&mut harness, "http-kv-key", 1, "X Trace"); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-kv-fault")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-kv-fault")).is_some()); } /// The headers sent unasked stand in their own block above the table: their values in one @@ -972,42 +780,22 @@ fn a_header_typed_with_its_value_is_split_and_a_bad_name_is_said() { fn the_headers_sent_unasked_are_a_block_of_two_columns_above_the_table() { let mut harness = editing(); click_id(&mut harness, "http-section-headers"); - let tab = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); - harness - .state_mut() - .state - .http - .tabs_mut() - .edit(&tab, |draft| { - draft.apply(crate::state::http::tabs::DraftEdit::Body( - engine::http::model::RequestBody::Json { - text: "{}".to_owned(), - }, - )); - }); + let tab = harness.state().state.http.tabs().active_key().unwrap().to_owned(); + harness.state_mut().state.http.tabs_mut().edit(&tab, |draft| { + draft.apply(crate::state::http::tabs::DraftEdit::Body(engine::http::model::RequestBody::Json { + text: "{}".to_owned(), + })); + }); settle(&mut harness); click_id(&mut harness, "http-section-headers"); - let block = harness - .get_by(|node| node.author_id() == Some("http-implied-headers")) - .rect(); + let block = harness.get_by(|node| node.author_id() == Some("http-implied-headers")).rect(); let values: Vec = harness .query_all_by(|node| node.author_id() == Some("http-implied-value")) .map(|node| node.rect()) .collect(); assert!(values.len() >= 2, "{values:?}"); - assert!( - values - .iter() - .all(|value| (value.left() - values[0].left()).abs() < 0.5) - ); + assert!(values.iter().all(|value| (value.left() - values[0].left()).abs() < 0.5)); let table = harness .get_all_by(|node| node.author_id() == Some("http-kv-key")) .next() @@ -1030,12 +818,7 @@ fn lines_pasted_in_a_name_fill_a_row_each() { harness.event(egui::Event::Paste("Accept: */*\nX-Trace: on\n".to_owned())); settle(&mut harness); - let keys: Vec = active(&harness) - .document - .headers - .iter() - .map(|row| row.key.clone()) - .collect(); + let keys: Vec = active(&harness).document.headers.iter().map(|row| row.key.clone()).collect(); assert_eq!(keys, ["Accept", "X-Trace"]); } @@ -1044,16 +827,10 @@ fn a_kind_is_said_where_a_method_would_be_chosen() { let mut harness = paiements(); click_named(&mut harness, "http-node-name", "WS Socket"); crate::notes::bench::until(&mut harness, "the editor is open", |harness| { - harness - .query_by(|node| node.author_id() == Some("http-kind-badge")) - .is_some() + harness.query_by(|node| node.author_id() == Some("http-kind-badge")).is_some() }); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-method")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-method")).is_none()); assert!( harness .query_by(|node| node.author_id() == Some("http-section-params")) @@ -1066,11 +843,7 @@ fn a_variable_is_listed_with_where_it_resolves_from() { let mut harness = editing(); type_into(&mut harness, "http-url", 0, "/{{token}}"); - eprintln!( - "URL {:?} USED {:?}", - active(&harness).document.url, - harness.state().state.http.used().len() - ); + eprintln!("URL {:?} USED {:?}", active(&harness).document.url, harness.state().state.http.used().len()); crate::notes::bench::until(&mut harness, "the variable is listed", |harness| { harness @@ -1100,17 +873,13 @@ pub(crate) fn sending_to(path: &str) -> Harness<'static, Bench> { ..RequestDocument::default() }, }; - engine::db::run_here(backend.engine(), move |engine| { - engine::http::create_http_request(engine, &draft) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::http::create_http_request(engine, &draft)) + .unwrap(); let mut harness = area_of(Area::Http, backend, profile); harness.set_size(egui::vec2(1_100.0, 900.0)); click_named(&mut harness, "http-node-name", "GET Ping"); crate::notes::bench::until(&mut harness, "the editor is open", |harness| { - harness - .query_by(|node| node.author_id() == Some("http-send")) - .is_some() + harness.query_by(|node| node.author_id() == Some("http-send")).is_some() }); harness } @@ -1141,30 +910,19 @@ fn a_request_is_sent_and_its_answer_read_part_by_part() { click_id(&mut harness, "http-send"); answered(&mut harness); - assert_eq!( - said_by(&harness, "http-response-status").as_deref(), - Some("200 OK") - ); + assert_eq!(said_by(&harness, "http-response-status").as_deref(), Some("200 OK")); assert!(said_by(&harness, "http-response-time").is_some_and(|time| time.ends_with("ms"))); assert!(said_by(&harness, "http-response-pretty").is_some_and(|body| body.contains("\"Ada\""))); click_id(&mut harness, "http-response-view-1"); - assert!( - said_by(&harness, "http-response-body").is_some_and(|body| body.starts_with("{\"name\"")) - ); + assert!(said_by(&harness, "http-response-body").is_some_and(|body| body.starts_with("{\"name\""))); click_id(&mut harness, "http-response-section-cookies"); - assert_eq!( - said_by(&harness, "http-response-cookie").as_deref(), - Some("session") - ); + assert_eq!(said_by(&harness, "http-response-cookie").as_deref(), Some("session")); click_id(&mut harness, "http-response-section-timeline"); assert!( - said_by(&harness, "http-response-sent") - .is_some_and(|sent| sent.starts_with("GET http://127.0.0.1")) - ); - assert!( - said_by(&harness, "http-response-received").is_some_and(|got| got.starts_with("200 OK")) + said_by(&harness, "http-response-sent").is_some_and(|sent| sent.starts_with("GET http://127.0.0.1")) ); + assert!(said_by(&harness, "http-response-received").is_some_and(|got| got.starts_with("200 OK"))); click_id(&mut harness, "http-response-clear"); assert!( @@ -1184,10 +942,7 @@ fn a_json_answer_is_explored_as_a_tree() { crate::notes::bench::until(&mut harness, "the tree is drawn", |harness| { harness - .query_all_by(|node| { - node.label() - .is_some_and(|label| label.contains("languages")) - }) + .query_all_by(|node| node.label().is_some_and(|label| label.contains("languages"))) .count() > 0 }); @@ -1198,9 +953,7 @@ fn a_send_under_way_counts_its_time_and_can_be_cancelled() { let mut harness = sending_to("/slow"); // Not settled: settling waits for the core, and the send with it. - harness - .get_by(|node| node.author_id() == Some("http-send")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-send")).click(); harness.step(); harness.step(); assert!( @@ -1213,9 +966,7 @@ fn a_send_under_way_counts_its_time_and_can_be_cancelled() { assert!(http.sends().is_sending(http.tabs().active_key().unwrap())); // A cancel that arrives before the send has left cancels nothing: it reaches the server first. let url = active(&harness).document.url; - let port: u16 = url["http://127.0.0.1:".len()..url.rfind('/').unwrap()] - .parse() - .unwrap(); + let port: u16 = url["http://127.0.0.1:".len()..url.rfind('/').unwrap()].parse().unwrap(); for _ in 0..10_000 { if testing::slow_arrived(port) { break; @@ -1224,9 +975,7 @@ fn a_send_under_way_counts_its_time_and_can_be_cancelled() { } assert!(testing::slow_arrived(port), "the send reached the server"); - harness - .get_by(|node| node.author_id() == Some("http-send")) - .click(); + harness.get_by(|node| node.author_id() == Some("http-send")).click(); harness.step(); harness.step(); crate::notes::bench::until(&mut harness, "the send is cancelled", |harness| { @@ -1241,29 +990,12 @@ fn a_status_says_its_family_and_a_failure_says_why() { let mut harness = sending_to("/missing"); click_id(&mut harness, "http-send"); answered(&mut harness); - assert_eq!( - said_by(&harness, "http-response-status").as_deref(), - Some("404 Not Found") - ); + assert_eq!(said_by(&harness, "http-response-status").as_deref(), Some("404 Not Found")); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); - harness - .state_mut() - .state - .http - .tabs_mut() - .edit(&key, |draft| { - draft.apply(crate::state::http::tabs::DraftEdit::Url( - "http://127.0.0.1:1/".to_owned(), - )); - }); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); + harness.state_mut().state.http.tabs_mut().edit(&key, |draft| { + draft.apply(crate::state::http::tabs::DraftEdit::Url("http://127.0.0.1:1/".to_owned())); + }); settle(&mut harness); click_id(&mut harness, "http-send"); crate::notes::bench::until(&mut harness, "the failure is said", |harness| { @@ -1273,15 +1005,30 @@ fn a_status_says_its_family_and_a_failure_says_why() { }); } +#[test] +fn every_arrow_moves_the_edge_between_the_request_and_its_answer() { + let mut harness = sending_to("/json"); + harness.state_mut().state.settings.http_request_share = 300; + settle(&mut harness); + harness.get_by(|node| node.author_id() == Some("http-split-handle")).focus(); + settle(&mut harness); + let mut shares = Vec::new(); + for _ in 0..3 { + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + shares.push(harness.state().state.settings.http_request_share); + } + + assert!(shares.is_sorted_by(|a, b| a < b), "{shares:?}"); +} + #[test] fn the_line_between_request_and_answer_is_left_automatic_on_a_double_click() { let mut harness = sending_to("/json"); harness.state_mut().state.settings.http_request_share = 500; settle(&mut harness); - harness - .get_by(|node| node.author_id() == Some("http-split-handle")) - .focus(); + harness.get_by(|node| node.author_id() == Some("http-split-handle")).focus(); settle(&mut harness); harness.key_press(egui::Key::Enter); settle(&mut harness); @@ -1321,10 +1068,7 @@ fn http_body_budget() { frames.push(started.elapsed()); } frames.sort(); - println!( - "scrolling p50 {:?}, p95 {:?}, p99 {:?}", - frames[100], frames[190], frames[198] - ); + println!("scrolling p50 {:?}, p95 {:?}, p99 {:?}", frames[100], frames[190], frames[198]); } #[test] @@ -1332,10 +1076,7 @@ fn the_headers_and_a_redirect_followed_are_read_from_the_answer() { let mut harness = sending_to("/redirect"); click_id(&mut harness, "http-send"); answered(&mut harness); - assert_eq!( - said_by(&harness, "http-response-status").as_deref(), - Some("200 OK") - ); + assert_eq!(said_by(&harness, "http-response-status").as_deref(), Some("200 OK")); click_id(&mut harness, "http-response-section-headers"); assert!( @@ -1344,33 +1085,18 @@ fn the_headers_and_a_redirect_followed_are_read_from_the_answer() { .is_some() ); click_id(&mut harness, "http-response-section-timeline"); - assert!( - said_by(&harness, "http-response-redirect").is_some_and(|line| line.starts_with("302")) - ); + assert!(said_by(&harness, "http-response-redirect").is_some_and(|line| line.starts_with("302"))); } #[test] fn a_body_sent_is_shown_in_the_timeline() { let mut harness = sending_to("/json"); - let key = harness - .state() - .state - .http - .tabs() - .active_key() - .unwrap() - .to_owned(); - harness - .state_mut() - .state - .http - .tabs_mut() - .edit(&key, |draft| { - draft.method = HttpMethod::Post; - draft.document.body = engine::http::model::RequestBody::Json { - text: r#"{"login":"ada"}"#.to_owned(), - }; - }); + let key = harness.state().state.http.tabs().active_key().unwrap().to_owned(); + harness.state_mut().state.http.tabs_mut().edit(&key, |draft| { + draft.method = HttpMethod::Post; + draft.document.body = + engine::http::model::RequestBody::Json { text: r#"{"login":"ada"}"#.to_owned() }; + }); settle(&mut harness); click_id(&mut harness, "http-send"); answered(&mut harness); @@ -1401,9 +1127,5 @@ fn a_wide_rail_names_what_its_head_makes() { click_id(&mut harness, "http-collection-create-open"); - assert!( - harness - .query_by(|node| node.author_id() == Some("http-create-input")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("http-create-input")).is_some()); } diff --git a/crates/ui/src/http/variables_table.rs b/crates/ui/src/http/variables_table.rs index b33b3a221..042425f12 100644 --- a/crates/ui/src/http/variables_table.rs +++ b/crates/ui/src/http/variables_table.rs @@ -96,8 +96,7 @@ pub(crate) fn show( for at in 0..=rows.len() { #[expect(clippy::cast_precision_loss, reason = "rows of a table")] let top = frame.top() + (at + 1) as f32 * ROW; - ui.painter() - .hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(frame.x_range(), top + 0.5, Stroke::new(1.0, p.line_soft)); let cell = Cell { id: id.with(at), top, @@ -148,36 +147,18 @@ fn row_of( let tr = |key| i18n::translate(language, key, &[]); let mut changed = false; if !cell.blank { - let label = i18n::translate( - language, - keys::http::table::ENABLE, - &[("key", row.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::http::table::ENABLE, &[("key", row.name.as_str().into())]); let rect = Columns::at(columns.check, cell.top); changed |= table::tick(ui, rect, &mut row.enabled, &label, "http-variable-enabled"); } - let ink = if row.enabled || cell.blank { - p.text_0 - } else { - p.text_2 - }; - let faulty_name = matches!( - cell.fault, - Some(VariableFault::Name | VariableFault::Duplicate) - ); - let hint = if cell.blank { - tr(keys::http::variables::NEW_NAME) - } else { - String::new() - }; + let ink = if row.enabled || cell.blank { p.text_0 } else { p.text_2 }; + let faulty_name = matches!(cell.fault, Some(VariableFault::Name | VariableFault::Duplicate)); + let hint = if cell.blank { tr(keys::http::variables::NEW_NAME) } else { String::new() }; changed |= table::text_cell( ui, (Columns::at(columns.name, cell.top), cell.id.with("name")), - ( - &mut row.name, - &tr(keys::http::variables::NAME), - "http-variable-name", - ), + (&mut row.name, &tr(keys::http::variables::NAME), "http-variable-name"), (&hint, if faulty_name { p.red } else { ink }, true, false), ) .changed(); @@ -185,9 +166,7 @@ fn row_of( let hidden = secret && !revealed.contains(&cell.at); let mut value_rect = Columns::at(columns.value, cell.top); if secret { - let eye = value_rect - .split_left_right_at_x(value_rect.right() - 28.0) - .1; + let eye = value_rect.split_left_right_at_x(value_rect.right() - 28.0).1; value_rect.set_right(eye.left()); reveal(ui, eye, (&row.name, cell.at), revealed, language); } @@ -200,11 +179,7 @@ fn row_of( changed |= table::text_cell( ui, (value_rect, cell.id.with("value")), - ( - &mut row.value, - &tr(keys::http::variables::VALUE), - "http-variable-value", - ), + (&mut row.value, &tr(keys::http::variables::VALUE), "http-variable-value"), ("", if faulty_value { p.red } else { ink }, true, hidden), ) .changed(); @@ -239,11 +214,8 @@ fn reveal( /// « filled by Login », at the end of the value: a click opens that request. `true` on a click. fn filled_by(ui: &mut Ui, value: &mut Rect, filled: &FilledBy, language: i18n::Language) -> bool { - let label = i18n::translate( - language, - keys::http::variables::FILLED_BY, - &[("name", filled.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::http::variables::FILLED_BY, &[("name", filled.name.as_str().into())]); let width = Button::width(ui, &label); let rect = Rect::from_min_max(pos2(value.right() - width, value.top()), value.max); value.set_right(rect.left()); @@ -273,17 +245,10 @@ fn kind_cell( (VariableKind::Number, names[1].as_str()), (VariableKind::Secret, names[2].as_str()), ]; - let label = i18n::translate( - language, - keys::http::variables::KIND_OF, - &[("name", row.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::http::variables::KIND_OF, &[("name", row.name.as_str().into())]); let rect = Columns::at(columns.kind, cell.top).shrink2(Vec2::new(8.0, 4.0)); - let mut over = ui.new_child( - UiBuilder::new() - .scope_id(cell.id.with("kind")) - .max_rect(rect), - ); + let mut over = ui.new_child(UiBuilder::new().scope_id(cell.id.with("kind")).max_rect(rect)); ChoiceMenu::new(&label, "http-variable-kind", &options) .show(&mut over, &mut row.kind) .changed() @@ -294,10 +259,7 @@ fn said(ui: &mut Ui, faults: &[Option], language: i18n::Language) let p = palette(ui.ctx()); for (fault, key) in [ (VariableFault::Name, keys::http::variables::faults::NAME), - ( - VariableFault::Duplicate, - keys::http::variables::faults::DUPLICATE, - ), + (VariableFault::Duplicate, keys::http::variables::faults::DUPLICATE), (VariableFault::Number, keys::http::variables::faults::NUMBER), ] { if !faults.contains(&Some(fault)) { @@ -310,3 +272,6 @@ fn said(ui: &mut Ui, faults: &[Option], language: i18n::Language) widgets::address(ui, &shown, "http-variable-fault"); } } + +#[cfg(test)] +mod tests; diff --git a/crates/ui/src/http/variables_table/tests.rs b/crates/ui/src/http/variables_table/tests.rs new file mode 100644 index 000000000..111e1e4de --- /dev/null +++ b/crates/ui/src/http/variables_table/tests.rs @@ -0,0 +1,34 @@ +//! What an edit of the table makes of its rows. + +use super::*; + +fn row(name: &str) -> Variable { + Variable { name: name.to_owned(), ..Variable::default() } +} + +fn names(changed: Changed) -> Vec { + match changed { + Changed::Rows(rows) => rows.into_iter().map(|row| row.name).collect(), + Changed::Filler(filler) => vec![format!("filled by {}", filler.name)], + } +} + +#[test] +fn an_edit_lands_on_its_row_and_the_blank_one_becomes_a_row() { + let rows = [row("a"), row("b")]; + for (at, edited, after) in [ + (0, Row::Edited(row("x")), vec!["x", "b"]), + (2, Row::Edited(row("x")), vec!["a", "b", "x"]), + (1, Row::Removed, vec!["a"]), + ] { + assert_eq!(names(applied(&rows, at, edited, &mut Revealed::default())), after); + } +} + +#[test] +fn the_request_that_filled_a_row_is_answered_as_such() { + let filler = FilledBy { request_id: Some("id".to_owned()), name: "Login".to_owned() }; + let changed = applied(&[row("a")], 0, Row::Filler(filler), &mut Revealed::default()); + + assert_eq!(names(changed), ["filled by Login"]); +} diff --git a/crates/ui/src/inputs.rs b/crates/ui/src/inputs.rs index f503fe94d..6635f5c90 100644 --- a/crates/ui/src/inputs.rs +++ b/crates/ui/src/inputs.rs @@ -58,10 +58,7 @@ impl EventSink for Inbox { pub fn channel() -> (Inbox, Waker, Receiver) { let (sender, receiver) = crossbeam_channel::unbounded(); let waker = Waker::default(); - let inbox = Inbox { - sender, - waker: waker.clone(), - }; + let inbox = Inbox { sender, waker: waker.clone() }; (inbox, waker, receiver) } @@ -77,10 +74,7 @@ mod tests { inbox.emit(EngineEvent::IndexReady); - assert!(matches!( - inputs.try_recv(), - Ok(Input::Engine(EngineEvent::IndexReady)) - )); + assert!(matches!(inputs.try_recv(), Ok(Input::Engine(EngineEvent::IndexReady)))); assert!(ctx.has_requested_repaint()); } diff --git a/crates/ui/src/keys.rs b/crates/ui/src/keys.rs index 21149a821..09ee2aa13 100644 --- a/crates/ui/src/keys.rs +++ b/crates/ui/src/keys.rs @@ -139,8 +139,6 @@ const fn area(key: Key, area: Area) -> Binding { } } -/// The first binding of `levels`, top level first, that a key pressed this frame and left by -/// the widgets matches. The key is consumed. /// Who reads what the widgets left of the keys, on what is on screen: the one answer the window /// and the tests' bench both ask. A modal takes the keys, and what is under it hears none; the /// palette lets the application's through. A modal the stack does not know of (one held in a @@ -150,8 +148,7 @@ pub fn read(state: &crate::state::AppState, ctx: &Context) -> Option { let bindings = &state.settings.bindings; let canvas = crate::notes::canvas::shortcuts::bound_to(bindings); let rail = [rail(bindings)]; - let modal = - state.dialogs.top().is_some() || ctx.memory(egui::Memory::top_modal_layer).is_some(); + let modal = state.dialogs.top().is_some() || ctx.memory(egui::Memory::top_modal_layer).is_some(); let levels: &[&[Binding]] = if state.palette.is_open() { &[&APPLICATION] } else if modal { @@ -170,6 +167,8 @@ pub fn read(state: &crate::state::AppState, ctx: &Context) -> Option { dispatch(ctx, levels) } +/// The first binding of `levels`, top level first, that a key pressed this frame and left by +/// the widgets matches. The key is consumed. pub fn dispatch(ctx: &Context, levels: &[&[Binding]]) -> Option { if composing(ctx) { return None; @@ -178,14 +177,7 @@ pub fn dispatch(ctx: &Context, levels: &[&[Binding]]) -> Option { let typing = ctx.output(|output| output.ime.is_some()); ctx.input_mut(|input| { let (at, action) = input.events.iter().enumerate().find_map(|(at, event)| { - let Event::Key { - key, - physical_key, - pressed: true, - modifiers, - .. - } = event - else { + let Event::Key { key, physical_key, pressed: true, modifiers, .. } = event else { return None; }; levels @@ -227,13 +219,7 @@ mod tests { use crate::action::GlobalAction; fn key(key: Key, physical: Key, modifiers: Modifiers) -> Event { - Event::Key { - key, - physical_key: Some(physical), - pressed: true, - repeat: false, - modifiers, - } + Event::Key { key, physical_key: Some(physical), pressed: true, repeat: false, modifiers } } fn escape(action: GlobalAction) -> Binding { @@ -260,28 +246,18 @@ mod tests { if frame.field { let mut text = String::new(); let label = ui.label("Search"); - ui.text_edit_singleline(&mut text) - .labelled_by(label.id) - .request_focus(); + ui.text_edit_singleline(&mut text).labelled_by(label.id).request_focus(); } for event in frame.events.drain(..) { ui.ctx().input_mut(|input| input.events.push(event)); } let modal = [escape(GlobalAction::Quit)]; let area = [escape(GlobalAction::NewNote)]; - let levels: Vec<&[Binding]> = if frame.modal { - vec![&modal, &area, &APPLICATION] - } else { - vec![&area, &APPLICATION] - }; + let levels: Vec<&[Binding]> = + if frame.modal { vec![&modal, &area, &APPLICATION] } else { vec![&area, &APPLICATION] }; frame.heard = frame.heard.take().or(dispatch(ui.ctx(), &levels)); }, - Frame { - events: Vec::new(), - field, - modal, - heard: None, - }, + Frame { events: Vec::new(), field, modal, heard: None }, ); harness.run(); harness.state_mut().events = events; @@ -293,14 +269,8 @@ mod tests { fn escape_goes_to_the_modal_before_the_area() { let pressed = || vec![key(Key::Escape, Key::Escape, Modifiers::NONE)]; - assert_eq!( - run(pressed(), false, true), - Some(Action::Global(GlobalAction::Quit)) - ); - assert_eq!( - run(pressed(), false, false), - Some(Action::Global(GlobalAction::NewNote)) - ); + assert_eq!(run(pressed(), false, true), Some(Action::Global(GlobalAction::Quit))); + assert_eq!(run(pressed(), false, false), Some(Action::Global(GlobalAction::NewNote))); } #[test] @@ -308,10 +278,7 @@ mod tests { // AZERTY: the key at the place of « 1 » types « & », which egui names after its place. let ampersand = key(Key::Num1, Key::Num1, Modifiers::COMMAND); - assert_eq!( - run(vec![ampersand], false, false), - Some(Action::App(AppAction::ShowArea(Area::Notes))) - ); + assert_eq!(run(vec![ampersand], false, false), Some(Action::App(AppAction::ShowArea(Area::Notes)))); } #[test] @@ -320,10 +287,7 @@ mod tests { let tools = || vec![key(Key::Num2, Key::Num2, Modifiers::COMMAND)]; assert_eq!(run(escape(), true, false), None); - assert_eq!( - run(tools(), true, false), - Some(Action::App(AppAction::ShowArea(Area::Tools))) - ); + assert_eq!(run(tools(), true, false), Some(Action::App(AppAction::ShowArea(Area::Tools)))); } #[test] @@ -336,10 +300,7 @@ mod tests { #[test] fn a_composition_keeps_its_keys() { let events = vec![ - Event::Ime(ImeEvent::Preedit { - text: "か".to_string(), - active_range_chars: None, - }), + Event::Ime(ImeEvent::Preedit { text: "か".to_string(), active_range_chars: None }), key(Key::Escape, Key::Escape, Modifiers::NONE), ]; @@ -350,9 +311,7 @@ mod tests { fn a_key_taken_is_consumed() { let ctx = Context::default(); let mut input = egui::RawInput::default(); - input - .events - .push(key(Key::Escape, Key::Escape, Modifiers::NONE)); + input.events.push(key(Key::Escape, Key::Escape, Modifiers::NONE)); let area = [escape(GlobalAction::NewNote)]; let mut output = ctx.run_ui(input, |ui| { assert!(dispatch(ui.ctx(), &[&area]).is_some()); @@ -360,4 +319,153 @@ mod tests { }); output.textures_delta.clear(); } + + /// What `read` answers to a keystroke, on the state given. + fn heard(state: &crate::state::AppState, pressed: Event) -> Option { + let ctx = Context::default(); + let mut input = egui::RawInput::default(); + input.events.push(pressed); + let mut answer = None; + let mut output = ctx.run_ui(input, |ui| answer = read(state, ui.ctx())); + output.textures_delta.clear(); + answer + } + + fn unlocked() -> crate::state::held::Held { + crate::state::held::held(crate::testing::unlocked()) + } + + fn ctrl(letter: Key) -> Event { + key(letter, letter, Modifiers::COMMAND) + } + + fn bare(letter: Key) -> Event { + key(letter, letter, Modifiers::NONE) + } + + const ELSEWHERE: Action = Action::App(AppAction::ShowArea(Area::Tools)); + + #[test] + fn each_area_hears_its_own_keys_and_the_application_s() { + let mut held = unlocked(); + for (area, pressed, answer) in [ + (Area::Notes, ctrl(Key::K), Some(NOTES[0].action.clone())), + (Area::Tools, ctrl(Key::K), Some(TOOLS[0].action.clone())), + (Area::Http, ctrl(Key::K), None), + (Area::Http, ctrl(Key::S), Some(HTTP[0].action.clone())), + (Area::Http, ctrl(Key::Enter), Some(HTTP[1].action.clone())), + (Area::Notes, ctrl(Key::S), None), + (Area::Tools, ctrl(Key::Enter), None), + ] { + held.state.settings.area = area; + assert_eq!(heard(&held.state, pressed), answer, "{area:?}"); + assert_eq!(heard(&held.state, ctrl(Key::Num2)), Some(ELSEWHERE), "{area:?}"); + assert_eq!( + heard(&held.state, ctrl(Key::B)), + Some(Action::App(AppAction::ToggleRail)), + "{area:?}" + ); + } + } + + #[test] + fn before_the_library_is_open_only_the_application_hears() { + let state = crate::state::AppState::new(crate::services::preferences::Preferences::default(), true); + + assert_eq!(heard(&state, ctrl(Key::K)), None); + assert_eq!(heard(&state, ctrl(Key::B)), None); + assert_eq!(heard(&state, ctrl(Key::Num2)), Some(ELSEWHERE)); + } + + #[test] + fn a_modal_keeps_the_keys_from_all_that_is_under_it() { + let mut held = unlocked(); + held.state + .dialogs + .open(crate::widgets::Layer::App, egui::Id::unique("a-modal"), None); + + for pressed in [ctrl(Key::K), ctrl(Key::Num2), bare(Key::J)] { + assert_eq!(heard(&held.state, pressed), None); + } + } + + /// A modal held in a view: the stack does not know of it, egui does. + #[test] + fn a_modal_only_egui_knows_of_keeps_the_keys_too() { + let held = unlocked(); + let ctx = Context::default(); + let mut answers = Vec::new(); + for pass in 0..2 { + let mut input = egui::RawInput::default(); + input.events.push(ctrl(Key::Num2)); + let mut output = ctx.run_ui(input, |ui| { + if pass == 1 { + answers.push(read(&held.state, ui.ctx())); + } + egui::Modal::new(egui::Id::unique("in-a-view")).show(ui.ctx(), |ui| ui.label("kept")); + }); + output.textures_delta.clear(); + } + assert_eq!(answers, [None]); + } + + #[test] + fn the_palette_lets_the_application_s_keys_through() { + let mut held = unlocked(); + held.state.palette.open(&held.backend, false); + held.settle(); + + assert_eq!(heard(&held.state, ctrl(Key::Num2)), Some(ELSEWHERE)); + assert_eq!(heard(&held.state, ctrl(Key::K)), None); + } + + /// The canvas's keys are the cards'; with a note open, J and K are the note's. + #[test] + fn the_canvas_hears_its_keys_until_a_note_is_open() { + let (backend, profile) = crate::testing::unlocked(); + let id = crate::testing::note(&backend, "psql").id.clone(); + let mut held = crate::state::held::held((backend, profile)); + let pin = + Action::Notes(crate::notes::Action::Canvas(crate::notes::canvas::shortcuts::CanvasKey::Pin)); + assert_eq!(heard(&held.state, bare(Key::P)), Some(pin)); + assert_eq!(heard(&held.state, bare(Key::J)), None); + + held.notes(crate::notes::Action::OpenNote(id)); + assert!(held.state.editor.is_open()); + assert_eq!(heard(&held.state, bare(Key::P)), None); + assert_eq!(heard(&held.state, bare(Key::J)), Some(EDITOR[0].action.clone())); + + held.notes(crate::notes::Action::Trash(crate::notes::Trash::Open)); + assert_eq!(heard(&held.state, bare(Key::J)), None, "the trash is over the note"); + assert_eq!(heard(&held.state, ctrl(Key::K)), None); + } + + #[test] + fn the_rail_answers_on_the_key_it_was_moved_to() { + let mut held = unlocked(); + held.state + .settings + .bindings + .set(crate::services::shortcuts::RAIL_ACTION, "Ctrl+L".to_owned()); + + assert_eq!(heard(&held.state, ctrl(Key::L)), Some(Action::App(AppAction::ToggleRail))); + assert_eq!(heard(&held.state, ctrl(Key::B)), None); + } + + #[test] + fn a_composition_ended_gives_the_keys_back() { + let ime = + |text: &str| Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None }); + let area = [escape(GlobalAction::NewNote)]; + let ctx = Context::default(); + let mut answers = Vec::new(); + for events in [vec![ime("か")], vec![bare(Key::Escape)], vec![ime("")], vec![bare(Key::Escape)]] { + let input = egui::RawInput { events, ..Default::default() }; + let mut output = ctx.run_ui(input, |ui| { + answers.push(dispatch(ui.ctx(), &[&area]).is_some()); + }); + output.textures_delta.clear(); + } + assert_eq!(answers, [false, false, false, true]); + } } diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 439c52b3d..e300f9911 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -1,24 +1,33 @@ //! The egui interface of DevNotes: the application frame, its state and its screens. It //! calls the core directly, in the same process. -pub mod action; -pub mod api; +// The modules are private, so that rustc reports what nothing in the crate uses any more. +#![allow(unreachable_pub, reason = "`pub` inside the crate says: for its other modules")] + +mod action; +mod api; mod app; -pub mod backend; +mod backend; mod banners; -pub mod gate; -pub mod http; -pub mod inputs; -pub mod keys; -pub mod notes; -pub mod palette; -pub mod services; -pub mod state; +mod gate; +mod http; +mod inputs; +mod keys; +mod notes; +mod palette; +mod services; +mod state; #[cfg(test)] mod testing; -pub mod theme; +mod theme; mod titlebar; -pub mod tools; -pub mod widgets; +mod tools; +mod widgets; pub use app::{Desktop, DevNotesApp, Startup}; +pub use inputs::{Inbox, Input, channel}; +pub use services::errors::ErrorNotifier; +pub use services::global_keys::described as global_keys; +pub use services::preferences::Preferences; +pub use services::settings::Settings; +pub use services::tray::labels as tray_labels; diff --git a/crates/ui/src/notes/bench.rs b/crates/ui/src/notes/bench.rs index 8b1b826a8..1b2a0aec7 100644 --- a/crates/ui/src/notes/bench.rs +++ b/crates/ui/src/notes/bench.rs @@ -25,10 +25,7 @@ pub(crate) fn area(backend: Backend, profile: tempfile::TempDir) -> Harness<'sta /// The notes area with the editor expanded over it: what a test of the editor's own content /// draws, as wide as a person would give it. -pub(crate) fn expanded_area( - backend: Backend, - profile: tempfile::TempDir, -) -> Harness<'static, Bench> { +pub(crate) fn expanded_area(backend: Backend, profile: tempfile::TempDir) -> Harness<'static, Bench> { let mut harness = area(backend, profile); harness.state_mut().state.settings.editor_fullscreen = true; // The header stays above an expanded note: the room it takes is given back below. @@ -36,73 +33,61 @@ pub(crate) fn expanded_area( harness } -pub(crate) fn area_of( - shown: Area, - backend: Backend, - profile: tempfile::TempDir, -) -> Harness<'static, Bench> { +pub(crate) fn area_of(shown: Area, backend: Backend, profile: tempfile::TempDir) -> Harness<'static, Bench> { let mut state = AppState::new(Preferences::default(), true); state.language = i18n::Language::En; state.settings.area = shown; // Unlocked already: the gate learns it as the window's does, and stays open. state.gate.ask(&backend); - let mut harness = testing::harness() - .with_size(vec2(1_100.0, 700.0)) - .build_ui_state( - |ui, bench: &mut Bench| { - crate::theme::motion::set_reduced(ui.ctx(), true); - let ctx = ui.ctx().clone(); - let state = &mut bench.state; - state - .gate - .update(&bench.backend, &mut state.status, &mut state.errors); - bench.state.update_library(&ctx, &bench.backend); - let mut actions = Actions::default(); - if bench.state.settings.area == Area::Http { - let mut view = std::mem::take(&mut bench.state.http_view); - crate::http::show(ui, &bench.state, &mut view, &mut actions); - crate::http::leave::show(ui, &bench.state, &mut view, &mut actions); - bench.state.http_view = view; - if let Some(action) = crate::keys::read(&bench.state, &ctx) { - actions.push(action); - } - for action in actions.drain().collect::>() { - bench.state.apply(action, &ctx, &bench.backend); - } - return; + let mut harness = testing::harness().with_size(vec2(1_100.0, 700.0)).build_ui_state( + |ui, bench: &mut Bench| { + crate::theme::motion::set_reduced(ui.ctx(), true); + let ctx = ui.ctx().clone(); + let state = &mut bench.state; + state.gate.update(&bench.backend, &mut state.status, &mut state.errors); + bench.state.update_library(&ctx, &bench.backend); + let mut actions = Actions::default(); + if bench.state.settings.area == Area::Http { + let mut view = std::mem::take(&mut bench.state.http_view); + crate::http::show(ui, &bench.state, &mut view, &mut actions); + crate::http::leave::show(ui, &bench.state, &mut view, &mut actions); + bench.state.http_view = view; + if let Some(action) = crate::keys::read(&bench.state, &ctx) { + actions.push(action); } - if bench.state.settings.area == Area::Tools { - let mut view = std::mem::take(&mut bench.state.tools_view); - crate::tools::show(ui, &bench.state, &mut view, &mut actions); - bench.state.tools_view = view; - if let Some(action) = crate::keys::read(&bench.state, &ctx) { - actions.push(action); - } - for action in actions.drain().collect::>() { - bench.state.apply(action, &ctx, &bench.backend); - } - return; + for action in actions.drain().collect::>() { + bench.state.apply(action, &ctx, &bench.backend); } - let mut view = std::mem::take(&mut bench.state.notes_view); - crate::notes::show(ui, &bench.state, &mut view, &mut actions); - let mut palette = std::mem::take(&mut bench.state.palette_view); - crate::palette::show(&ctx, &bench.state, &mut palette, &mut actions); - bench.state.palette_view = palette; - crate::notes::fill_form(ui, &bench.state, &mut view, &mut actions); - bench.state.notes_view = view; + return; + } + if bench.state.settings.area == Area::Tools { + let mut view = std::mem::take(&mut bench.state.tools_view); + crate::tools::show(ui, &bench.state, &mut view, &mut actions); + bench.state.tools_view = view; if let Some(action) = crate::keys::read(&bench.state, &ctx) { actions.push(action); } for action in actions.drain().collect::>() { bench.state.apply(action, &ctx, &bench.backend); } - }, - Bench { - backend, - state, - _profile: profile, - }, - ); + return; + } + let mut view = std::mem::take(&mut bench.state.notes_view); + crate::notes::show(ui, &bench.state, &mut view, &mut actions); + let mut palette = std::mem::take(&mut bench.state.palette_view); + crate::palette::show(&ctx, &bench.state, &mut palette, &mut actions); + bench.state.palette_view = palette; + crate::notes::fill_form(ui, &bench.state, &mut view, &mut actions); + bench.state.notes_view = view; + if let Some(action) = crate::keys::read(&bench.state, &ctx) { + actions.push(action); + } + for action in actions.drain().collect::>() { + bench.state.apply(action, &ctx, &bench.backend); + } + }, + Bench { backend, state, _profile: profile }, + ); settle(&mut harness); harness } @@ -113,27 +98,18 @@ pub(crate) fn settle(harness: &mut Harness<'_, Bench>) { pub(crate) fn space(backend: &Backend, name: &str) -> Space { let draft = SpaceDraft { name: name.into() }; - engine::db::run_here(backend.engine(), move |engine| { - engine::spaces::create_space(engine, &draft) - }) - .unwrap() -} - -pub(crate) fn folder( - backend: &Backend, - space: &Space, - parent: Option<&Folder>, - name: &str, -) -> Folder { + engine::db::run_here(backend.engine(), move |engine| engine::spaces::create_space(engine, &draft)) + .unwrap() +} + +pub(crate) fn folder(backend: &Backend, space: &Space, parent: Option<&Folder>, name: &str) -> Folder { let draft = FolderDraft { space_id: space.id.clone(), name: name.into(), parent_id: parent.map(|parent| parent.id.clone()), }; - engine::db::run_here(backend.engine(), move |engine| { - engine::folders::create_folder(engine, &draft) - }) - .unwrap() + engine::db::run_here(backend.engine(), move |engine| engine::folders::create_folder(engine, &draft)) + .unwrap() } /// The names of the rows wearing `author_id`, top to bottom. @@ -152,9 +128,7 @@ pub(crate) fn click(harness: &mut Harness<'_, Bench>, author_id: &str, name: &st } pub(crate) fn click_id(harness: &mut Harness<'_, Bench>, author_id: &str) { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); settle(harness); } @@ -168,9 +142,7 @@ pub(crate) fn type_and_enter(harness: &mut Harness<'_, Bench>, author_id: &str, } pub(crate) fn cards(harness: &Harness<'_, Bench>) -> usize { - harness - .query_all_by(|node| node.author_id() == Some("note-card")) - .count() + harness.query_all_by(|node| node.author_id() == Some("note-card")).count() } pub(crate) fn spaces_of_backend(backend: &Backend) -> Vec { @@ -178,19 +150,13 @@ pub(crate) fn spaces_of_backend(backend: &Backend) -> Vec { } pub(crate) fn spaces_of(harness: &Harness<'_, Bench>) -> Vec { - engine::db::run_here( - harness.state().backend.engine(), - engine::spaces::list_spaces, - ) - .unwrap() + engine::db::run_here(harness.state().backend.engine(), engine::spaces::list_spaces).unwrap() } pub(crate) fn remembered(harness: &Harness<'_, Bench>, key: &str) -> Option { - let directory = engine::db::run_here( - harness.state().backend.engine(), - engine::libraries::open_library_directory, - ) - .unwrap(); + let directory = + engine::db::run_here(harness.state().backend.engine(), engine::libraries::open_library_directory) + .unwrap(); Preferences::read(&directory.join(engine::layout::PREFERENCES)) .get(key) .map(str::to_owned) diff --git a/crates/ui/src/notes/calc.rs b/crates/ui/src/notes/calc.rs index 318829965..c1b85d32e 100644 --- a/crates/ui/src/notes/calc.rs +++ b/crates/ui/src/notes/calc.rs @@ -94,12 +94,7 @@ impl Format { /// The language on screen and nothing of its own. pub fn plain(language: Language) -> Self { - Self { - language, - decimals: None, - numbers: None, - dates: CalcDate::Numeric, - } + Self { language, decimals: None, numbers: None, dates: CalcDate::Numeric } } } @@ -130,15 +125,8 @@ pub fn value(value: &CalcValue, places: Option, format: Format) -> Written { } CalcValue::Percent { value, signed } => { let shown = number(value, digits(value, false, places), *signed, format); - let text = i18n::translate( - language, - i18n::keys::calc::PERCENT, - &[("value", shown.text.into())], - ); - Written { - text, - approx: shown.approx, - } + let text = i18n::translate(language, i18n::keys::calc::PERCENT, &[("value", shown.text.into())]); + Written { text, approx: shown.approx } } CalcValue::Date { date } => exact_text(match format.dates { CalcDate::Numeric => i18n::format::date_numeric(*date, language), @@ -146,11 +134,7 @@ pub fn value(value: &CalcValue, places: Option, format: Format) -> Written { CalcDate::Long => i18n::format::date_long(*date, language), }), CalcValue::Span { parts } => exact_text(span(parts, true, language)), - CalcValue::Base { - digits, - radix, - negative, - } => { + CalcValue::Base { digits, radix, negative } => { let prefix = match radix { 2 => "0b", 8 => "0o", @@ -168,25 +152,14 @@ pub fn value(value: &CalcValue, places: Option, format: Format) -> Written { approx: shown.approx, } } - CalcValue::Fraction { - numerator, - denominator, - negative, - } => { + CalcValue::Fraction { numerator, denominator, negative } => { let sign = if *negative { "-" } else { "" }; - let below = if denominator == "1" { - String::new() - } else { - format!("/{denominator}") - }; + let below = if denominator == "1" { String::new() } else { format!("/{denominator}") }; exact_text(format!("{sign}{numerator}{below}")) } CalcValue::Multiplier { value } => { let shown = number(value, digits(value, false, None), false, format); - Written { - text: format!("×{}", shown.text), - approx: shown.approx, - } + Written { text: format!("×{}", shown.text), approx: shown.approx } } } } @@ -195,34 +168,22 @@ pub fn value(value: &CalcValue, places: Option, format: Format) -> Written { /// grouped, since a sheet reads `1.578` and `1,578` as decimals. pub fn exact(value: &CalcValue, language: Language) -> String { let every = |figures: &str, signed: bool| { - let digits = figures - .split_once('.') - .map_or(0, |(_, fraction)| fraction.len()); + let digits = figures.split_once('.').map_or(0, |(_, fraction)| fraction.len()); i18n::format::exact(figures, (0, digits.min(20)), signed, false, language) }; match value { CalcValue::Scientific { mantissa, exponent } => { let sign = if *exponent < 0 { '-' } else { '+' }; - format!( - "{}e{sign}{}", - every(mantissa, false), - exponent.unsigned_abs() - ) + format!("{}e{sign}{}", every(mantissa, false), exponent.unsigned_abs()) } CalcValue::Multiplier { value } => format!("×{}", every(value, false)), CalcValue::Span { parts } => span(parts, false, language), - CalcValue::Percent { value, signed } => i18n::translate( - language, - i18n::keys::calc::PERCENT, - &[("value", every(value, *signed).into())], - ), + CalcValue::Percent { value, signed } => { + i18n::translate(language, i18n::keys::calc::PERCENT, &[("value", every(value, *signed).into())]) + } CalcValue::Number { value, unit } => match unit { None => every(value, false), - Some(unit) => format!( - "{}{NBSP}{}", - every(value, false), - self::unit(*unit, language) - ), + Some(unit) => format!("{}{NBSP}{}", every(value, false), self::unit(*unit, language)), }, other => self::value(other, None, Format::plain(language)).text, } @@ -233,9 +194,7 @@ pub fn exact(value: &CalcValue, language: Language) -> String { /// read past and the same lines compute again. pub fn copy_text(text: &str, sheet: &CalcSheet, format: Format) -> String { let lines = text.split('\n').enumerate().map(|(index, line)| { - let Some(CalcLine::Value { value, places, .. }) = - sheet.rows.get(index).map(|row| &row.line) - else { + let Some(CalcLine::Value { value, places, .. }) = sheet.rows.get(index).map(|row| &row.line) else { return line.to_owned(); }; let shown = self::value(value, *places, format); @@ -260,34 +219,16 @@ pub fn error(error: &CalcError, language: Language) -> String { CalcError::Unreadable { .. } => tr("unreadable", &[]), CalcError::UnknownName { name } => tr("unknownName", &[("name", name.as_str().into())]), CalcError::Reserved { word } => tr("reserved", &[("word", word.as_str().into())]), - CalcError::Mismatch { - expected, - found, - unit: None, - } => tr( - "mismatch", - &[ - ("found", dimension(*found).into()), - ("expected", dimension(*expected).into()), - ], - ), - CalcError::Mismatch { - expected, - unit: Some(found), - .. - } => tr( + CalcError::Mismatch { expected, found, unit: None } => { + tr("mismatch", &[("found", dimension(*found).into()), ("expected", dimension(*expected).into())]) + } + CalcError::Mismatch { expected, unit: Some(found), .. } => tr( "mismatchUnit", - &[ - ("unit", unit(*found, language).into()), - ("expected", dimension(*expected).into()), - ], + &[("unit", unit(*found, language).into()), ("expected", dimension(*expected).into())], ), CalcError::NotConvertible { from, to } => { let to = to.map_or_else(|| "%".to_owned(), |to| unit(to, language)); - tr( - "notConvertible", - &[("from", dimension(*from).into()), ("to", to.into())], - ) + tr("notConvertible", &[("from", dimension(*from).into()), ("to", to.into())]) } other => { let kind = serde_json::to_value(other).ok(); @@ -295,7 +236,11 @@ pub fn error(error: &CalcError, language: Language) -> String { tr(kind.unwrap_or("unsupported"), &[]) } }; - capitalised(&text) + // A unit's case is its meaning: « m » is no « M ». + match error { + CalcError::Mismatch { unit: Some(_), .. } => text, + _ => capitalised(&text), + } } fn name_of(dimension: Dimension) -> String { @@ -306,9 +251,9 @@ fn name_of(dimension: Dimension) -> String { fn capitalised(text: &str) -> String { let mut characters = text.chars(); - characters.next().map_or_else(String::new, |first| { - first.to_uppercase().chain(characters).collect() - }) + characters + .next() + .map_or_else(String::new, |first| first.to_uppercase().chain(characters).collect()) } fn spellings(entry: &WordEntry, language: Language) -> &[&'static str] { @@ -341,8 +286,7 @@ pub fn complete(typed: &str, language: Language) -> Vec { let fits: Vec<&&str> = spellings(entry, language) .iter() .filter(|spelling| { - (entry.class == WordClass::Value || spelling.contains(' ')) - && spelling.starts_with(&start) + (entry.class == WordClass::Value || spelling.contains(' ')) && spelling.starts_with(&start) }) .collect(); let whole = fits.iter().any(|spelling| ***spelling == *start); @@ -357,10 +301,7 @@ pub fn complete(typed: &str, language: Language) -> Vec { /// The start of a unit after a conversion word, in either language: a sheet reads both. pub fn conversion_start(before: &str) -> Option<&str> { - let typed = before - .rsplit(char::is_whitespace) - .next() - .unwrap_or_default(); + let typed = before.rsplit(char::is_whitespace).next().unwrap_or_default(); let head = before[..before.len() - typed.len()].to_lowercase(); if head.trim_end().len() == head.len() { return None; @@ -388,9 +329,7 @@ pub fn units_for(dimension: Dimension, typed: &str, language: Language) -> Vec Vec Written { - Written { - text, - approx: false, - } + Written { text, approx: false } } fn unit(unit: CalcUnit, language: Language) -> String { @@ -418,8 +354,7 @@ fn symbol(unit: UnitId, language: Language) -> String { .ok() .and_then(|name| name.as_str().map(str::to_string)) .unwrap_or_default(); - i18n::Key::find(&format!("calc.units.{name}")) - .map_or(name, |key| i18n::translate(language, key, &[])) + i18n::Key::find(&format!("calc.units.{name}")).map_or(name, |key| i18n::translate(language, key, &[])) } /// `6 sem 3 j`: whole parts, each with its unit. @@ -446,17 +381,12 @@ fn number(value: &str, (min, max): (usize, usize), signed: bool, format: Format) }) .collect(), }; - Written { - text, - approx: fraction(value).len() > max, - } + Written { text, approx: fraction(value).len() > max } } /// The decimals of `-12.50`, its trailing zeros dropped: `5`. fn fraction(value: &str) -> &str { - value - .split_once('.') - .map_or("", |(_, fraction)| fraction.trim_end_matches('0')) + value.split_once('.').map_or("", |(_, fraction)| fraction.trim_end_matches('0')) } /// At least and at most how many decimals: what the line asked for, else two for money and @@ -470,11 +400,7 @@ fn digits(value: &str, money: bool, places: Option) -> (usize, usize) { if money { return (2, 2); } - let whole = value - .trim_start_matches('-') - .split('.') - .next() - .unwrap_or(""); + let whole = value.trim_start_matches('-').split('.').next().unwrap_or(""); let fraction = fraction(value); if whole.bytes().all(|digit| digit == b'0') && !fraction.is_empty() { let first = fraction.find(|digit| digit != '0').unwrap_or(0); @@ -493,10 +419,7 @@ mod format_tests { use super::*; fn written(format: Format) -> String { - let value = CalcValue::Number { - value: "1578.13".to_owned(), - unit: None, - }; + let value = CalcValue::Number { value: "1578.13".to_owned(), unit: None }; value_of(&value, format) } @@ -506,24 +429,15 @@ mod format_tests { #[test] fn a_locale_writes_its_own_separators() { - let german = Format { - numbers: Some(NUMBER_FORMATS[4]), - ..Format::plain(Language::En) - }; + let german = Format { numbers: Some(NUMBER_FORMATS[4]), ..Format::plain(Language::En) }; assert_eq!(written(german), "1.578,13"); } #[test] fn the_decimals_chosen_stand_under_what_a_line_asks() { - let three = Format { - decimals: Some(3), - ..Format::plain(Language::En) - }; - let value = CalcValue::Number { - value: "2.5".to_owned(), - unit: None, - }; + let three = Format { decimals: Some(3), ..Format::plain(Language::En) }; + let value = CalcValue::Number { value: "2.5".to_owned(), unit: None }; assert_eq!(self::value(&value, None, three).text, "2.500"); assert_eq!(self::value(&value, Some(1), three).text, "2.5"); @@ -531,18 +445,10 @@ mod format_tests { #[test] fn a_date_follows_the_style_chosen() { - let date = CalcValue::Date { - date: chrono::NaiveDate::from_ymd_opt(2026, 11, 6).unwrap(), - }; - let long = Format { - dates: CalcDate::Long, - ..Format::plain(Language::En) - }; + let date = CalcValue::Date { date: chrono::NaiveDate::from_ymd_opt(2026, 11, 6).unwrap() }; + let long = Format { dates: CalcDate::Long, ..Format::plain(Language::En) }; - assert_ne!( - value_of(&date, long), - value_of(&date, Format::plain(Language::En)) - ); + assert_ne!(value_of(&date, long), value_of(&date, Format::plain(Language::En))); } } @@ -585,31 +491,31 @@ mod tests { fn a_value_is_given_whole_with_no_thousands_grouped() { let money = CalcValue::Number { value: "1234.56789".to_owned(), - unit: Some(CalcUnit { - unit: UnitId::Euro, - per: None, - }), + unit: Some(CalcUnit { unit: UnitId::Euro, per: None }), }; assert_eq!(exact(&money, Language::En), format!("1234.56789{NBSP}€")); assert_eq!(exact(&money, Language::Fr), format!("1234,56789{NBSP}€")); - let times = CalcValue::Multiplier { - value: "1.5".to_owned(), - }; + let times = CalcValue::Multiplier { value: "1.5".to_owned() }; assert_eq!(exact(×, Language::En), "×1.5"); } #[test] fn an_error_is_said_with_a_capital_and_its_words() { - let unknown = CalcError::UnknownName { - name: "prix".to_owned(), - }; + let unknown = CalcError::UnknownName { name: "prix".to_owned() }; assert!(error(&unknown, Language::En).contains("prix")); let text = error(&CalcError::DivisionByZero, Language::En); - assert!( - text.chars().next().is_some_and(char::is_uppercase), - "{text}" - ); + assert!(text.chars().next().is_some_and(char::is_uppercase), "{text}"); + } + + /// « m » is no « M ». + #[test] + fn an_error_that_starts_with_a_unit_keeps_its_case() { + let metre = CalcUnit { unit: UnitId::Metre, per: None }; + let wrong = + CalcError::Mismatch { expected: Dimension::Time, found: Dimension::Length, unit: Some(metre) }; + + assert_eq!(error(&wrong, Language::En), "m is not a duration"); } #[test] @@ -642,8 +548,7 @@ mod tests { #[test] fn values_are_written_as_the_golden_cases_say() { let cases: Vec = - serde_json::from_str(include_str!("../../../../golden/calc-format/cases.json")) - .unwrap(); + serde_json::from_str(include_str!("../../../../golden/calc-format/cases.json")).unwrap(); let mut checked = 0; for case in cases { let language = match case["options"]["lang"].as_str() { @@ -654,13 +559,180 @@ mod tests { }; let input: CalcValue = serde_json::from_value(case["input"].clone()).unwrap(); let written = value(&input, None, Format::plain(language)); - assert_eq!( - written.text, case["output"]["text"], - "{input:?} in {language:?}" - ); + assert_eq!(written.text, case["output"]["text"], "{input:?} in {language:?}"); assert_eq!(written.approx, case["output"]["approx"], "{input:?}"); checked += 1; } assert_eq!(checked, 20); } + + fn number_of(value: &str, unit: Option<(UnitId, Option)>) -> CalcValue { + CalcValue::Number { value: value.to_owned(), unit: unit.map(|(unit, per)| CalcUnit { unit, per }) } + } + + /// Each form a result takes: on its line, then whole, as a copy gives it. + #[test] + fn each_kind_of_value_is_written_on_its_line_and_whole() { + let base = |radix| CalcValue::Base { digits: "ff".to_owned(), radix, negative: radix == 16 }; + let fraction = |denominator: &str, negative| CalcValue::Fraction { + numerator: "3".to_owned(), + denominator: denominator.to_owned(), + negative, + }; + let science = |exponent| CalcValue::Scientific { mantissa: "1.23456".to_owned(), exponent }; + let span = CalcValue::Span { + parts: vec![ + SpanPart { value: "1250".to_owned(), unit: UnitId::Week }, + SpanPart { value: "3".to_owned(), unit: UnitId::Day }, + ], + }; + for (value, shown, whole) in [ + (base(16), "-0xff", "-0xff"), + (base(8), "0off", "0off"), + (base(2), "0bff", "0bff"), + (base(36), "ff", "ff"), + (fraction("4", false), "3/4", "3/4"), + (fraction("1", true), "-3", "-3"), + (science(6), "1.235e+6", "1.23456e+6"), + (science(-6), "1.235e-6", "1.23456e-6"), + (CalcValue::Multiplier { value: "1234.5".to_owned() }, "×1,234.5", "×1234.5"), + (CalcValue::Percent { value: "1234.567".to_owned(), signed: true }, "+1,234.57%", "+1234.567%"), + (span, "1,250 wk 3 d", "1250 wk 3 d"), + ( + number_of("1234.5", Some((UnitId::Kilometre, Some(UnitId::Hour)))), + "1,234.5 km/h", + "1234.5 km/h", + ), + ] { + let plain = |text: String| text.replace(NBSP, " "); + let line = self::value(&value, None, Format::plain(Language::En)).text; + assert_eq!(plain(line), shown, "{value:?}"); + assert_eq!(plain(exact(&value, Language::En)), whole, "{value:?}"); + } + } + + /// Two for money; four figures otherwise, two decimals at least; a small value keeps its first. + #[test] + fn a_value_keeps_the_decimals_that_say_it() { + let euro = Some((UnitId::Euro, None)); + let rate = Some((UnitId::Euro, Some(UnitId::Hour))); + for (value, unit, shown, approx) in [ + ("2", euro, "2.00 €", false), + ("2.005", euro, "2.01 €", true), + ("0.045", rate, "0.045 €/h", false), + ("1.23456", None, "1.235", true), + ("12.3456", None, "12.35", true), + ("12345.678", None, "12,345.68", true), + ("0.000123456", None, "0.0001235", true), + ("0.0000000001234", None, "0", true), + ("-0.5", None, "-0.5", false), + ("2.500", None, "2.5", false), + ("0", None, "0", false), + ] { + let value = number_of(value, unit); + let written = self::value(&value, None, Format::plain(Language::En)); + let said = (written.text.replace(NBSP, " "), written.approx); + assert_eq!(said, (shown.to_owned(), approx), "{value:?}"); + } + } + + #[test] + fn a_date_is_written_in_the_style_chosen() { + let date = CalcValue::Date { date: chrono::NaiveDate::from_ymd_opt(2026, 11, 6).unwrap() }; + let written = |dates| { + let format = Format { dates, ..Format::plain(Language::En) }; + self::value(&date, None, format).text + }; + let styles = [CalcDate::Numeric, CalcDate::Short, CalcDate::Long].map(written); + + assert!(styles.iter().all(|text| text.contains("2026")), "{styles:?}"); + assert!(styles[2].contains("November") && !styles[1].contains("November"), "{styles:?}"); + assert!(!styles[0].contains("Nov"), "{styles:?}"); + } + + #[test] + fn a_locale_is_the_one_named_or_the_language_s() { + assert_eq!(sample("1234.5", "de-DE", Language::En), "1.234,50"); + assert_eq!(sample("1234.5", "ja-JP", Language::Fr), "1,234.50"); + assert_eq!(sample("1234.5", "", Language::En), "1,234.50"); + let settings = Settings { + calc_number_format: "sv-SE".to_owned(), + calc_decimals: Some(3), + ..Settings::default() + }; + let format = Format::of(&settings, Language::En); + assert_eq!(format.numbers.map(|format| format.id), Some("sv-SE")); + assert_eq!(format.decimals, Some(3)); + } + + /// What is wrong, and what it is wrong about. + #[test] + fn each_error_is_said_in_its_own_words() { + let kilo = CalcUnit { unit: UnitId::Kilogram, per: None }; + let mismatch = + |unit| CalcError::Mismatch { expected: Dimension::Length, found: Dimension::Mass, unit }; + let not_convertible = |to| CalcError::NotConvertible { from: Dimension::Length, to }; + let mut said = Vec::new(); + for (wrong, about) in [ + (CalcError::Unreadable { at: 3 }, vec![]), + (CalcError::UnknownName { name: "prix".to_owned() }, vec!["prix"]), + (CalcError::Reserved { word: "en".to_owned() }, vec!["en"]), + (mismatch(None), vec!["length", "mass"]), + (mismatch(Some(kilo)), vec!["length", "kg"]), + (CalcError::Currency, vec![]), + (not_convertible(Some(kilo)), vec!["length", "kg"]), + (not_convertible(None), vec!["length", "%"]), + (CalcError::DivisionByZero, vec![]), + (CalcError::NothingAbove, vec![]), + (CalcError::NoPrevious, vec![]), + (CalcError::DateShift, vec![]), + (CalcError::NegativeRoot, vec![]), + (CalcError::LogDomain, vec![]), + (CalcError::NotWhole, vec![]), + (CalcError::NotPositive, vec![]), + (CalcError::RateExpected, vec![]), + (CalcError::Overflow, vec![]), + (CalcError::Unsupported, vec![]), + ] { + let words = error(&wrong, Language::En); + assert!(!words.is_empty(), "{wrong:?}"); + assert!(about.iter().all(|each| words.contains(each)), "{wrong:?}: {words:?}"); + said.push(words); + } + let count = said.len(); + said.sort(); + said.dedup(); + assert_eq!(said.len(), count, "{said:?}"); + } + + /// The same in both languages: a sheet reads either. + #[test] + fn what_is_after_a_conversion_word_is_a_unit_being_typed() { + for (before, typed) in [ + ("3 km en m", Some("m")), + ("3 km to ", Some("")), + ("3 km EN mi", Some("mi")), + ("en m", Some("m")), + ("3 km", None), + ("chien m", None), + ("", None), + ("3 kmen m", None), + ] { + assert_eq!(conversion_start(before), typed, "{before:?}"); + } + } + + #[test] + fn a_word_is_proposed_in_the_language_on_screen() { + assert!(complete("auj", Language::Fr).contains(&"aujourd'hui".to_owned())); + assert!(complete("AUJOURD’", Language::Fr).contains(&"aujourd'hui".to_owned())); + assert!(complete("auj", Language::En).is_empty()); + } + + #[test] + fn a_unit_is_proposed_by_its_start_whatever_its_case() { + assert_eq!(units_for(Dimension::Length, "K", Language::En), ["km"]); + let all = units_for(Dimension::Length, "", Language::En); + assert!(all.len() > 3 && !all.contains(&"%".to_owned()), "{all:?}"); + } } diff --git a/crates/ui/src/notes/canvas/board/gesture.rs b/crates/ui/src/notes/canvas/board/gesture.rs index d01c7832e..0f3474b3a 100644 --- a/crates/ui/src/notes/canvas/board/gesture.rs +++ b/crates/ui/src/notes/canvas/board/gesture.rs @@ -42,13 +42,7 @@ pub(super) struct Gesture { impl Gesture { pub(super) fn new(kind: Kind, origin: BoardPoint, from: BoardFrame) -> Self { - Self { - kind, - origin, - from, - to: from, - moved: false, - } + Self { kind, origin, from, to: from, moved: false } } /// The pointer is at `at`: the frame follows once it has travelled. @@ -113,11 +107,7 @@ pub(super) fn worth_drawing(band: BoardFrame) -> bool { /// What a drawn band becomes once it is a zone: never too small to drop a card into. pub(super) fn as_zone(band: BoardFrame) -> BoardFrame { - BoardFrame { - width: band.width.max(MIN_ZONE_WIDTH), - height: band.height.max(MIN_ZONE_HEIGHT), - ..band - } + BoardFrame { width: band.width.max(MIN_ZONE_WIDTH), height: band.height.max(MIN_ZONE_HEIGHT), ..band } } /// Touching is enough, as with any rubber band; half-open on the far edges. @@ -137,23 +127,14 @@ pub(super) fn nudged(frame: BoardFrame, (dx, dy): (i32, i32), resizing: bool) -> ..frame }; } - BoardFrame { - x: snap(frame.x + dx * GRID_PX).max(0), - y: snap(frame.y + dy * GRID_PX).max(0), - ..frame - } + BoardFrame { x: snap(frame.x + dx * GRID_PX).max(0), y: snap(frame.y + dy * GRID_PX).max(0), ..frame } } #[cfg(test)] mod tests { use super::*; - const ZONE: BoardFrame = BoardFrame { - x: 100, - y: 100, - width: 300, - height: 240, - }; + const ZONE: BoardFrame = BoardFrame { x: 100, y: 100, width: 300, height: 240 }; fn at(x: i32, y: i32) -> BoardPoint { BoardPoint { x, y } @@ -178,19 +159,9 @@ mod tests { let mut gesture = Gesture::new(Kind::ResizeZone("perf".into()), at(400, 340), ZONE); gesture.follow(at(470, 350)); - assert_eq!( - gesture.to, - BoardFrame { - width: 380, - height: 260, - ..ZONE - } - ); + assert_eq!(gesture.to, BoardFrame { width: 380, height: 260, ..ZONE }); gesture.follow(at(0, 0)); - assert_eq!( - (gesture.to.width, gesture.to.height), - (MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT) - ); + assert_eq!((gesture.to.width, gesture.to.height), (MIN_ZONE_WIDTH, MIN_ZONE_HEIGHT)); assert_eq!((gesture.to.x, gesture.to.y), (100, 100)); } @@ -200,54 +171,17 @@ mod tests { let backward = drawn_to(at(483, 1218), at(61, 899)); assert_eq!(forward, backward); - assert_eq!( - forward, - BoardFrame { - x: 60, - y: 900, - width: 420, - height: 320 - } - ); + assert_eq!(forward, BoardFrame { x: 60, y: 900, width: 420, height: 320 }); assert!(!worth_drawing(drawn_to(at(10, 10), at(30, 30)))); - assert_eq!( - as_zone(BoardFrame { - width: 40, - height: 40, - ..forward - }) - .width, - MIN_ZONE_WIDTH - ); + assert_eq!(as_zone(BoardFrame { width: 40, height: 40, ..forward }).width, MIN_ZONE_WIDTH); } #[test] fn touching_is_overlapping_and_the_far_edges_are_open() { - let card = BoardFrame { - x: 0, - y: 0, - width: 240, - height: 150, - }; + let card = BoardFrame { x: 0, y: 0, width: 240, height: 150 }; - assert!(overlaps( - BoardFrame { - x: 239, - y: 149, - width: 10, - height: 10 - }, - card - )); - assert!(!overlaps( - BoardFrame { - x: 240, - y: 0, - width: 10, - height: 10 - }, - card - )); + assert!(overlaps(BoardFrame { x: 239, y: 149, width: 10, height: 10 }, card)); + assert!(!overlaps(BoardFrame { x: 240, y: 0, width: 10, height: 10 }, card)); } #[test] diff --git a/crates/ui/src/notes/canvas/board/mod.rs b/crates/ui/src/notes/canvas/board/mod.rs index f0bec0694..77cf87e9b 100644 --- a/crates/ui/src/notes/canvas/board/mod.rs +++ b/crates/ui/src/notes/canvas/board/mod.rs @@ -13,8 +13,8 @@ mod zone; use crate::theme::tokens::{font, radius}; use egui::{ - CornerRadius, FontFamily, PointerButton, Pos2, Rect, Response, Role, Sense, Shape, Stroke, - StrokeKind, Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2, + CornerRadius, FontFamily, PointerButton, Pos2, Rect, Response, Role, Sense, Shape, Stroke, StrokeKind, + Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2, }; use engine::folders::board::{BoardFrame, BoardNote, BoardPoint, BoardView, CARD_WIDTH, zone_at}; use i18n::{Key, keys}; @@ -34,12 +34,7 @@ use gesture::{Gesture, Kind}; /// Where a card the view never placed is drawn: `folders::board` places every one it reads. const UNPLACED: BoardPoint = BoardPoint { x: 16, y: 16 }; -const NOWHERE: BoardFrame = BoardFrame { - x: 0, - y: 0, - width: 0, - height: 0, -}; +const NOWHERE: BoardFrame = BoardFrame { x: 0, y: 0, width: 0, height: 0 }; /// A card that matches nothing asked stays in its seat and stops asking for attention. const DIMMED: f32 = 0.32; @@ -75,27 +70,16 @@ struct Hand<'a> { impl Hand<'_> { fn point(&self, at: Pos2) -> BoardPoint { - #[expect( - clippy::cast_possible_truncation, - reason = "a board is far under 2³¹ px" - )] + #[expect(clippy::cast_possible_truncation, reason = "a board is far under 2³¹ px")] let round = |value: f32| value.round() as i32; - BoardPoint { - x: round(at.x - self.origin.x), - y: round(at.y - self.origin.y), - } + BoardPoint { x: round(at.x - self.origin.x), y: round(at.y - self.origin.y) } } fn frame(&self, rect: Rect) -> BoardFrame { let at = self.point(rect.min); #[expect(clippy::cast_possible_truncation, reason = "a card's or a zone's size")] let size = |value: f32| value.round() as i32; - BoardFrame { - x: at.x, - y: at.y, - width: size(rect.width()), - height: size(rect.height()), - } + BoardFrame { x: at.x, y: at.y, width: size(rect.width()), height: size(rect.height()) } } /// A press that started travelling on `response`: the left button's gesture is `kind`, if it @@ -119,13 +103,9 @@ impl Hand<'_> { /// The rail row under a card being dragged, if the pointer is over one. fn over_rail(&self, ui: &Ui) -> Option<&RailRow> { - let dragging = self - .moving() - .is_some_and(|gesture| matches!(gesture.kind, Kind::Card { .. })); + let dragging = self.moving().is_some_and(|gesture| matches!(gesture.kind, Kind::Card { .. })); let at = ui.input(|input| input.pointer.latest_pos())?; - dragging - .then(|| self.rail.iter().find(|row| row.rect.contains(at))) - .flatten() + dragging.then(|| self.rail.iter().find(|row| row.rect.contains(at))).flatten() } /// The gesture under way, once it has travelled. @@ -134,12 +114,7 @@ impl Hand<'_> { } } -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - canvas_view: &mut CanvasView, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, state: &AppState, canvas_view: &mut CanvasView, actions: &mut Actions) { let language = state.language; let tr = |key: Key| i18n::translate(language, key, &[]); let canvas = spacing(ui.ctx()).canvas; @@ -147,10 +122,7 @@ pub(super) fn show( if board.error().is_some() { padded(ui, canvas, |ui| { state_text(ui, &tr(keys::errors::BOARD_LOAD_FAILED), "canvas-error"); - if Button::new(&tr(keys::errors::RETRY), "canvas-retry") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::errors::RETRY), "canvas-retry").show(ui).clicked() { actions.push(Action::Notes(crate::notes::Action::Reload)); } }); @@ -167,13 +139,7 @@ pub(super) fn show( // Said again by whichever card has it this frame, as on the list. canvas_view.anchor = canvas_view.focused.take(); let mut screen = std::mem::take(&mut canvas_view.board); - ground( - ui, - (board, view), - &context, - &mut screen, - (canvas_view, actions), - ); + ground(ui, (board, view), &context, &mut screen, (canvas_view, actions)); canvas_view.board = screen; } @@ -227,20 +193,10 @@ fn ground( drawn.widget_info(|| WidgetInfo::labeled(Role::Canvas, true, &surface_name)); address(ui, &drawn, "board-surface"); dots(ui, surface.min); - let mut hand = Hand { - gesture, - seats: Vec::new(), - origin: surface.min, - rail: &rail, - }; + let mut hand = Hand { gesture, seats: Vec::new(), origin: surface.min, rail: &rail }; track(ui, &mut hand); hand.grab(ui, &drawn, Some(Kind::DrawZone), NOWHERE); - reveal( - ui, - (board, view), - (surface.min, context.card_height()), - canvas_view.request.as_deref(), - ); + reveal(ui, (board, view), (surface.min, context.card_height()), canvas_view.request.as_deref()); cards_and_zones( ui, (board, view), @@ -253,11 +209,9 @@ fn ground( empty(ui, ui.clip_rect(), context.language, actions); } committed = follow(ui, (board, view), &mut hand); - canvas_view.over_rail = hand.over_rail(ui).map(|row| { - row.folder_id - .clone() - .unwrap_or_else(|| row.space_id.clone()) - }); + canvas_view.over_rail = hand + .over_rail(ui) + .map(|row| row.folder_id.clone().unwrap_or_else(|| row.space_id.clone())); }); if let Some(done) = committed { actions.push(Action::Notes(crate::notes::Action::Board(done))); @@ -266,13 +220,7 @@ fn ground( // Over the ground and not in the header: it acts on this board's geometry alone. Bottom // right, where it covers no zone's ⋯. let counts = (view.zones.len(), view.loose.len()); - tidy::show( - ui, - frame.max - vec2(16.0, 18.0), - counts, - context.language, - actions, - ); + tidy::show(ui, frame.max - vec2(16.0, 18.0), counts, context.language, actions); } /// The zones, then the loose cards over them, each only when it crosses what is seen. @@ -296,30 +244,14 @@ fn cards_and_zones( notes: cards_in(board, view, Some(&shown.folder.id)).collect(), }; let drawing = (context, &mut *menu, &mut *hand); - zone::show( - ui, - &drawn, - shown, - drawing, - (&mut *canvas_view, &mut *actions), - ); + zone::show(ui, &drawn, shown, drawing, (&mut *canvas_view, &mut *actions)); } } for entry in loose_cards(board, view) { - let rect = card_rect( - origin, - place_of(board, entry, hand.moving()), - context.card_height(), - ); + let rect = card_rect(origin, place_of(board, entry, hand.moving()), context.card_height()); if rect.intersects(clip) { let seat = (rect, "board-loose-card", false); - seated( - ui, - seat, - entry, - (context, &mut *hand), - (&mut *canvas_view, &mut *actions), - ); + seated(ui, seat, entry, (context, &mut *hand), (&mut *canvas_view, &mut *actions)); } } } @@ -338,11 +270,7 @@ fn track(ui: &Ui, hand: &mut Hand<'_>) { /// The pointer followed while it is down; on release, what the gesture commits. Nothing else /// commits, and a drag that never travelled was a click. -fn follow( - ui: &Ui, - (board, view): (&BoardState, &BoardView), - hand: &mut Hand<'_>, -) -> Option { +fn follow(ui: &Ui, (board, view): (&BoardState, &BoardView), hand: &mut Hand<'_>) -> Option { hand.gesture.as_ref()?; let (down, at) = ui.input(|input| (input.pointer.any_down(), input.pointer.latest_pos())); let Some(at) = at else { @@ -382,19 +310,12 @@ fn follow( if filed && folder.is_some() && folder == sits { return None; } - Some(BoardGesture::DropCard { - note_id, - folder, - at: point, - }) + Some(BoardGesture::DropCard { note_id, folder, at: point }) } - Kind::MoveZone(folder_id) | Kind::ResizeZone(folder_id) => Some(BoardGesture::MoveZone { - folder_id, - frame: to, - }), - Kind::DrawZone => { - gesture::worth_drawing(to).then(|| BoardGesture::DrawZone(gesture::as_zone(to))) + Kind::MoveZone(folder_id) | Kind::ResizeZone(folder_id) => { + Some(BoardGesture::MoveZone { folder_id, frame: to }) } + Kind::DrawZone => gesture::worth_drawing(to).then(|| BoardGesture::DrawZone(gesture::as_zone(to))), Kind::SelectBand => { let swept: Vec = hand .seats @@ -423,13 +344,7 @@ fn drop_target(board: &BoardState, view: &BoardView, moving: Option<&Gesture>) - .iter() .map(|zone| (zone.folder.id.clone(), board.frame(zone))) .collect(); - zone_at( - &frames, - BoardPoint { - x: gesture.to.x, - y: gesture.to.y, - }, - ) + zone_at(&frames, BoardPoint { x: gesture.to.x, y: gesture.to.y }) } /// A zone's frame now: the gesture moving it, else a move staged, else the view's. @@ -439,25 +354,20 @@ fn frame_of( moving: Option<&Gesture>, ) -> BoardFrame { match moving { - Some(Gesture { - kind: Kind::MoveZone(id) | Kind::ResizeZone(id), - to, - .. - }) if *id == zone.folder.id => *to, + Some(Gesture { kind: Kind::MoveZone(id) | Kind::ResizeZone(id), to, .. }) + if *id == zone.folder.id => + { + *to + } _ => board.frame(zone), } } fn place_of(board: &BoardState, entry: &BoardNote, moving: Option<&Gesture>) -> BoardPoint { match moving { - Some(Gesture { - kind: Kind::Card { - note_id, - filed: false, - }, - to, - .. - }) if *note_id == entry.note.id => BoardPoint { x: to.x, y: to.y }, + Some(Gesture { kind: Kind::Card { note_id, filed: false }, to, .. }) if *note_id == entry.note.id => { + BoardPoint { x: to.x, y: to.y } + } _ => board.place(entry).unwrap_or(UNPLACED), } } @@ -478,22 +388,17 @@ fn cards_in<'a>( view: &'a BoardView, zone: Option<&'a str>, ) -> impl Iterator { - let in_zones = view.zones.iter().flat_map(|shown| { - shown - .notes - .iter() - .map(move |entry| (entry, Some(shown.folder.id.as_str()))) - }); + let in_zones = view + .zones + .iter() + .flat_map(|shown| shown.notes.iter().map(move |entry| (entry, Some(shown.folder.id.as_str())))); in_zones .chain(view.loose.iter().map(|entry| (entry, None))) .filter(move |(entry, in_view)| board.sitting_in(&entry.note.id, *in_view) == zone) .map(|(entry, _)| entry) } -fn loose_cards<'a>( - board: &'a BoardState, - view: &'a BoardView, -) -> impl Iterator { +fn loose_cards<'a>(board: &'a BoardState, view: &'a BoardView) -> impl Iterator { cards_in(board, view, None) } @@ -524,11 +429,7 @@ fn seated( (context, hand): (&card::Context<'_>, &mut Hand<'_>), (canvas_view, actions): (&mut CanvasView, &mut Actions), ) { - let mut card_ui = ui.new_child( - UiBuilder::new() - .max_rect(rect) - .id_salt(("board-card", &entry.note.id)), - ); + let mut card_ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(("board-card", &entry.note.id))); let lifted = hand.moving().is_some_and(|gesture| { filed && matches!(&gesture.kind, Kind::Card { note_id, .. } if *note_id == entry.note.id) }); @@ -545,13 +446,7 @@ fn seated( let from = hand.frame(rect); hand.grab(ui, &seat, Some(Kind::Card { note_id, filed }), from); hand.seats.push((entry.note.id.clone(), from)); - card::show( - &mut card_ui, - rect, - &entry.note, - context, - (canvas_view, actions), - ); + card::show(&mut card_ui, rect, &entry.note, context, (canvas_view, actions)); // Over the card's own layer, which opens it: the hand that carries it says so. if hand.moving().is_some() { ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); @@ -561,48 +456,26 @@ fn seated( /// The card a drag took out of a zone, at the pointer, above everything: a filed card flows and /// has no place of its own to move, so without it the pointer would carry nothing. fn ghost(ui: &mut Ui, board: &BoardState, context: &card::Context<'_>, hand: &Hand<'_>) { - let Some(Gesture { - kind: Kind::Card { - note_id, - filed: true, - }, - to, - .. - }) = hand.moving() - else { + let Some(Gesture { kind: Kind::Card { note_id, filed: true }, to, .. }) = hand.moving() else { return; }; let Some(entry) = board.cards().find(|entry| entry.note.id == *note_id) else { return; }; - let rect = card_rect( - hand.origin, - BoardPoint { x: to.x, y: to.y }, - context.card_height(), - ); + let rect = card_rect(hand.origin, BoardPoint { x: to.x, y: to.y }, context.card_height()); let mut ghost_ui = ui.new_child( UiBuilder::new() .max_rect(rect) .id_salt(("board-ghost", note_id)) - .layer_id(egui::LayerId::new( - egui::Order::Tooltip, - egui::Id::unique("board-ghost"), - )), + .layer_id(egui::LayerId::new(egui::Order::Tooltip, egui::Id::unique("board-ghost"))), ); ghost_ui.set_clip_rect(ui.clip_rect()); let p = palette(ui.ctx()); - ghost_ui.painter().add( - p.shadow_overlay - .as_shape(rect, CornerRadius::same(radius::CARD)), - ); + ghost_ui + .painter() + .add(p.shadow_overlay.as_shape(rect, CornerRadius::same(radius::CARD))); let mut idle = CanvasView::default(); - card::show( - &mut ghost_ui, - rect, - &entry.note, - context, - (&mut idle, &mut Actions::default()), - ); + card::show(&mut ghost_ui, rect, &entry.note, context, (&mut idle, &mut Actions::default())); } /// The band being drawn: a folder's, dashed in the accent; a selection's, filled and plain — the @@ -658,14 +531,10 @@ fn reveal( .iter() .find(|zone| zone.notes.iter().any(|entry| entry.note.id == id)) .map(|zone| frame_rect(origin, board.frame(zone))); - let card = view - .loose - .iter() - .find(|entry| entry.note.id == id) - .map(|entry| { - let at = board.place(entry).unwrap_or(UNPLACED); - card_rect(origin, at, card_height) - }); + let card = view.loose.iter().find(|entry| entry.note.id == id).map(|entry| { + let at = board.place(entry).unwrap_or(UNPLACED); + card_rect(origin, at, card_height) + }); if let Some(rect) = zone.or(card) { ui.scroll_to_rect(rect, None); } @@ -696,14 +565,7 @@ fn dots(ui: &Ui, origin: Pos2) { fn empty(ui: &mut Ui, seen: Rect, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); let words = i18n::translate(language, keys::board::EMPTY, &[]); - let galley = widgets::text( - ui, - &words, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::BODY, 400.0, FontFamily::Proportional, p.text_2); let centre = pos2(seen.center().x, seen.top() + seen.height() * 0.4); let rect = Rect::from_center_size(centre, galley.size()); let response = ui.allocate_rect(rect, Sense::hover()); @@ -717,14 +579,9 @@ fn empty(ui: &mut Ui, seen: Rect, language: i18n::Language, actions: &mut Action vec2(widgets::Button::width(ui, &label), 28.0), ); let mut room = ui.new_child(egui::UiBuilder::new().max_rect(under)); - if widgets::Button::new(&label, "board-guide") - .show(&mut room) - .clicked() - { + if widgets::Button::new(&label, "board-guide").show(&mut room).clicked() { let guide = Panel::Docs(docs::ORGANISING); - actions.push(crate::action::Action::Menu( - crate::titlebar::Action::OpenHelp(guide), - )); + actions.push(crate::action::Action::Menu(crate::titlebar::Action::OpenHelp(guide))); } } @@ -735,17 +592,11 @@ fn px(value: i32) -> f32 { } fn frame_rect(origin: Pos2, frame: BoardFrame) -> Rect { - Rect::from_min_size( - origin + vec2(px(frame.x), px(frame.y)), - vec2(px(frame.width), px(frame.height)), - ) + Rect::from_min_size(origin + vec2(px(frame.x), px(frame.y)), vec2(px(frame.width), px(frame.height))) } fn card_rect(origin: Pos2, at: BoardPoint, height: f32) -> Rect { - Rect::from_min_size( - origin + vec2(px(at.x), px(at.y)), - vec2(px(CARD_WIDTH), height), - ) + Rect::from_min_size(origin + vec2(px(at.x), px(at.y)), vec2(px(CARD_WIDTH), height)) } #[cfg(test)] diff --git a/crates/ui/src/notes/canvas/board/tests.rs b/crates/ui/src/notes/canvas/board/tests.rs index c4a86303f..5572420a0 100644 --- a/crates/ui/src/notes/canvas/board/tests.rs +++ b/crates/ui/src/notes/canvas/board/tests.rs @@ -5,9 +5,7 @@ use egui_kittest::kittest::{NodeT, Queryable}; use engine::folders::model::Folder; use engine::spaces::model::Space; -use crate::notes::bench::{ - Bench, area, cards, click, click_id, folder, names, remembered, space, until, -}; +use crate::notes::bench::{Bench, area, cards, click, click_id, folder, names, remembered, space, until}; use crate::state::board::Mode; use crate::testing; @@ -74,10 +72,7 @@ fn titles_in(harness: &Harness<'_, Bench>, zone: &str) -> Vec { #[test] fn the_board_draws_each_folder_as_a_zone_holding_its_notes_the_loose_ones_beside() { let (mut harness, tableau) = tableau(); - assert!( - harness.state().state.board_place().is_none(), - "the list is the default" - ); + assert!(harness.state().state.board_place().is_none(), "the list is the default"); click_id(&mut harness, "view-board"); @@ -121,21 +116,11 @@ fn a_zone_title_and_a_sub_folder_chip_open_their_folder() { let mut harness = area(backend, profile); click(&mut harness, "space-option", "Tableau"); click_id(&mut harness, "view-board"); - assert_eq!( - titles_in(&harness, "Base"), - ["Index partiel"], - "a zone gathers its sub-tree" - ); + assert_eq!(titles_in(&harness, "Base"), ["Index partiel"], "a zone gathers its sub-tree"); click(&mut harness, "board-zone-child", "Perf"); - assert_eq!( - harness.state().state.active_folder(), - Some(perf.id.as_str()) - ); - assert!( - harness.state().state.board_place().is_none(), - "a folder of none is a grid" - ); + assert_eq!(harness.state().state.active_folder(), Some(perf.id.as_str())); + assert!(harness.state().state.board_place().is_none(), "a folder of none is a grid"); click(&mut harness, "folder-breadcrumb-back", "‹ Tableau"); click(&mut harness, "board-zone-open", "Base"); @@ -188,20 +173,15 @@ fn board_budget() { frames.push(started.elapsed()); } frames.sort(); - println!( - "3,000 cards: scrolling p50 {:?}, p95 {:?}, p99 {:?}", - frames[100], frames[190], frames[198] - ); + println!("3,000 cards: scrolling p50 {:?}, p95 {:?}, p99 {:?}", frames[100], frames[190], frames[198]); } /// Whether the seat of the card titled `title` is lit. fn lit(harness: &Harness<'_, Bench>, title: &str) -> bool { !harness .get_by(|node| { - matches!( - node.author_id(), - Some("board-loose-card" | "board-zone-card") - ) && node.label().as_deref() == Some(title) + matches!(node.author_id(), Some("board-loose-card" | "board-zone-card")) + && node.label().as_deref() == Some(title) }) .accesskit_node() .is_disabled() @@ -212,8 +192,7 @@ fn a_search_dims_what_it_does_not_match_and_moves_nothing() { let (mut harness, _) = tableau(); click_id(&mut harness, "view-board"); let offset = |harness: &Harness<'_, Bench>| { - rect_of(harness, "board-loose-card", "Dump nocturne").min - - rect_of(harness, "board-zone", "Perf").min + rect_of(harness, "board-loose-card", "Dump nocturne").min - rect_of(harness, "board-zone", "Perf").min }; let before = offset(&harness); @@ -221,17 +200,13 @@ fn a_search_dims_what_it_does_not_match_and_moves_nothing() { harness .get_by(|node| node.author_id() == Some("search-input")) .type_text("EXPLAIN"); - until(&mut harness, "the board dims", |harness| { - !lit(harness, "Dump nocturne") - }); + until(&mut harness, "the board dims", |harness| !lit(harness, "Dump nocturne")); assert!(lit(&harness, "EXPLAIN lent sur join")); assert_eq!(titles_in(&harness, "Perf"), ["EXPLAIN lent sur join"]); assert_eq!(offset(&harness), before, "dimmed in its seat"); click_id(&mut harness, "search-clear"); - until(&mut harness, "the board lights again", |harness| { - lit(harness, "Dump nocturne") - }); + until(&mut harness, "the board lights again", |harness| lit(harness, "Dump nocturne")); } /// The zone of `name`, far off to the right, as a hand would have left it. @@ -245,12 +220,7 @@ fn far_off(harness: &Harness<'_, Bench>, space: &Space, name: &str) { .unwrap(); let zone = engine::folders::board::ZonePlacement { folder_id: folder.id, - frame: engine::folders::board::BoardFrame { - x: 1_600, - y: 40, - width: 300, - height: 220, - }, + frame: engine::folders::board::BoardFrame { x: 1_600, y: 40, width: 300, height: 220 }, }; engine::folders::save_board_layout(engine, None, &[zone], &Vec::new()) }) @@ -267,48 +237,25 @@ fn aligning_leaves_the_zones_and_reorganising_brings_them_back_undoably() { crate::notes::bench::settle(&mut harness); let zone_x = |harness: &Harness<'_, Bench>| frame_of(harness, "Perf").x; // Waited for, not settled: under load the view is read again a frame or two later. - until(&mut harness, "the zone is read far off", |harness| { - zone_x(harness) == 1_600 - }); + until(&mut harness, "the zone is read far off", |harness| zone_x(harness) == 1_600); click_id(&mut harness, "board-tidy"); assert_eq!(zone_x(&harness), 1_600, "aligning moves no zone"); click_id(&mut harness, "board-tidy-more"); click_id(&mut harness, "board-tidy-everything"); - until(&mut harness, "the zone is back at its seat", |harness| { - zone_x(harness) != 1_600 - }); - assert_eq!( - rect_of(&harness, "board-zone", "Perf"), - seat, - "and the ground pans home" - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("undo-text")) - .is_some() - ); + until(&mut harness, "the zone is back at its seat", |harness| zone_x(harness) != 1_600); + assert_eq!(rect_of(&harness, "board-zone", "Perf"), seat, "and the ground pans home"); + assert!(harness.query_by(|node| node.author_id() == Some("undo-text")).is_some()); click_id(&mut harness, "undo-restore"); - until(&mut harness, "the hand's layout is back", |harness| { - zone_x(harness) == 1_600 - }); + until(&mut harness, "the hand's layout is back", |harness| zone_x(harness) == 1_600); } /// A press at `from`, the pointer moved in steps, a release at `to`: as a hand drags. -fn drag( - harness: &mut Harness<'_, Bench>, - from: egui::Pos2, - to: egui::Pos2, - button: egui::PointerButton, -) { - let press = |pos, pressed| egui::Event::PointerButton { - pos, - button, - pressed, - modifiers: egui::Modifiers::NONE, - }; +fn drag(harness: &mut Harness<'_, Bench>, from: egui::Pos2, to: egui::Pos2, button: egui::PointerButton) { + let press = + |pos, pressed| egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE }; harness.event(egui::Event::PointerMoved(from)); harness.step(); harness.event(press(from, true)); @@ -366,8 +313,7 @@ fn frame_of(harness: &Harness<'_, Bench>, name: &str) -> engine::folders::board: fn control_in(harness: &Harness<'_, Bench>, author_id: &str, zone: &str) -> egui::Rect { harness .get_by(|node| { - node.author_id() == Some(author_id) - && node.label().is_some_and(|label| label.contains(zone)) + node.author_id() == Some(author_id) && node.label().is_some_and(|label| label.contains(zone)) }) .rect() } @@ -380,34 +326,19 @@ fn a_card_dragged_into_a_zone_is_filed_there_and_back_out_on_the_ground() { let zone = rect_of(&harness, "board-zone", "Migrations"); let migrations = folder_named(&harness, &tableau, "Migrations"); - drag( - &mut harness, - card.center(), - zone.center(), - egui::PointerButton::Primary, - ); - assert_eq!( - titles_in(&harness, "Migrations"), - ["Dump nocturne"], - "drawn there at once" - ); + drag(&mut harness, card.center(), zone.center(), egui::PointerButton::Primary); + assert_eq!(titles_in(&harness, "Migrations"), ["Dump nocturne"], "drawn there at once"); until(&mut harness, "the drop is written", |harness| { filed_in(harness, "Dump nocturne").as_deref() == Some(migrations.id.as_str()) }); let seat = harness .get_by(|node| { - node.author_id() == Some("board-zone-card") - && node.label().as_deref() == Some("Dump nocturne") + node.author_id() == Some("board-zone-card") && node.label().as_deref() == Some("Dump nocturne") }) .rect(); let ground = seat.center() + egui::vec2(0.0, 360.0); - drag( - &mut harness, - seat.center(), - ground, - egui::PointerButton::Primary, - ); + drag(&mut harness, seat.center(), ground, egui::PointerButton::Primary); until(&mut harness, "the card is loose again", |harness| { filed_in(harness, "Dump nocturne").is_none() && names(harness, "board-loose-card") == ["Dump nocturne"] @@ -421,15 +352,8 @@ fn a_zone_moves_by_its_grip_and_resizes_by_its_corner_on_the_grid_filing_nothing let before = frame_of(&harness, "Perf"); let grip = control_in(&harness, "board-zone-grip", "Perf"); - drag( - &mut harness, - grip.center(), - grip.center() + egui::vec2(93.0, 141.0), - egui::PointerButton::Primary, - ); - until(&mut harness, "the move is written", |harness| { - frame_of(harness, "Perf").x != before.x - }); + drag(&mut harness, grip.center(), grip.center() + egui::vec2(93.0, 141.0), egui::PointerButton::Primary); + until(&mut harness, "the move is written", |harness| frame_of(harness, "Perf").x != before.x); let moved = frame_of(&harness, "Perf"); assert_eq!((moved.width, moved.height), (before.width, before.height)); assert_eq!((moved.x % 20, moved.y % 20), (0, 0), "on the grid"); @@ -441,18 +365,12 @@ fn a_zone_moves_by_its_grip_and_resizes_by_its_corner_on_the_grid_filing_nothing corner.center() + egui::vec2(260.0, 200.0), egui::PointerButton::Primary, ); - until(&mut harness, "the resize is written", |harness| { - frame_of(harness, "Perf").width > moved.width - }); + until(&mut harness, "the resize is written", |harness| frame_of(harness, "Perf").width > moved.width); let resized = frame_of(&harness, "Perf"); assert_eq!((resized.x, resized.y), (moved.x, moved.y)); let perf = folder_named(&harness, &tableau, "Perf"); assert_eq!(filed_in(&harness, "EXPLAIN lent sur join"), Some(perf.id)); - assert_eq!( - filed_in(&harness, "Dump nocturne"), - None, - "a stretched zone captures nothing" - ); + assert_eq!(filed_in(&harness, "Dump nocturne"), None, "a stretched zone captures nothing"); } #[test] @@ -474,10 +392,7 @@ fn the_grip_and_the_corner_answer_the_arrows_a_dot_at_a_time() { harness.step(); } // A dot further each way, snapped onto the lattice. - let wanted = ( - super::gesture::snap(before.x + 20), - super::gesture::snap(before.y + 20), - ); + let wanted = (super::gesture::snap(before.x + 20), super::gesture::snap(before.y + 20)); until(&mut harness, "both nudges are written", |harness| { let after = frame_of(harness, "Perf"); (after.x, after.y) == wanted @@ -492,12 +407,7 @@ fn a_band_drawn_on_the_ground_becomes_the_folder_named_there() { let ground = rect_of(&harness, "board", "Board"); let from = egui::pos2(ground.left() + 520.0, ground.top() + 420.0); - drag( - &mut harness, - from, - from + egui::vec2(300.0, 230.0), - egui::PointerButton::Primary, - ); + drag(&mut harness, from, from + egui::vec2(300.0, 230.0), egui::PointerButton::Primary); assert!(harness.state().state.board.drawn_zone().is_some()); crate::notes::bench::type_and_enter(&mut harness, "folder-name-input", "Reporting"); until(&mut harness, "the zone is drawn", |harness| { @@ -506,11 +416,7 @@ fn a_band_drawn_on_the_ground_becomes_the_folder_named_there() { let made = folder_named(&harness, &tableau, "Reporting"); let view = harness.state().state.board.view().unwrap(); - let zone = view - .zones - .iter() - .find(|zone| zone.folder.id == made.id) - .unwrap(); + let zone = view.zones.iter().find(|zone| zone.folder.id == made.id).unwrap(); assert_eq!((zone.frame.x % 20, zone.frame.y % 20), (0, 0)); assert!(zone.frame.width >= 300 - 20); } @@ -531,10 +437,7 @@ fn a_right_button_sweep_ticks_the_cards_it_crosses_zones_included() { let ticked = harness.state().state.on_screen(); let ticked: Vec<&str> = ticked.iter().map(String::as_str).collect(); assert_eq!(harness.state().state.selection.checked_in(&ticked).len(), 2); - assert!( - harness.state().state.board.drawn_zone().is_none(), - "the right button draws no folder" - ); + assert!(harness.state().state.board.drawn_zone().is_none(), "the right button draws no folder"); } #[test] @@ -566,25 +469,14 @@ fn a_card_let_go_of_over_a_rail_row_is_filed_there_and_offered_back() { let perf = folder_named(&harness, &tableau, "Perf"); let card = rect_of(&harness, "board-loose-card", "Dump nocturne"); let row = harness - .get_by(|node| { - node.author_id() == Some("folder-option") && node.label().as_deref() == Some("Perf") - }) + .get_by(|node| node.author_id() == Some("folder-option") && node.label().as_deref() == Some("Perf")) .rect(); - drag( - &mut harness, - card.center(), - row.center(), - egui::PointerButton::Primary, - ); + drag(&mut harness, card.center(), row.center(), egui::PointerButton::Primary); until(&mut harness, "the card is filed from the rail", |harness| { filed_in(harness, "Dump nocturne").as_deref() == Some(perf.id.as_str()) }); - assert!( - harness - .query_by(|node| node.author_id() == Some("undo-restore")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("undo-restore")).is_some()); } #[test] @@ -592,17 +484,116 @@ fn an_open_folder_s_list_is_named_after_it_until_something_is_searched() { let (mut harness, _) = tableau(); click(&mut harness, "folder-option", "Perf"); let heading = |harness: &Harness<'_, Bench>| names(harness, "note-section").join(" "); - assert!( - heading(&harness).starts_with("PERF"), - "{}", - heading(&harness) - ); + assert!(heading(&harness).starts_with("PERF"), "{}", heading(&harness)); click_id(&mut harness, "search-input"); harness .get_by(|node| node.author_id() == Some("search-input")) .type_text("EXPLAIN"); - until(&mut harness, "the search is asked", |harness| { - !heading(harness).starts_with("PERF") - }); + until(&mut harness, "the search is asked", |harness| !heading(harness).starts_with("PERF")); +} + +fn present(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn a_space_s_board( + backend: crate::backend::Backend, + profile: tempfile::TempDir, + name: &str, +) -> Harness<'static, Bench> { + let mut harness = area(backend, profile); + harness.set_size(egui::vec2(1_600.0, 900.0)); + click(&mut harness, "space-option", name); + click_id(&mut harness, "view-board"); + harness +} + +/// With what it is for, and the page that says how it works. +#[test] +fn a_board_with_nothing_on_it_says_so_and_opens_its_page() { + let (backend, profile) = testing::unlocked(); + space(&backend, "Accueil"); + space(&backend, "Vide"); + let mut harness = a_space_s_board(backend, profile, "Vide"); + assert!(present(&harness, "board-empty")); + + click_id(&mut harness, "board-guide"); + assert!(harness.state().state.dialogs.top().is_some()); +} + +#[test] +fn a_board_that_failed_offers_to_retry() { + let (mut harness, _) = tableau(); + click_id(&mut harness, "view-board"); + testing::close_library(&harness.state().backend); + let bench = harness.state_mut(); + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Reload), + &egui::Context::default(), + &bench.backend, + ); + until(&mut harness, "it failed", |harness| present(harness, "canvas-error")); + let before = harness.state().state.revision; + harness.get_by(|node| node.author_id() == Some("canvas-retry")).click(); + harness.run(); + + assert_ne!(harness.state().state.revision, before); +} + +/// One out of view is not drawn: the ground scrolls to it first. +#[test] +fn a_card_asked_for_is_scrolled_into_view() { + let (backend, profile) = testing::unlocked(); + space(&backend, "Accueil"); + let wide = space(&backend, "Grand"); + let far = folder(&backend, &wide, None, "Loin"); + let filed = note_in(&backend, &wide, "Rangée", Some(&far)); + let loose: Vec = (0..40) + .map(|at| note_in(&backend, &wide, &format!("Libre {at}"), None)) + .collect(); + let mut harness = a_space_s_board(backend, profile, "Grand"); + harness.set_size(egui::vec2(1_100.0, 500.0)); + crate::notes::bench::settle(&mut harness); + let drawn = |harness: &Harness<'_, Bench>, id: &str| { + harness.state().state.notes_view.canvas.focused.as_deref() == Some(id) + }; + for id in [&loose[39], &loose[0], &filed] { + harness.state_mut().state.notes_view.canvas.request = Some(id.clone()); + until(&mut harness, "it has the focus", |harness| drawn(harness, id)); + } +} + +fn button(pos: egui::Pos2, button: egui::PointerButton, pressed: bool) -> egui::Event { + egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE } +} + +/// Nobody chose the place under a pointer that left: the card goes back where it was. +#[test] +fn a_drag_whose_pointer_left_the_window_is_dropped() { + let (mut harness, _) = tableau(); + click_id(&mut harness, "view-board"); + let before = rect_of(&harness, "board-loose-card", "Dump nocturne"); + let from = before.center(); + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, egui::PointerButton::Primary, true)); + harness.step(); + for part in 1..=5_u8 { + harness.event(egui::Event::PointerMoved(from + egui::vec2(20.0 * f32::from(part), 0.0))); + harness.step(); + } + let dragging = + |harness: &Harness<'_, Bench>| harness.state().state.notes_view.canvas.board.gesture.is_some(); + assert!(dragging(&harness)); + harness.event(egui::Event::PointerGone); + harness.step(); + harness.step(); + assert!(!dragging(&harness)); + harness.event(button(from, egui::PointerButton::Primary, false)); + crate::notes::bench::settle(&mut harness); + + assert_eq!(rect_of(&harness, "board-loose-card", "Dump nocturne"), before); } diff --git a/crates/ui/src/notes/canvas/board/tidy.rs b/crates/ui/src/notes/canvas/board/tidy.rs index 15b3d7616..38b4bb829 100644 --- a/crates/ui/src/notes/canvas/board/tidy.rs +++ b/crates/ui/src/notes/canvas/board/tidy.rs @@ -5,8 +5,8 @@ use crate::theme::tokens::{font, radius}; use egui::{ - CornerRadius, FontFamily, Popup, PopupCloseBehavior, Pos2, RectAlign, Role, Sense, Stroke, - StrokeKind, Ui, UiBuilder, WidgetInfo, pos2, vec2, + CornerRadius, FontFamily, Popup, PopupCloseBehavior, Pos2, RectAlign, Role, Sense, Stroke, StrokeKind, + Ui, UiBuilder, WidgetInfo, pos2, vec2, }; use engine::folders::board::BoardScope; use i18n::keys; @@ -37,14 +37,7 @@ pub(super) fn show( let align = i18n::translate(language, keys::board::ALIGN, &[]); let hint = i18n::translate(language, keys::board::ALIGN_HINT, &counts); let more = i18n::translate(language, keys::board::TIDY_MORE_LABEL, &[]); - let words = widgets::text( - ui, - &align, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let words = widgets::text(ui, &align, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); let height = 30.0; let left_width = 13.0 + 14.0 + 6.0 + words.size().x + 13.0; let right_width = 10.0 + 14.0 + 10.0; @@ -58,37 +51,16 @@ pub(super) fn show( pill_ui.spacing_mut().item_spacing.x = 0.0; let round = CornerRadius::same(radius::DIALOG); ui.painter().add(p.shadow_dropdown.as_shape(pill, round)); - ui.painter().rect( - pill, - round, - p.bg_1, - Stroke::new(1.0, p.line), - StrokeKind::Inside, - ); - let tidy = half( - &mut pill_ui, - left_width, - "board-tidy", - &align, - CornerRadius { - nw: 15, - sw: 15, - ne: 0, - se: 0, - }, - ); + ui.painter() + .rect(pill, round, p.bg_1, Stroke::new(1.0, p.line), StrokeKind::Inside); + let tidy = + half(&mut pill_ui, left_width, "board-tidy", &align, CornerRadius { nw: 15, sw: 15, ne: 0, se: 0 }); let tidy = widgets::tooltip(tidy, &hint); let ink = if tidy.hovered() { p.text_0 } else { p.text_1 }; - let icon = egui::Rect::from_min_size( - pos2(pill.left() + 13.0, pill.center().y - 7.0), - vec2(14.0, 14.0), - ); + let icon = egui::Rect::from_min_size(pos2(pill.left() + 13.0, pill.center().y - 7.0), vec2(14.0, 14.0)); icons::paint(ui, icon, Icon::Table, ink); - ui.painter().galley( - pos2(icon.right() + 6.0, pill.center().y - words.size().y / 2.0), - words, - ink, - ); + ui.painter() + .galley(pos2(icon.right() + 6.0, pill.center().y - words.size().y / 2.0), words, ink); if tidy.clicked() { ask(actions, BoardScope::LooseCards); } @@ -97,18 +69,10 @@ pub(super) fn show( right_width, "board-tidy-more", &more, - CornerRadius { - nw: 0, - sw: 0, - ne: 15, - se: 15, - }, - ); - ui.painter().vline( - caret.rect.left(), - caret.rect.y_range().shrink(6.0), - Stroke::new(1.0, p.line_soft), + CornerRadius { nw: 0, sw: 0, ne: 15, se: 15 }, ); + ui.painter() + .vline(caret.rect.left(), caret.rect.y_range().shrink(6.0), Stroke::new(1.0, p.line_soft)); let ink = if caret.hovered() { p.text_0 } else { p.text_1 }; let chevron = egui::Rect::from_center_size(caret.rect.center(), vec2(12.0, 12.0)); icons::paint(ui, chevron, Icon::ChevronDown, ink); @@ -132,41 +96,22 @@ fn menu( .close_behavior(PopupCloseBehavior::CloseOnClickOutside) .show(|ui| { ui.set_width(240.0); - if widgets::menu_entry( - ui, - &everything, - "board-tidy-everything", - false, - false, - false, - ) - .clicked() - { + if widgets::menu_entry(ui, &everything, "board-tidy-everything", false, false, false).clicked() { ask(actions, BoardScope::Everything); ui.close(); } let mut job = egui::text::LayoutJob::single_section( note, - egui::TextFormat::simple( - egui::FontId::new(font::META, FontFamily::Proportional), - p.text_2, - ), + egui::TextFormat::simple(egui::FontId::new(font::META, FontFamily::Proportional), p.text_2), ); job.wrap.max_width = 240.0 - 18.0; let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); let (rect, _) = ui.allocate_exact_size(galley.size() + vec2(18.0, 6.0), Sense::hover()); - ui.painter() - .galley(rect.min + vec2(9.0, 2.0), galley, p.text_2); + ui.painter().galley(rect.min + vec2(9.0, 2.0), galley, p.text_2); }); } /// One half of the pill: a button of its own, rounded on its outer side. -fn half( - ui: &mut Ui, - width: f32, - author_id: &str, - label: &str, - corner: CornerRadius, -) -> egui::Response { +fn half(ui: &mut Ui, width: f32, author_id: &str, label: &str, corner: CornerRadius) -> egui::Response { let p = palette(ui.ctx()); let response = interact( ui, @@ -177,8 +122,7 @@ fn half( corner, ); if response.hovered() { - ui.painter() - .rect_filled(response.rect.shrink(1.0), corner, p.bg_2); + ui.painter().rect_filled(response.rect.shrink(1.0), corner, p.bg_2); } response } diff --git a/crates/ui/src/notes/canvas/board/zone.rs b/crates/ui/src/notes/canvas/board/zone.rs index 01df03364..3095654b7 100644 --- a/crates/ui/src/notes/canvas/board/zone.rs +++ b/crates/ui/src/notes/canvas/board/zone.rs @@ -10,8 +10,8 @@ use egui::{ StrokeKind, Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2, }; use engine::folders::board::{ - BoardChild, BoardFrame, BoardNote, BoardZone, CARD_WIDTH, GAP, ZONE_BORDER, ZONE_HEADER, - ZONE_PADDING, ZONE_SUBFOLDERS, columns_in, + BoardChild, BoardFrame, BoardNote, BoardZone, CARD_WIDTH, GAP, ZONE_BORDER, ZONE_HEADER, ZONE_PADDING, + ZONE_SUBFOLDERS, columns_in, }; use engine::folders::model::FolderContents; use i18n::keys; @@ -46,11 +46,7 @@ pub(super) fn show( let (rect, folder) = (drawn.rect, &zone.folder); let p = palette(ui.ctx()); let hue = folder_hue(ui, folder.colour); - let mut zone_ui = ui.new_child( - UiBuilder::new() - .max_rect(rect) - .id_salt(("board-zone", &folder.id)), - ); + let mut zone_ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt(("board-zone", &folder.id))); zone_ui.set_clip_rect(rect.intersect(ui.clip_rect())); let ui = &mut zone_ui; let corner = CornerRadius::same(radius::CARD); @@ -60,11 +56,7 @@ pub(super) fn show( if moving { ui.painter().add(p.shadow_overlay.as_shape(rect, corner)); } - let (fill, edge) = if drawn.lit { - (0.14, 2.0) - } else { - (0.08, px(ZONE_BORDER)) - }; + let (fill, edge) = if drawn.lit { (0.14, 2.0) } else { (0.08, px(ZONE_BORDER)) }; ui.painter().rect( rect, corner, @@ -89,29 +81,13 @@ pub(super) fn show( ); let mut top = head.bottom(); if !zone.children.is_empty() { - let row = Rect::from_min_size( - pos2(inside.left(), top), - vec2(inside.width(), px(ZONE_SUBFOLDERS)), - ); + let row = Rect::from_min_size(pos2(inside.left(), top), vec2(inside.width(), px(ZONE_SUBFOLDERS))); children(ui, row, zone, context.language, actions); top = row.bottom(); } let body = Rect::from_min_max(pos2(inside.left(), top), inside.max); - flow( - ui, - (body, drawn), - zone, - (context, &mut *hand), - (canvas_view, actions), - ); - resize_corner( - ui, - rect, - (zone, drawn.frame), - context.language, - hand, - actions, - ); + flow(ui, (body, drawn), zone, (context, &mut *hand), (canvas_view, actions)); + resize_corner(ui, rect, (zone, drawn.frame), context.language, hand, actions); } /// The grip, the swatch, the title that opens the folder, the count, and the ⋯ that edits it — @@ -134,8 +110,7 @@ fn header( grip(ui, grip_room, (zone, drawn.frame), language, hand, actions); let mut left = grip_room.right() + 4.0; let swatch = Rect::from_min_size(pos2(left, middle - 4.5), Vec2::splat(9.0)); - ui.painter() - .rect_filled(swatch, CornerRadius::same(radius::MARK), hue); + ui.painter().rect_filled(swatch, CornerRadius::same(radius::MARK), hue); left = swatch.right() + 9.0; let menu_room = Rect::from_center_size( @@ -143,23 +118,9 @@ fn header( Vec2::splat(widgets::MIN_TARGET), ); let count = drawn.notes.len().to_string(); - let count_galley = widgets::text( - ui, - &count, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let count_galley = widgets::text(ui, &count, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); let name_room = (menu_room.left() - 9.0 - count_galley.size().x - 9.0 - left).max(0.0); - let name = widgets::text( - ui, - &folder.name, - font::READING, - 500.0, - FontFamily::Proportional, - p.text_0, - ); + let name = widgets::text(ui, &folder.name, font::READING, 500.0, FontFamily::Proportional, p.text_0); let name_size = vec2(name.size().x.min(name_room), name.size().y); let target = Rect::from_min_size( pos2(left, middle - widgets::MIN_TARGET / 2.0), @@ -181,13 +142,10 @@ fn header( .galley(at, name, p.text_0); if open.hovered() { let under = clip.bottom() + 1.0; - ui.painter() - .hline(clip.x_range(), under, Stroke::new(1.0, hue)); + ui.painter().hline(clip.x_range(), under, Stroke::new(1.0, hue)); } if open.clicked() { - actions.push(Action::Notes(crate::notes::Action::ChooseFolder( - folder.id.clone(), - ))); + actions.push(Action::Notes(crate::notes::Action::ChooseFolder(folder.id.clone()))); } let count_at = pos2(target.right() + 9.0, middle - count_galley.size().y / 2.0); let count_rect = Rect::from_min_size(count_at, count_galley.size()); @@ -198,32 +156,15 @@ fn header( if drawn.lit { drop_here(ui, head, hue, language); } else { - menu( - ui, - menu_room, - (zone, drawn.notes.len()), - (contents, language), - menu_edit, - actions, - ); + menu(ui, menu_room, (zone, drawn.notes.len()), (contents, language), menu_edit, actions); } } /// « Drop here », said before the pointer lifts, where the ⋯ was. fn drop_here(ui: &mut Ui, head: Rect, hue: egui::Color32, language: i18n::Language) { let words = i18n::translate(language, keys::board::DROP_HERE, &[]); - let galley = widgets::text( - ui, - &words, - font::CONTROL, - 400.0, - FontFamily::Proportional, - hue, - ); - let at = pos2( - head.right() - 12.0 - galley.size().x, - head.center().y - galley.size().y / 2.0, - ); + let galley = widgets::text(ui, &words, font::CONTROL, 400.0, FontFamily::Proportional, hue); + let at = pos2(head.right() - 12.0 - galley.size().x, head.center().y - galley.size().y / 2.0); let rect = Rect::from_min_size(at, galley.size()); let response = ui.allocate_rect(rect, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); @@ -242,11 +183,8 @@ fn grip( actions: &mut Actions, ) { let p = palette(ui.ctx()); - let label = i18n::translate( - language, - keys::board::MOVE_ZONE, - &[("name", zone.folder.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::board::MOVE_ZONE, &[("name", zone.folder.name.as_str().into())]); let mut grip_ui = ui.new_child(UiBuilder::new().max_rect(room)); let response = interact( &mut grip_ui, @@ -260,11 +198,8 @@ fn grip( let response = widgets::tooltip(response, &label); let kind = Kind::MoveZone(zone.folder.id.clone()); hand.grab(ui, &response, Some(kind), frame); - let ink = if response.hovered() || response.has_focus() { - p.text_0 - } else { - p.text_2.gamma_multiply(0.6) - }; + let ink = + if response.hovered() || response.has_focus() { p.text_0 } else { p.text_2.gamma_multiply(0.6) }; // Six dots, ⠿: no embedded face has the braille block. for column in [-2.5, 2.5] { for row in [-4.0, 0.0, 4.0] { @@ -284,11 +219,8 @@ fn resize_corner( hand: &mut Hand<'_>, actions: &mut Actions, ) { - let label = i18n::translate( - language, - keys::board::RESIZE_ZONE, - &[("name", zone.folder.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::board::RESIZE_ZONE, &[("name", zone.folder.name.as_str().into())]); let room = Rect::from_min_max(rect.max - Vec2::splat(widgets::MIN_TARGET), rect.max); let mut corner_ui = ui.new_child(UiBuilder::new().max_rect(room)); let response = interact( @@ -308,10 +240,8 @@ fn resize_corner( let hue = folder_hue(ui, zone.folder.colour); let tip = rect.max - Vec2::splat(4.0); let stroke = Stroke::new(2.0, hue); - ui.painter() - .line_segment([tip - vec2(12.0, 0.0), tip], stroke); - ui.painter() - .line_segment([tip - vec2(0.0, 12.0), tip], stroke); + ui.painter().line_segment([tip - vec2(12.0, 0.0), tip], stroke); + ui.painter().line_segment([tip - vec2(0.0, 12.0), tip], stroke); nudge(ui, &response, (zone, frame), true, actions); } @@ -326,12 +256,7 @@ fn nudge( if !widgets::takes_keys(ui, response) { return; } - let kept = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, - ..egui::EventFilter::default() - }; - ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, kept)); + crate::widgets::keep_arrows(ui, response); let steps = [ (Key::ArrowLeft, (-1, 0)), (Key::ArrowRight, (1, 0)), @@ -341,12 +266,10 @@ fn nudge( for (key, step) in steps { let pressed = ui.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key)); if pressed { - actions.push(Action::Notes(crate::notes::Action::Board( - BoardGesture::MoveZone { - folder_id: zone.folder.id.clone(), - frame: gesture::nudged(frame, step, resizing), - }, - ))); + actions.push(Action::Notes(crate::notes::Action::Board(BoardGesture::MoveZone { + folder_id: zone.folder.id.clone(), + frame: gesture::nudged(frame, step, resizing), + }))); } } } @@ -362,14 +285,10 @@ fn menu( actions: &mut Actions, ) { let folder = &zone.folder; - let label = i18n::translate( - language, - keys::folders::OPTIONS_LABEL, - &[("name", folder.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::folders::OPTIONS_LABEL, &[("name", folder.name.as_str().into())]); let mut menu_ui = ui.new_child(UiBuilder::new().max_rect(room)); - let button = - widgets::IconButton::new(Icon::Ellipsis, &label, "board-zone-menu").show(&mut menu_ui); + let button = widgets::IconButton::new(Icon::Ellipsis, &label, "board-zone-menu").show(&mut menu_ui); let shown = Popup::menu(&button) .frame(widgets::menu_frame(ui.ctx())) .close_behavior(PopupCloseBehavior::CloseOnClickOutside) @@ -378,15 +297,9 @@ fn menu( if held > 0 { #[expect(clippy::cast_possible_truncation, reason = "a zone's cards")] let count = held as u32; - let words = i18n::translate( - language, - keys::folders::SELECT_NOTES, - &[("count", count.into())], - ); - if Button::new(&words, "folder-select-notes") - .show(ui) - .clicked() - { + let words = + i18n::translate(language, keys::folders::SELECT_NOTES, &[("count", count.into())]); + if Button::new(&words, "folder-select-notes").show(ui).clicked() { let ticked = BoardGesture::SelectFolder(folder.id.clone()); actions.push(Action::Notes(crate::notes::Action::Board(ticked))); ui.close(); @@ -408,32 +321,16 @@ fn menu( /// One line of the zone's sub-folders, never wrapped: its height is the one Rust counts in the /// zone's. It scrolls sideways when they do not hold. -fn children( - ui: &mut Ui, - row: Rect, - zone: &BoardZone, - language: i18n::Language, - actions: &mut Actions, -) { +fn children(ui: &mut Ui, row: Rect, zone: &BoardZone, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); - let label = i18n::translate( - language, - keys::board::SUB_FOLDERS, - &[("name", zone.folder.name.as_str().into())], - ); + let label = + i18n::translate(language, keys::board::SUB_FOLDERS, &[("name", zone.folder.name.as_str().into())]); let line = Rect::from_min_max(row.min + vec2(12.0, 0.0), row.max - vec2(12.0, 6.0)); let node = ui.allocate_rect(line, Sense::hover()); node.widget_info(|| WidgetInfo::labeled(Role::Navigation, true, &label)); address(ui, &node, "board-zone-children"); let caption = i18n::translate(language, keys::board::SUB_FOLDERS_LABEL, &[]); - let galley = widgets::text( - ui, - &caption, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &caption, font::META, 400.0, FontFamily::Proportional, p.text_2); let at = pos2(line.left(), line.center().y - galley.size().y / 2.0); let width = galley.size().x; ui.painter().galley(at, galley, p.text_2); @@ -451,9 +348,7 @@ fn children( ui.horizontal_centered(|ui| { for child in &zone.children { if chip(ui, child).clicked() { - actions.push(Action::Notes(crate::notes::Action::ChooseFolder( - child.id.clone(), - ))); + actions.push(Action::Notes(crate::notes::Action::ChooseFolder(child.id.clone()))); } } }); @@ -464,23 +359,9 @@ fn children( fn chip(ui: &mut Ui, child: &BoardChild) -> egui::Response { let p = palette(ui.ctx()); let hue = folder_hue(ui, child.colour); - let name = widgets::text( - ui, - &child.name, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let name = widgets::text(ui, &child.name, font::CONTROL, 400.0, FontFamily::Proportional, p.text_1); let count = child.count.to_string(); - let counted = widgets::text( - ui, - &count, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let counted = widgets::text(ui, &count, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); let width = 8.0 + 7.0 + 6.0 + name.size().x + 6.0 + counted.size().x + 9.0; let corner = CornerRadius::same(radius::PANEL); let response = interact( @@ -493,29 +374,16 @@ fn chip(ui: &mut Ui, child: &BoardChild) -> egui::Response { ); let rect = response.rect; let edge = if response.hovered() { hue } else { p.line }; - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, p.bg_2, Stroke::new(1.0, edge), StrokeKind::Inside); let middle = rect.center().y; let swatch = Rect::from_min_size(pos2(rect.left() + 8.0, middle - 3.5), Vec2::splat(7.0)); - ui.painter() - .rect_filled(swatch, CornerRadius::same(radius::MARK), hue); - let ink = if response.hovered() { - p.text_0 - } else { - p.text_1 - }; + ui.painter().rect_filled(swatch, CornerRadius::same(radius::MARK), hue); + let ink = if response.hovered() { p.text_0 } else { p.text_1 }; let name_at = pos2(swatch.right() + 6.0, middle - name.size().y / 2.0); let name_width = name.size().x; ui.painter().galley(name_at, name, ink); - let count_at = pos2( - name_at.x + name_width + 6.0, - middle - counted.size().y / 2.0, - ); + let count_at = pos2(name_at.x + name_width + 6.0, middle - counted.size().y / 2.0); ui.painter().galley(count_at, counted, p.text_2); response } @@ -533,14 +401,7 @@ fn flow( if notes.is_empty() { let p = palette(ui.ctx()); let words = i18n::translate(context.language, keys::board::EMPTY_ZONE, &[]); - let galley = widgets::text( - ui, - &words, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); let rect = Rect::from_min_size(body.min + Vec2::splat(padding), galley.size()); let response = ui.allocate_rect(rect, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); @@ -548,21 +409,13 @@ fn flow( ui.painter().galley(rect.min, galley, p.text_2); return; } - let columns = usize::try_from(columns_in(drawn.frame.width)) - .unwrap_or(1) - .max(1); + let columns = usize::try_from(columns_in(drawn.frame.width)).unwrap_or(1).max(1); let rows = notes.len().div_ceil(columns); let (width, height, gap) = (px(CARD_WIDTH), context.card_height(), px(GAP)); - #[expect( - clippy::cast_precision_loss, - reason = "a zone holds far under 2²⁴ rows" - )] + #[expect(clippy::cast_precision_loss, reason = "a zone holds far under 2²⁴ rows")] let tall = 2.0 * padding + rows as f32 * (height + gap) - gap; - let mut body_ui = ui.new_child( - UiBuilder::new() - .max_rect(body) - .id_salt(("board-zone-body", &zone.folder.id)), - ); + let mut body_ui = + ui.new_child(UiBuilder::new().max_rect(body).id_salt(("board-zone-body", &zone.folder.id))); body_ui.set_clip_rect(body.intersect(ui.clip_rect())); egui::ScrollArea::vertical() .id_salt(("board-zone-body", &zone.folder.id)) @@ -583,10 +436,7 @@ fn flow( ) }; let requested = canvas_view.request.as_deref(); - if let Some(at) = notes - .iter() - .position(|entry| Some(entry.note.id.as_str()) == requested) - { + if let Some(at) = notes.iter().position(|entry| Some(entry.note.id.as_str()) == requested) { ui.scroll_to_rect(seat(at), None); } let clip = ui.clip_rect(); diff --git a/crates/ui/src/notes/canvas/card/actions.rs b/crates/ui/src/notes/canvas/card/actions.rs index 420b12fcf..491263698 100644 --- a/crates/ui/src/notes/canvas/card/actions.rs +++ b/crates/ui/src/notes/canvas/card/actions.rs @@ -3,9 +3,7 @@ //! edge, clear of its footer and costing it no room. use crate::theme::tokens::{gap, radius}; -use egui::{ - CornerRadius, Id, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Stroke, Ui, Vec2, pos2, -}; +use egui::{CornerRadius, Id, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Stroke, Ui, Vec2, pos2}; use engine::notes::kind::NoteKind; use engine::notes::model::DisplayNote; use engine::notes::priority::Priority; @@ -19,13 +17,8 @@ use crate::theme::icons::Icon; use crate::theme::palette; use crate::widgets::{self, IconButton, MIN_TARGET}; -const LEVELS: [Priority; 5] = [ - Priority::None, - Priority::Low, - Priority::Medium, - Priority::High, - Priority::Urgent, -]; +const LEVELS: [Priority; 5] = + [Priority::None, Priority::Low, Priority::Medium, Priority::High, Priority::Urgent]; fn push(actions: &mut Actions, action: Asked) { actions.push(Action::Notes(action)); @@ -59,11 +52,7 @@ pub(super) fn show( let p = palette(&ctx); let language = context.language; let tr = |key| i18n::translate(language, key, &[]); - let title = if note.title.is_empty() { - tr(keys::notes::UNTITLED) - } else { - note.title.clone() - }; + let title = if note.title.is_empty() { tr(keys::notes::UNTITLED) } else { note.title.clone() }; // ⚠️ In the card's own layer, drawn after its click surface: a pill in an area above it // lost its clicks to that surface. let mut ui = ui.new_child(egui::UiBuilder::new().max_rect(pill).id_salt(here)); @@ -81,11 +70,7 @@ pub(super) fn show( } else { (Icon::Zap, keys::placeholders::TITLE, "note-card-fill") }; - if copies - && IconButton::new(icon, &tr(key), author_id) - .show(ui) - .clicked() - { + if copies && IconButton::new(icon, &tr(key), author_id).show(ui).clicked() { push(actions, Asked::Copy(note.id.clone())); } let label = i18n::translate( @@ -104,24 +89,14 @@ pub(super) fn show( ctx.data_mut(|data| data.insert_temp(here, (drawn, open))); } -fn menu( - ui: &Ui, - trigger: &Response, - note: &DisplayNote, - context: &Context<'_>, - actions: &mut Actions, -) { +fn menu(ui: &Ui, trigger: &Response, note: &DisplayNote, context: &Context<'_>, actions: &mut Actions) { let language = context.language; let tr = |key| i18n::translate(language, key, &[]); let armed_id = trigger.id.with("armed"); - let armed = ui - .data(|data| data.get_temp::(armed_id)) - .unwrap_or(false); + let armed = ui.data(|data| data.get_temp::(armed_id)).unwrap_or(false); // The places take the entries' room: the menu keeps its size whatever the folders are. let moving_id = trigger.id.with("moving"); - let moving = ui - .data(|data| data.get_temp::(moving_id)) - .unwrap_or(false); + let moving = ui.data(|data| data.get_temp::(moving_id)).unwrap_or(false); let shown = Popup::menu(trigger) .frame(widgets::menu_frame(ui.ctx())) .align(RectAlign::BOTTOM_END) @@ -141,14 +116,9 @@ fn menu( ui.data_mut(|data| data.insert_temp(moving_id, true)); } widgets::menu_line(ui); - let delete = tr(if armed { - keys::editor::DELETE_CONFIRM - } else { - keys::editor::DELETE - }); + let delete = tr(if armed { keys::editor::DELETE_CONFIRM } else { keys::editor::DELETE }); let about = (Icon::Trash, None); - let deleted = - widgets::icon_entry(ui, about, &delete, "note-card-delete", (true, false)); + let deleted = widgets::icon_entry(ui, about, &delete, "note-card-delete", (true, false)); if deleted.clicked() { if armed { push(actions, Asked::Delete(id)); @@ -194,50 +164,22 @@ fn first_entries(ui: &mut Ui, note: &DisplayNote, language: i18n::Language, acti let id = note.id.clone(); let plain = (false, false); let open = (Icon::ArrowUpRight, None); - if widgets::icon_entry( - ui, - open, - &tr(keys::notes::OPEN_NOTE), - "note-card-open-menu", - plain, - ) - .clicked() - { + if widgets::icon_entry(ui, open, &tr(keys::notes::OPEN_NOTE), "note-card-open-menu", plain).clicked() { push(actions, Asked::OpenNote(id.clone())); ui.close(); } // What the entry does, not the state the note is in. - let pin = tr(if note.pinned { - keys::selection::UNPIN - } else { - keys::editor::PIN - }); + let pin = tr(if note.pinned { keys::selection::UNPIN } else { keys::editor::PIN }); let p = palette(ui.ctx()); - let mark = if note.pinned { - (Icon::PinFilled, Some(p.red)) - } else { - (Icon::Pin, None) - }; + let mark = if note.pinned { (Icon::PinFilled, Some(p.red)) } else { (Icon::Pin, None) }; if widgets::icon_entry(ui, mark, &pin, "note-card-pin-toggle", plain).clicked() { - push( - actions, - Asked::Pin { - id: id.clone(), - pinned: !note.pinned, - }, - ); + push(actions, Asked::Pin { id: id.clone(), pinned: !note.pinned }); ui.close(); } priority(ui, note, language, actions); if note.kind != NoteKind::Drawing - && widgets::icon_entry( - ui, - (Icon::Copy, None), - &tr(keys::notes::COPY), - "note-card-copy-menu", - plain, - ) - .clicked() + && widgets::icon_entry(ui, (Icon::Copy, None), &tr(keys::notes::COPY), "note-card-copy-menu", plain) + .clicked() { push(actions, Asked::Copy(id.clone())); ui.close(); @@ -254,19 +196,9 @@ fn first_entries(ui: &mut Ui, note: &DisplayNote, language: i18n::Language, acti let copy = if note.title.is_empty() { String::new() } else { - i18n::translate( - language, - keys::notes::COPY_TITLE, - &[("title", note.title.as_str().into())], - ) + i18n::translate(language, keys::notes::COPY_TITLE, &[("title", note.title.as_str().into())]) }; - push( - actions, - Asked::Duplicate { - id: id.clone(), - title: copy, - }, - ); + push(actions, Asked::Duplicate { id: id.clone(), title: copy }); ui.close(); } } @@ -283,8 +215,7 @@ fn priority(ui: &mut Ui, note: &DisplayNote, language: i18n::Language, actions: for level in LEVELS { let name = i18n::translate(language, level_key(level), &[]); let on = level == note.priority; - let entry = - widgets::menu_entry(ui, &name, "note-card-priority-level", false, on, false); + let entry = widgets::menu_entry(ui, &name, "note-card-priority-level", false, on, false); ids.push(entry.id); if entry.clicked() { picked = Some(level); @@ -297,13 +228,7 @@ fn priority(ui: &mut Ui, note: &DisplayNote, language: i18n::Language, actions: return; }; if level != note.priority { - push( - actions, - Asked::Prioritise { - id: note.id.clone(), - priority: level, - }, - ); + push(actions, Asked::Prioritise { id: note.id.clone(), priority: level }); } ui.close(); } @@ -338,9 +263,7 @@ mod tests { /// The pill shows under the pointer: the menu opens from it. fn open_menu(harness: &mut Harness<'_, Bench>) { - harness - .get_by(|node| node.author_id() == Some("note-card-open")) - .hover(); + harness.get_by(|node| node.author_id() == Some("note-card-open")).hover(); settle(harness); click_id(harness, "note-card-menu"); } @@ -428,10 +351,7 @@ mod tests { click_id(&mut harness, "note-card-move"); click(&mut harness, "note-card-move-place", "Work › Scripts"); let moved = stored(&harness, &id); - assert_eq!( - (moved.space_id.clone(), moved.folder_id.clone()), - (work.id, Some(scripts.id)) - ); + assert_eq!((moved.space_id.clone(), moved.folder_id.clone()), (work.id, Some(scripts.id))); let offered = |harness: &Harness<'_, Bench>| -> Vec { harness @@ -443,10 +363,7 @@ mod tests { click_id(&mut harness, "note-card-move"); let first = offered(&harness); assert_eq!(first[0], "No folder"); - assert_eq!( - first[1], "Work", - "its own space first, the place it is in not again" - ); + assert_eq!(first[1], "Work", "its own space first, the place it is in not again"); click(&mut harness, "note-card-move-place", "No folder"); assert_eq!(stored(&harness, &id).folder_id, None); @@ -469,12 +386,7 @@ mod tests { testing::note(&backend, "psql"); let spaces = engine::db::run_here(backend.engine(), engine::spaces::list_spaces).unwrap(); for at in 0..300 { - folder( - &backend, - &spaces[0], - None, - &format!("A folder of a long name, number {at}"), - ); + folder(&backend, &spaces[0], None, &format!("A folder of a long name, number {at}")); } let mut harness = area(backend, profile); @@ -517,13 +429,50 @@ mod tests { testing::note(&backend, "psql"); let mut harness = area(backend, profile); - harness - .get_by(|node| node.author_id() == Some("note-card-open")) - .hover(); + harness.get_by(|node| node.author_id() == Some("note-card-open")).hover(); settle(&mut harness); click_id(&mut harness, "note-card-copy"); let (_, said) = harness.state().state.status.latest().unwrap(); assert_eq!(said.key, i18n::keys::notes::COPIED_NOTE); } + + #[test] + fn the_menu_opens_the_note_and_copies_it() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql"); + let mut harness = area(backend, profile); + open_menu(&mut harness); + click_id(&mut harness, "note-card-copy-menu"); + crate::notes::bench::until(&mut harness, "it is copied", |harness| { + harness.state().state.status.latest().is_some() + }); + + open_menu(&mut harness); + click_id(&mut harness, "note-card-open-menu"); + assert!(harness.state().state.editor.is_open()); + } + + /// A copy of a note with no title has none either, and its options still say whose they are. + #[test] + fn a_note_with_no_title_is_duplicated_without_one() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let patch = engine::notes::model::NotePatch { + title: Some(String::new()), + content: Some("select 1".to_owned()), + ..Default::default() + }; + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &id, &patch)) + .unwrap(); + let mut harness = area(backend, profile); + open_menu(&mut harness); + let menu = harness.get_by(|node| node.author_id() == Some("note-card-menu")); + assert!(menu.accesskit_node().label().unwrap_or_default().contains("Untitled")); + click_id(&mut harness, "note-card-duplicate"); + + let view = harness.state().state.notes_query.view().unwrap(); + let titles: Vec<&str> = view.cards().map(|card| card.title.as_str()).collect(); + assert_eq!(titles, ["", ""]); + } } diff --git a/crates/ui/src/notes/canvas/card/bands.rs b/crates/ui/src/notes/canvas/card/bands.rs index bbc96e11f..befddf877 100644 --- a/crates/ui/src/notes/canvas/card/bands.rs +++ b/crates/ui/src/notes/canvas/card/bands.rs @@ -4,9 +4,7 @@ //! right its fields to fill, its attachments, and when it changed. Neither is ever empty. use crate::theme::tokens::{gap, radius}; -use egui::{ - Color32, CornerRadius, Rect, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2, -}; +use egui::{Color32, CornerRadius, Rect, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use engine::notes::model::{DisplayNote, NoteFooter}; use i18n::{Message, keys}; @@ -29,23 +27,9 @@ pub(super) fn frame(ui: &Ui, (top, bottom): (Rect, Rect), hovered: bool, armed: let p = palette(ui.ctx()); let painter = ui.painter(); if hovered { - painter.rect_filled( - top, - CornerRadius { - nw: 9, - ne: 9, - sw: 0, - se: 0, - }, - p.bg_3, - ); + painter.rect_filled(top, CornerRadius { nw: 9, ne: 9, sw: 0, se: 0 }, p.bg_3); } - let corner = CornerRadius { - nw: 0, - ne: 0, - sw: 9, - se: 9, - }; + let corner = CornerRadius { nw: 0, ne: 0, sw: 9, se: 9 }; if armed { painter.rect_filled(bottom, corner, p.red.gamma_multiply(0.12)); } else if hovered { @@ -103,14 +87,7 @@ pub(super) fn top( /// An icon and its count, named by what they count. fn counted(ui: &mut Ui, (icon, ink): (Icon, Color32), count: u32, words: &str, author_id: &str) { - let figure = galley( - ui, - &count.to_string(), - &Font::mono(10.0, 1.2), - ink, - f32::INFINITY, - 1, - ); + let figure = galley(ui, &count.to_string(), &Font::mono(10.0, 1.2), ink, f32::INFINITY, 1); let size = vec2(12.0 + 3.0 + figure.size().x, 12.0); let (rect, _) = ui.allocate_exact_size(size, Sense::hover()); label(ui, rect, words, author_id); @@ -138,11 +115,7 @@ fn tick( language: i18n::Language, ) -> (f32, bool) { let p = palette(ui.ctx()); - let label = i18n::translate( - language, - keys::notes::SELECT_NOTE, - &[("title", title.into())], - ); + let label = i18n::translate(language, keys::notes::SELECT_NOTE, &[("title", title.into())]); let target = Rect::from_min_size( pos2(band.left() + gap::LINE, band.center().y - MIN_TARGET / 2.0), egui::Vec2::splat(MIN_TARGET), @@ -164,11 +137,7 @@ fn tick( ); icons::paint(ui, square.shrink(2.0), Icon::Check, p.amber_ink); } else { - let edge = if lit || response.hovered() { - p.text_2 - } else { - p.text_2.gamma_multiply(0.55) - }; + let edge = if lit || response.hovered() { p.text_2 } else { p.text_2.gamma_multiply(0.55) }; tick_box(ui, square, false, edge); } (target.right(), response.clicked()) @@ -188,35 +157,15 @@ pub(super) fn bottom(ui: &mut Ui, band: Rect, note: &DisplayNote, context: &Cont date(&mut right, note, context); if note.attachment_count > 0 { let count = note.attachment_count; - let words = i18n::translate( - language, - keys::notes::ATTACHMENTS_COUNT, - &[("count", count.into())], - ); + let words = i18n::translate(language, keys::notes::ATTACHMENTS_COUNT, &[("count", count.into())]); let ink = p.text_2; - counted( - &mut right, - (Icon::Paperclip, ink), - count, - &words, - "note-card-clip", - ); + counted(&mut right, (Icon::Paperclip, ink), count, &words, "note-card-clip"); } if !note.placeholders.is_empty() { let count = u32::try_from(note.placeholders.len()).unwrap_or(u32::MAX); - let words = i18n::translate( - language, - keys::notes::PLACEHOLDERS_COUNT, - &[("count", count.into())], - ); + let words = i18n::translate(language, keys::notes::PLACEHOLDERS_COUNT, &[("count", count.into())]); let ink = p.amber_text; - counted( - &mut right, - (Icon::Zap, ink), - count, - &words, - "note-card-fields", - ); + counted(&mut right, (Icon::Zap, ink), count, &words, "note-card-fields"); } let room = (right.min_rect().left() - GAP - inner.left()).max(0.0); if let Some(place) = place_of(ui, note, context) { @@ -230,10 +179,7 @@ fn date(ui: &mut Ui, note: &DisplayNote, context: &Context<'_>) { let (short, long) = when(ui, note, context); let ink = if note.expiring_soon { p.red } else { p.text_2 }; let weight = if note.expiring_soon { 600.0 } else { 400.0 }; - let font = Font { - weight, - ..Font::mono(10.0, 1.2) - }; + let font = Font { weight, ..Font::mono(10.0, 1.2) }; let shown = galley(ui, &short, &font, ink, f32::INFINITY, 1); let (rect, _) = ui.allocate_exact_size(shown.size(), Sense::hover()); text_at(ui, rect.min, shown, &long, "note-card-when"); @@ -245,14 +191,7 @@ pub(super) fn arming(ui: &mut Ui, band: Rect, language: i18n::Language) { let p = palette(ui.ctx()); let words = i18n::translate(language, keys::notes::DELETE_ARMED, &[]); let inner = band.shrink2(vec2(INSET, 0.0)); - let shown = galley( - ui, - &words, - &Font::proportional(10.0, 600.0, 1.2), - p.red, - inner.width(), - 1, - ); + let shown = galley(ui, &words, &Font::proportional(10.0, 600.0, 1.2), p.red, inner.width(), 1); let at = pos2(inner.left(), band.center().y - shown.size().y / 2.0); text_at(ui, at, shown, &words, "note-card-arming"); } @@ -264,16 +203,13 @@ fn when(ui: &Ui, note: &DisplayNote, context: &Context<'_>) -> (String, String) let now = context.clock.now(); match ¬e.footer { NoteFooter::Expiry { at } => { - ui.ctx() - .request_repaint_after(std::time::Duration::from_mins(1)); + ui.ctx().request_repaint_after(std::time::Duration::from_mins(1)); let short = i18n::time::short_expiry(*at, now, &chrono::Local); let long = i18n::time::expiry(*at, now, &chrono::Local); (tr(&short), tr(&long)) } // The source is the editor's to show: a card's corner says when. - NoteFooter::Source { .. } => { - aged(ui, note.updated_at, keys::notes::footer::MODIFIED, context) - } + NoteFooter::Source { .. } => aged(ui, note.updated_at, keys::notes::footer::MODIFIED, context), NoteFooter::Age { at } => aged(ui, *at, keys::notes::footer::MODIFIED, context), NoteFooter::Created { at } => aged(ui, *at, keys::notes::footer::CREATED, context), } @@ -288,11 +224,7 @@ fn aged( let (label, wait) = time::relative(at, context.clock); ui.ctx().request_repaint_after(wait); let short = i18n::time::short(at, context.clock.now()).text(context.language); - let long = format!( - "{} {}", - i18n::translate(context.language, prefix, &[]), - label.text(context.language) - ); + let long = format!("{} {}", i18n::translate(context.language, prefix, &[]), label.text(context.language)); (short, long) } @@ -333,12 +265,7 @@ fn place_of(ui: &Ui, note: &DisplayNote, context: &Context<'_>) -> Option if note.folder_id.is_some() { return None; } - space.map(|name| Place { - words: name.clone(), - hue: None, - path: name, - author_id: "note-card-space", - }) + space.map(|name| Place { words: name.clone(), hue: None, path: name, author_id: "note-card-space" }) } fn place_font() -> Font { @@ -352,8 +279,7 @@ fn draw_place(ui: &mut Ui, place: &Place, left_middle: egui::Pos2, room: f32) -> let middle = left_middle.y; if let Some(hue) = place.hue { let swatch = Rect::from_center_size(pos2(left + 3.5, middle), vec2(7.0, 7.0)); - ui.painter() - .rect_filled(swatch, CornerRadius::same(radius::MARK), hue); + ui.painter().rect_filled(swatch, CornerRadius::same(radius::MARK), hue); left = swatch.right() + 5.0; } let width = (room - (left - left_middle.x)).max(1.0); diff --git a/crates/ui/src/notes/canvas/card/body.rs b/crates/ui/src/notes/canvas/card/body.rs index e40691bae..7ebda6b8e 100644 --- a/crates/ui/src/notes/canvas/card/body.rs +++ b/crates/ui/src/notes/canvas/card/body.rs @@ -4,9 +4,7 @@ //! found, when that is not code. use crate::theme::tokens::{gap, radius}; -use egui::{ - Color32, CornerRadius, Rect, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2, -}; +use egui::{Color32, CornerRadius, Rect, Role, Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2}; use engine::notes::checklist::ChecklistItem; use engine::notes::kind::NoteKind; use engine::notes::model::{DisplayNote, OutlineLine}; @@ -151,11 +149,7 @@ fn prose(ui: &mut Ui, rect: Rect, (words, lines): (&str, usize), tag: bool, auth } fn rows_in(height: f32, line: f32) -> usize { - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "floored" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "floored")] let rows = (height / line).floor().max(1.0) as usize; rows } @@ -170,31 +164,15 @@ fn outline(ui: &mut Ui, rect: Rect, lines: &[OutlineLine], count: usize) { let mut top = rect.top(); for line in lines { let (font, colour, marker, depth, text) = match line { - OutlineLine::Heading { text } => ( - Font::proportional(12.0, 600.0, 17.0 / 12.0), - p.text_0, - None, - 0, - text, - ), - OutlineLine::Text { text } => ( - Font::proportional(12.0, 400.0, 17.0 / 12.0), - p.text_1, - None, - 0, - text, - ), - OutlineLine::Item { - text, - depth, - marker, - } => ( - Font::proportional(12.0, 400.0, 17.0 / 12.0), - p.text_1, - Some(marker.clone()), - *depth, - text, - ), + OutlineLine::Heading { text } => { + (Font::proportional(12.0, 600.0, 17.0 / 12.0), p.text_0, None, 0, text) + } + OutlineLine::Text { text } => { + (Font::proportional(12.0, 400.0, 17.0 / 12.0), p.text_1, None, 0, text) + } + OutlineLine::Item { text, depth, marker } => { + (Font::proportional(12.0, 400.0, 17.0 / 12.0), p.text_1, Some(marker.clone()), *depth, text) + } OutlineLine::Task { text, depth, done } => { let marker = if *done { TICKED } else { UNTICKED }; ( @@ -212,21 +190,14 @@ fn outline(ui: &mut Ui, rect: Rect, lines: &[OutlineLine], count: usize) { } #[expect(clippy::cast_precision_loss, reason = "a nesting depth")] let mut left = rect.left() + depth as f32 * 12.0; - if let Some(marker) = marker - .as_deref() - .filter(|marker| [TICKED, UNTICKED].contains(marker)) - { - let at = Rect::from_min_size( - pos2(left, top + (font.height() - 11.0) / 2.0), - vec2(11.0, 11.0), - ); + if let Some(marker) = marker.as_deref().filter(|marker| [TICKED, UNTICKED].contains(marker)) { + let at = Rect::from_min_size(pos2(left, top + (font.height() - 11.0) / 2.0), vec2(11.0, 11.0)); tick_box(ui, at, marker == TICKED, p.purple); left += 11.0 + 6.0; } else if let Some(marker) = marker { let shown = galley(ui, &marker, &font, p.purple, f32::INFINITY, 1); let width = shown.size().x; - ui.painter() - .galley(pos2(left, top), shown, Color32::TRANSPARENT); + ui.painter().galley(pos2(left, top), shown, Color32::TRANSPARENT); left += width + 6.0; } let shown = galley(ui, text, &font, colour, rect.right() - left, 1); @@ -261,24 +232,16 @@ fn calc_lines(ui: &mut Ui, rect: Rect, (note, lines): (&DisplayNote, usize), for break; } if line.aggregate { - ui.painter() - .hline(rect.x_range(), top + 0.5, Stroke::new(1.0, p.line)); + ui.painter().hline(rect.x_range(), top + 0.5, Stroke::new(1.0, p.line)); top += 2.0; } let written = calc::value(&line.value, line.places, format); - let result = if written.approx { - format!("≈ {}", written.text) - } else { - written.text - }; + let result = if written.approx { format!("≈ {}", written.text) } else { written.text }; let weight = if line.aggregate { 700.0 } else { 400.0 }; let result = galley( ui, &result, - &Font { - weight, - ..Font::mono(11.0, 16.0 / 11.0) - }, + &Font { weight, ..Font::mono(11.0, 16.0 / 11.0) }, p.text_0, f32::INFINITY, 1, @@ -287,21 +250,13 @@ fn calc_lines(ui: &mut Ui, rect: Rect, (note, lines): (&DisplayNote, usize), for let expression = galley(ui, &line.expression, &font, p.text_2, room, 1); let row = Rect::from_min_size(pos2(rect.left(), top), vec2(rect.width(), font.height())); covered = covered.union(row); + ui.painter().galley(row.min, expression, Color32::TRANSPARENT); ui.painter() - .galley(row.min, expression, Color32::TRANSPARENT); - ui.painter().galley( - pos2(row.right() - result.size().x, top), - result, - Color32::TRANSPARENT, - ); + .galley(pos2(row.right() - result.size().x, top), result, Color32::TRANSPARENT); top += font.height(); } if covered.is_positive() { - let words: Vec<&str> = note - .calc - .iter() - .map(|line| line.expression.as_str()) - .collect(); + let words: Vec<&str> = note.calc.iter().map(|line| line.expression.as_str()).collect(); label(ui, covered, &words.join("\n"), "note-card-calc"); } } @@ -323,11 +278,7 @@ fn checklist( // and keeps as many tasks as before it had a progress strip. let rect = rect.expand2(vec2(0.0, super::GAP)); let strip = Rect::from_min_size(rect.min, vec2(rect.width(), PROGRESS_HEIGHT)); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a few rows of a card" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a few rows of a card")] let fits = ((rect.height() - PROGRESS_HEIGHT + 0.5) / ITEM_HEIGHT).max(0.0) as usize; let seats = seats(note, rows.min(fits)); progress(ui, strip, items, items.len() - seats.len(), language); @@ -337,10 +288,8 @@ fn checklist( if item(ui, row, &items[at], language) { let mut ticked = items.clone(); ticked[at].done = !ticked[at].done; - actions.push(Action::Notes(crate::notes::Action::SetItems { - id: note.id.clone(), - items: ticked, - })); + actions + .push(Action::Notes(crate::notes::Action::SetItems { id: note.id.clone(), items: ticked })); } top += ITEM_HEIGHT; } @@ -348,24 +297,15 @@ fn checklist( /// A bar filled to the share of tasks done, « done/total » at its right, and « +n » for the tasks /// the card has no row for. -fn progress( - ui: &mut Ui, - strip: Rect, - items: &[ChecklistItem], - hidden: usize, - language: i18n::Language, -) { +fn progress(ui: &mut Ui, strip: Rect, items: &[ChecklistItem], hidden: usize, language: i18n::Language) { let p = palette(ui.ctx()); let count = |n: usize| u32::try_from(n).unwrap_or(u32::MAX); let done = items.iter().filter(|item| item.done).count(); let middle = strip.center().y; let mut right = strip.right(); if hidden > 0 { - let words = i18n::translate( - language, - keys::notes::CHECKLIST_MORE, - &[("count", count(hidden).into())], - ); + let words = + i18n::translate(language, keys::notes::CHECKLIST_MORE, &[("count", count(hidden).into())]); let font = Font::proportional(9.5, 400.0, 1.2); let shown = galley(ui, &words, &font, p.text_2, f32::INFINITY, 1); right -= shown.size().x; @@ -376,15 +316,9 @@ fn progress( let words = i18n::translate( language, keys::notes::CHECKLIST_PROGRESS, - &[ - ("done", count(done).into()), - ("total", count(items.len()).into()), - ], + &[("done", count(done).into()), ("total", count(items.len()).into())], ); - let font = Font { - weight: 600.0, - ..Font::mono(9.5, 1.2) - }; + let font = Font { weight: 600.0, ..Font::mono(9.5, 1.2) }; let shown = galley(ui, &words, &font, p.text_2, f32::INFINITY, 1); right -= shown.size().x; let at = pos2(right, middle - shown.size().y / 2.0); @@ -406,14 +340,10 @@ fn progress( /// Which items a card shows, in the note's order: the one a search found, then the first /// ones left to do, then the last ones — the top of a finished list says the least. -fn seats(note: &DisplayNote, count: usize) -> Vec { +pub(super) fn seats(note: &DisplayNote, count: usize) -> Vec { let items = ¬e.items; let mut seats = Vec::new(); - if let Some(hit) = note - .search_hit - .as_ref() - .filter(|hit| hit.field == SearchField::Item) - { + if let Some(hit) = note.search_hit.as_ref().filter(|hit| hit.field == SearchField::Item) { let needle = hit.excerpt.strip_suffix('…').unwrap_or(&hit.excerpt); if let Some(at) = items.iter().position(|item| item.text.starts_with(needle)) { seats.push(at); @@ -442,11 +372,8 @@ fn seats(note: &DisplayNote, count: usize) -> Vec { /// One item, a checkbox of its own. `true` when it was clicked. fn item(ui: &mut Ui, row: Rect, item: &ChecklistItem, language: i18n::Language) -> bool { let p = palette(ui.ctx()); - let name = i18n::translate( - language, - keys::notes::CHECKLIST_TOGGLE, - &[("text", item.text.as_str().into())], - ); + let name = + i18n::translate(language, keys::notes::CHECKLIST_TOGGLE, &[("text", item.text.as_str().into())]); let mut row_ui = ui.new_child(UiBuilder::new().max_rect(row)); let done = item.done; let response = interact( @@ -457,18 +384,11 @@ fn item(ui: &mut Ui, row: Rect, item: &ChecklistItem, language: i18n::Language) || WidgetInfo::selected(Role::CheckBox, true, done, &name), CornerRadius::same(radius::TAG), ); - let ink = if response.hovered() { - p.text_1 - } else { - p.text_2 - }; + let ink = if response.hovered() { p.text_1 } else { p.text_2 }; let box_ink = if done { p.amber_text } else { ink }; let left = row.left() + 10.0 + 6.0; - let mut format = Font::proportional(11.0, 400.0, 1.5).format(if done { - ink.gamma_multiply(0.6) - } else { - ink - }); + let mut format = + Font::proportional(11.0, 400.0, 1.5).format(if done { ink.gamma_multiply(0.6) } else { ink }); if done { format.strikethrough = Stroke::new(1.0, ink.gamma_multiply(0.6)); } @@ -483,27 +403,15 @@ fn item(ui: &mut Ui, row: Rect, item: &ChecklistItem, language: i18n::Language) let middle = row.center().y; let tick = Rect::from_center_size(pos2(row.left() + 5.0, middle), vec2(10.0, 10.0)); tick_box(ui, tick, done, box_ink); - ui.painter().galley( - pos2(left, middle - text.size().y / 2.0), - text, - Color32::TRANSPARENT, - ); + ui.painter() + .galley(pos2(left, middle - text.size().y / 2.0), text, Color32::TRANSPARENT); response.clicked() } /// The picture, whole in the card's room: a sketch, not a crop of one. Asked for the first time /// the card is drawn. -fn drawing( - ui: &mut Ui, - rect: Rect, - note: &DisplayNote, - context: &Context<'_>, - actions: &mut Actions, -) { - let stamp = Stamp { - id: note.id.clone(), - updated_at: note.updated_at, - }; +fn drawing(ui: &mut Ui, rect: Rect, note: &DisplayNote, context: &Context<'_>, actions: &mut Actions) { + let stamp = Stamp { id: note.id.clone(), updated_at: note.updated_at }; let says = |ui: &mut Ui, key| { let words = i18n::translate(context.language, key, &[]); prose(ui, rect, (&words, 1), false, "note-card-drawing-empty"); diff --git a/crates/ui/src/notes/canvas/card/mod.rs b/crates/ui/src/notes/canvas/card/mod.rs index eb88adcfd..eb02d1986 100644 --- a/crates/ui/src/notes/canvas/card/mod.rs +++ b/crates/ui/src/notes/canvas/card/mod.rs @@ -11,8 +11,8 @@ use std::sync::Arc; use egui::text::{LayoutJob, TextFormat, TextWrapping}; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Role, Sense, Stroke, StrokeKind, - Ui, WidgetInfo, pos2, vec2, + Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Role, Sense, Stroke, StrokeKind, Ui, + WidgetInfo, pos2, vec2, }; use engine::folders::board::PreviewLines; use engine::notes::model::DisplayNote; @@ -94,15 +94,9 @@ pub(super) fn show( // after it, a task's box, takes the click first. // ⚠️ Named after the note, not its place: the focus follows a card the list moves. Its layer // too: the silhouette of a drag is the same card, drawn above. - #[expect( - clippy::disallowed_methods, - reason = "named and addressed just below, as the card" - )] - let open = ui.interact( - rect, - egui::Id::unique(("note-card-open", ¬e.id)).with(ui.layer_id()), - Sense::click(), - ); + #[expect(clippy::disallowed_methods, reason = "named and addressed just below, as the card")] + let open = + ui.interact(rect, egui::Id::unique(("note-card-open", ¬e.id)).with(ui.layer_id()), Sense::click()); open.widget_info(|| WidgetInfo::labeled(Role::Button, true, &title)); address(ui, &open, "note-card-open"); crate::theme::focus::ring(ui, &open, CornerRadius::same(radius::CARD)); @@ -115,12 +109,8 @@ pub(super) fn show( if crate::widgets::takes_keys(ui, &open) { canvas_view.focused = Some(note.id.clone()); // The arrows and Escape are the canvas's table's: egui would move the focus itself. - let kept = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, - escape: true, - ..egui::EventFilter::default() - }; + crate::widgets::keep_arrows(ui, &open); + let kept = egui::EventFilter { escape: true, ..egui::EventFilter::default() }; ui.memory_mut(|memory| memory.set_focus_lock_filter(open.id, kept)); } if open.clicked() { @@ -159,16 +149,11 @@ pub(super) fn show( let inner = rect.shrink(1.0); let top = Rect::from_min_size(inner.min, vec2(inner.width(), bands::TOP_HEIGHT)); - let bottom = Rect::from_min_max( - pos2(inner.left(), inner.bottom() - bands::BOTTOM_HEIGHT), - inner.max, - ); + let bottom = Rect::from_min_max(pos2(inner.left(), inner.bottom() - bands::BOTTOM_HEIGHT), inner.max); bands::frame(ui, (top, bottom), hovered, armed); let lit = hovered || context.selecting; if bands::top(ui, top, (note, &title), context, (checked, lit)) { - actions.push(crate::action::Action::Notes(crate::notes::Action::Check( - note.id.clone(), - ))); + actions.push(crate::action::Action::Notes(crate::notes::Action::Check(note.id.clone()))); } let inset = spacing(ui.ctx()).card.min(12.0); let room = Rect::from_min_max( @@ -191,10 +176,7 @@ fn clicked(ui: &Ui, note: &DisplayNote, canvas_view: &super::CanvasView, actions let asked = if modifiers.command { crate::notes::Action::Check(id) } else if modifiers.shift { - crate::notes::Action::CheckRange { - id, - anchor: canvas_view.anchor.clone(), - } + crate::notes::Action::CheckRange { id, anchor: canvas_view.anchor.clone() } } else { crate::notes::Action::OpenNote(id) }; @@ -211,21 +193,11 @@ pub(super) struct Font { impl Font { pub(super) fn proportional(size: f32, weight: f32, line: f32) -> Self { - Self { - size, - weight, - family: FontFamily::Proportional, - line, - } + Self { size, weight, family: FontFamily::Proportional, line } } pub(super) fn mono(size: f32, line: f32) -> Self { - Self { - size, - weight: 400.0, - family: FontFamily::Monospace, - line, - } + Self { size, weight: 400.0, family: FontFamily::Monospace, line } } pub(super) fn height(&self) -> f32 { @@ -270,13 +242,7 @@ pub(super) fn label(ui: &mut Ui, rect: Rect, words: &str, author_id: &str) { } /// `galley` drawn at `at`, and its node. -pub(super) fn text_at( - ui: &mut Ui, - at: Pos2, - galley: Arc, - words: &str, - author_id: &str, -) -> Rect { +pub(super) fn text_at(ui: &mut Ui, at: Pos2, galley: Arc, words: &str, author_id: &str) -> Rect { let rect = Rect::from_min_size(at, galley.size()); label(ui, rect, words, author_id); ui.painter().galley(at, galley, Color32::TRANSPARENT); diff --git a/crates/ui/src/notes/canvas/card/tests.rs b/crates/ui/src/notes/canvas/card/tests.rs index d4dfb81e8..58d1bfc7e 100644 --- a/crates/ui/src/notes/canvas/card/tests.rs +++ b/crates/ui/src/notes/canvas/card/tests.rs @@ -61,9 +61,7 @@ fn a_snippet_shows_its_first_lines_its_language_and_its_marks() { assert_eq!(label(&harness, "note-card-fields"), "1 field to fill"); assert!(label(&harness, "note-card-when").starts_with("modified")); assert!( - harness - .query_by(|node| node.author_id() == Some("note-card-tags")) - .is_none(), + harness.query_by(|node| node.author_id() == Some("note-card-tags")).is_none(), "a card shows no tag" ); } @@ -84,22 +82,13 @@ fn a_card_reads_in_three_bands_top_to_bottom() { let rect = |author_id| node(&harness, author_id).rect(); let (icon, title) = (rect("kind-icon"), rect("note-card-title")); let (preview, when) = (rect("note-card-snippet"), rect("note-card-when")); - assert!( - (icon.center().y - title.center().y).abs() < 1.0, - "{icon:?} {title:?}" - ); + assert!((icon.center().y - title.center().y).abs() < 1.0, "{icon:?} {title:?}"); let format = rect("note-format"); assert!(icon.right() < format.left() && format.right() < title.left()); - assert!( - (format.center().y - title.center().y).abs() < 1.0, - "{format:?}" - ); + assert!((format.center().y - title.center().y).abs() < 1.0, "{format:?}"); assert!(title.bottom() <= preview.top() && preview.bottom() <= when.top()); let fields = rect("note-card-fields"); - assert!( - (fields.center().y - when.center().y).abs() < 1.0, - "{fields:?}" - ); + assert!((fields.center().y - when.center().y).abs() < 1.0, "{fields:?}"); assert!(fields.right() <= when.left()); assert!(card.contains_rect(icon) && card.contains_rect(when)); } @@ -116,11 +105,7 @@ fn only_a_snippet_has_a_format() { let harness = canvas(backend, profile); assert_eq!(label(&harness, "kind-icon"), "Note"); - assert!( - harness - .query_by(|node| node.author_id() == Some("note-format")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("note-format")).is_none()); } /// Never « Untitled » on the card: the icon stands alone in its title bar. @@ -133,11 +118,7 @@ fn an_untitled_card_writes_no_title() { let harness = canvas(backend, profile); - assert!( - harness - .query_by(|node| node.author_id() == Some("note-card-title")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("note-card-title")).is_none()); assert_eq!(label(&harness, "note-card-open"), "Untitled"); } @@ -152,11 +133,9 @@ fn the_card_follows_the_librarys_preview_lines() { }); let mut harness = canvas(backend, profile); - for (lines, height) in [ - (PreviewLines::Three, 120.0), - (PreviewLines::Four, 140.0), - (PreviewLines::Five, 160.0), - ] { + for (lines, height) in + [(PreviewLines::Three, 120.0), (PreviewLines::Four, 140.0), (PreviewLines::Five, 160.0)] + { harness.state_mut().state.preview_lines = lines; harness.run(); let card = node(&harness, "note-card").rect().height(); @@ -189,10 +168,7 @@ fn a_note_shows_its_outline() { let harness = canvas(backend, profile); - assert_eq!( - label(&harness, "note-card-outline"), - "Deploy\n• build\n☑ ship" - ); + assert_eq!(label(&harness, "note-card-outline"), "Deploy\n• build\n☑ ship"); assert_eq!(label(&harness, "kind-icon"), "Note"); } @@ -201,10 +177,7 @@ fn a_note_shows_its_outline() { fn a_task_lists_card_shows_a_bar_filled_to_its_share_done() { let (backend, profile) = testing::unlocked(); let items: Vec = (0..6) - .map(|at| ChecklistItem { - text: format!("task {at}"), - done: at < 5, - }) + .map(|at| ChecklistItem { text: format!("task {at}"), done: at < 5 }) .collect(); write(&backend, move |draft| { draft.kind = NoteKind::Checklist; @@ -260,10 +233,7 @@ fn an_empty_task_list_draws_no_bar() { #[test] fn an_item_ticked_on_its_card_is_written_and_shown_done() { let (backend, profile) = testing::unlocked(); - let items = ["milk", "bread", "eggs"].map(|text| ChecklistItem { - text: text.into(), - done: false, - }); + let items = ["milk", "bread", "eggs"].map(|text| ChecklistItem { text: text.into(), done: false }); let id = write(&backend, move |draft| { draft.kind = NoteKind::Checklist; draft.title = "shopping".into(); @@ -274,11 +244,7 @@ fn an_item_ticked_on_its_card_is_written_and_shown_done() { // Four lines: the progress strip, then the three tasks, as many as before the strip. let shown = harness.query_all_by(|node| node.author_id() == Some("note-card-item")); assert_eq!(shown.count(), 3); - assert!( - harness - .query_by(|node| node.author_id() == Some("note-card-more")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("note-card-more")).is_none()); harness .get_all_by(|node| node.author_id() == Some("note-card-item")) @@ -326,8 +292,7 @@ fn a_sheet_with_a_short_date_before_an_accent_is_listed() { fn a_priority_is_its_bars_in_the_top_band() { let (backend, profile) = testing::unlocked(); let id = write(&backend, |draft| draft.title = "urgent fix".into()); - let mut set = - backend.db(move |engine| engine::notes::set_priority(engine, &[id], Priority::Urgent)); + let mut set = backend.db(move |engine| engine::notes::set_priority(engine, &[id], Priority::Urgent)); backend.settle(); set.poll().unwrap().unwrap(); @@ -335,10 +300,7 @@ fn a_priority_is_its_bars_in_the_top_band() { assert_eq!(label(&harness, "priority-bars"), "Urgent"); let bars = node(&harness, "priority-bars").rect(); - assert!( - bars.width() > 20.0, - "« Urgent » is written beside its bars: {bars:?}" - ); + assert!(bars.width() > 20.0, "« Urgent » is written beside its bars: {bars:?}"); let title = node(&harness, "note-card-title").rect(); assert!((bars.center().y - title.center().y).abs() < 1.0); assert!(title.right() <= bars.left()); @@ -386,15 +348,8 @@ fn an_armed_cards_bottom_band_says_both_keys() { harness.state_mut().state.selection.arm(&id); harness.run(); - assert_eq!( - label(&harness, "note-card-arming"), - "Del again · Esc to cancel" - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("note-card-when")) - .is_none() - ); + assert_eq!(label(&harness, "note-card-arming"), "Del again · Esc to cancel"); + assert!(harness.query_by(|node| node.author_id() == Some("note-card-when")).is_none()); } #[test] @@ -413,15 +368,9 @@ fn a_drawing_shows_its_picture_once_decoded() { let mut writer = encoder.write_header().unwrap(); writer.write_image_data(&[200; 4 * 2 * 4]).unwrap(); } - let uri = format!( - "data:image/png;base64,{}", - base64::engine::general_purpose::STANDARD.encode(bytes) - ); + let uri = format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)); let patch = NotePatch { - pictures: Some(engine::notes::drawing::DrawingPictures { - thumbnail: uri.clone(), - picture: uri, - }), + pictures: Some(engine::notes::drawing::DrawingPictures { thumbnail: uri.clone(), picture: uri }), ..NotePatch::default() }; let mut written = backend.db(move |engine| engine::notes::update_note(engine, &id, &patch)); @@ -433,12 +382,11 @@ fn a_drawing_shows_its_picture_once_decoded() { node(&harness, "note-card-drawing"); } -const SCENE: &str = r#"{"version":1,"scene":{"objects":[{"type":"Rect","left":60,"top":45,"width":100,"height":50}]}}"#; +const SCENE: &str = + r#"{"version":1,"scene":{"objects":[{"type":"Rect","left":60,"top":45,"width":100,"height":50}]}}"#; fn count(harness: &Harness<'_, Bench>, author_id: &str) -> usize { - harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .count() + harness.query_all_by(|node| node.author_id() == Some(author_id)).count() } /// As an import leaves them: a scene, and no picture taken of it. @@ -461,10 +409,7 @@ fn a_drawing_with_no_picture_yet_has_one_taken_once_its_card_is_drawn() { assert!(count(&harness, "note-card-drawing") > 5); assert_eq!(count(&harness, "note-card-drawing-empty"), 0); let backend = &harness.state().backend; - let kept = ids - .iter() - .filter(|id| thumbnail(backend, id).is_some()) - .count(); + let kept = ids.iter().filter(|id| thumbnail(backend, id).is_some()).count(); assert_eq!( kept, count(&harness, "note-card-drawing"), @@ -490,16 +435,104 @@ fn a_drawing_with_nothing_on_it_says_so() { fn stored(backend: &crate::backend::Backend, id: &str) -> engine::notes::model::DisplayNote { let id = id.to_owned(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() + engine::db::run_here(backend.engine(), move |engine| engine::notes::get_note(engine, &id)).unwrap() } fn thumbnail(backend: &crate::backend::Backend, id: &str) -> Option { let id = id.to_owned(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::drawing_thumbnail(engine, &id) - }) - .unwrap() + engine::db::run_here(backend.engine(), move |engine| engine::notes::drawing_thumbnail(engine, &id)) + .unwrap() +} + +/// A card's corner says when, whatever the footer is of. +#[test] +fn the_corner_says_when_the_note_was_created_once_sorted_by_it() { + use crate::state::notes_query::{Arrangement, natural_order}; + use engine::notes::view::SortKey; + + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| draft.title = "psql".into()); + let mut harness = canvas(backend, profile); + let said = |harness: &Harness<'_, Bench>| label(harness, "note-card-when"); + assert!( + said(&harness).starts_with("Modified") || said(&harness).starts_with("modified"), + "{}", + said(&harness) + ); + let bench = harness.state_mut(); + let arrangement = + Arrangement { order: natural_order(SortKey::Created), ..bench.state.notes_query.arrangement() }; + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + + assert!(said(&harness).to_lowercase().starts_with("created"), "{}", said(&harness)); +} + +/// The one a search found, what is left to do, then the last done. +#[test] +fn a_list_shows_what_is_left_to_do_first_and_what_was_found_always() { + use engine::notes::view::{SearchField, SearchHit}; + + let (backend, _profile) = testing::unlocked(); + let item = |text: &str, done| ChecklistItem { text: text.to_owned(), done }; + let id = write(&backend, move |draft| { + draft.kind = NoteKind::Checklist; + draft.items = + vec![item("a", true), item("b", false), item("c", true), item("d", false), item("e", true)]; + }); + let mut note = + engine::db::run_here(backend.engine(), move |engine| engine::notes::get_note(engine, &id)).unwrap(); + for (count, seats) in + [(1, vec![1]), (2, vec![1, 3]), (3, vec![1, 3, 4]), (4, vec![1, 2, 3, 4]), (9, vec![0, 1, 2, 3, 4])] + { + assert_eq!(super::body::seats(¬e, count), seats, "{count}"); + } + let hit = |field, excerpt: &str| Some(SearchHit { field, excerpt: excerpt.to_owned() }); + note.search_hit = hit(SearchField::Item, "a"); + assert_eq!(super::body::seats(¬e, 2), [0, 1]); + note.search_hit = hit(SearchField::Item, "c…"); + assert_eq!(super::body::seats(¬e, 1), [2]); + note.search_hit = hit(SearchField::Body, "a"); + assert_eq!(super::body::seats(¬e, 1), [1], "found elsewhere"); +} + +#[test] +fn a_note_s_lines_are_drawn_with_what_they_are() { + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| { + draft.kind = NoteKind::Note; + draft.content = + "# Titre\n\n- point\n\n1. premier\n\n- [x] fait\n- [ ] reste\n\n```\ncode\n```".into(); + }); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + bench.state.preview_lines = engine::folders::board::PreviewLines::Five; + testing::settle(&mut harness, |bench| &bench.backend); + let outline = label(&harness, "note-card-outline"); + + for words in ["Titre", "• point", "1. premier", "☑ fait", "☐ reste"] { + assert!(outline.contains(words), "{words}: {outline}"); + } +} + +#[test] +fn each_line_of_a_sheet_has_its_result() { + let (backend, profile) = testing::unlocked(); + write(&backend, |draft| { + draft.kind = NoteKind::Calc; + draft.content = "a = 10 / 4 +b = 4 +total" + .into(); + }); + let harness = canvas(backend, profile); + let painted = testing::painted(&harness); + + for words in ["a = 10 / 4", "2.5", "4", "total", "6.5"] { + assert!(painted.contains(&words.to_owned()), "{words}: {painted:?}"); + } } diff --git a/crates/ui/src/notes/canvas/grid.rs b/crates/ui/src/notes/canvas/grid.rs index 292e6f1af..cf70267b3 100644 --- a/crates/ui/src/notes/canvas/grid.rs +++ b/crates/ui/src/notes/canvas/grid.rs @@ -30,16 +30,13 @@ pub fn neighbour<'a>( Direction::Next if at + 1 < cards.len() => Some((section, at + 1)), Direction::Next => (section + 1 < filled.len()).then_some((section + 1, 0)), Direction::Previous if at > 0 => Some((section, at - 1)), - Direction::Previous => section - .checked_sub(1) - .map(|before| (before, filled[before].len() - 1)), + Direction::Previous => section.checked_sub(1).map(|before| (before, filled[before].len() - 1)), Direction::Down if at + columns < cards.len() => Some((section, at + columns)), // A shorter last row below: its last card. - Direction::Down if at / columns < (cards.len() - 1) / columns => { - Some((section, cards.len() - 1)) + Direction::Down if at / columns < (cards.len() - 1) / columns => Some((section, cards.len() - 1)), + Direction::Down => { + (section + 1 < filled.len()).then(|| (section + 1, column.min(filled[section + 1].len() - 1))) } - Direction::Down => (section + 1 < filled.len()) - .then(|| (section + 1, column.min(filled[section + 1].len() - 1))), Direction::Up if at >= columns => Some((section, at - columns)), Direction::Up => section.checked_sub(1).map(|before| { let above = filled[before].len(); @@ -51,12 +48,10 @@ pub fn neighbour<'a>( } fn locate(sections: &[&Vec<&str>], id: &str) -> Option<(usize, usize)> { - sections.iter().enumerate().find_map(|(section, cards)| { - cards - .iter() - .position(|card| *card == id) - .map(|at| (section, at)) - }) + sections + .iter() + .enumerate() + .find_map(|(section, cards)| cards.iter().position(|card| *card == id).map(|at| (section, at))) } #[cfg(test)] @@ -75,10 +70,7 @@ mod tests { #[test] fn the_first_arrow_lands_on_the_first_card() { assert_eq!(neighbour(§ions(), 3, None, Direction::Down), Some("a")); - assert_eq!( - neighbour(§ions(), 3, Some("gone"), Direction::Next), - Some("a") - ); + assert_eq!(neighbour(§ions(), 3, Some("gone"), Direction::Next), Some("a")); } #[test] diff --git a/crates/ui/src/notes/canvas/mod.rs b/crates/ui/src/notes/canvas/mod.rs index 26353eada..416ff9409 100644 --- a/crates/ui/src/notes/canvas/mod.rs +++ b/crates/ui/src/notes/canvas/mod.rs @@ -12,8 +12,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::emath::GuiRounding as _; use egui::text::{LayoutJob, TextFormat}; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Rect, Role, Sense, Shape, Stroke, Ui, UiBuilder, - Vec2, WidgetInfo, pos2, vec2, + Color32, CornerRadius, FontFamily, FontId, Rect, Role, Sense, Shape, Stroke, Ui, UiBuilder, Vec2, + WidgetInfo, pos2, vec2, }; use engine::notes::view::{NoteSection, NoteSectionKey, NotesView, SectionGroup}; use i18n::{Key, keys}; @@ -61,10 +61,7 @@ pub fn show(ui: &mut Ui, state: &AppState, canvas_view: &mut CanvasView, actions // Loading is the one failure that empties the whole screen: it has its own retry. padded(ui, canvas, |ui| { state_text(ui, &tr(keys::errors::NOTES_LOAD_FAILED), "canvas-error"); - if Button::new(&tr(keys::errors::RETRY), "canvas-retry") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::errors::RETRY), "canvas-retry").show(ui).clicked() { actions.push(Action::Notes(super::Action::Reload)); } }); @@ -86,11 +83,7 @@ pub fn show(ui: &mut Ui, state: &AppState, canvas_view: &mut CanvasView, actions } else { (tr(keys::notes::CLEAR_SEARCH), "canvas-clear-filters") }; - let action = widgets::EmptyAction { - label: &label, - author_id, - primary: false, - }; + let action = widgets::EmptyAction { label: &label, author_id, primary: false }; let words = tr(keys::notes::NO_RESULTS); let room = ui.max_rect(); if widgets::empty_state(ui, room, (&words, "canvas-no-results"), &[action]).is_some() { @@ -122,30 +115,17 @@ fn hint(ui: &mut Ui, language: i18n::Language) { let words = i18n::translate(language, keys::notes::KEYBOARD_HINT, &[]); let width = widgets::arrowed(ui, None, &words, font::META, p.text_2); let region = ui.max_rect(); - let band = Rect::from_min_max( - pos2(region.left(), region.bottom() - HINT_HEIGHT), - region.max, - ); + let band = Rect::from_min_max(pos2(region.left(), region.bottom() - HINT_HEIGHT), region.max); let mut band_ui = ui.new_child(UiBuilder::new().max_rect(band)); + band_ui.painter().rect_filled(band, CornerRadius::ZERO, p.bg_0); band_ui .painter() - .rect_filled(band, CornerRadius::ZERO, p.bg_0); - band_ui.painter().hline( - band.x_range(), - band.top(), - egui::Stroke::new(1.0, p.line_soft), - ); + .hline(band.x_range(), band.top(), egui::Stroke::new(1.0, p.line_soft)); let rect = Rect::from_center_size(band.center(), vec2(width, 14.0)); let response = band_ui.allocate_rect(rect, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); address(&band_ui, &response, "canvas-keyboard-hint"); - widgets::arrowed( - &band_ui, - Some(rect.left_center()), - &words, - font::META, - p.text_2, - ); + widgets::arrowed(&band_ui, Some(rect.left_center()), &words, font::META, p.text_2); } fn on_screen(view: &NotesView) -> Vec<&str> { @@ -161,14 +141,7 @@ pub(super) fn padded(ui: &mut Ui, padding: f32, draw: impl FnOnce(&mut Ui)) { pub(super) fn state_text(ui: &mut Ui, words: &str, author_id: &str) { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - words, - font::READING, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, words, font::READING, 400.0, FontFamily::Proportional, p.text_2); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); address(ui, &response, author_id); @@ -194,11 +167,7 @@ fn sections( ui.set_height(rows.height() + 2.0 * s.canvas + HINT_HEIGHT); canvas_view.columns = rows.columns(); // A card asked to take the focus may be scrolled out of view, so not drawn. - if let Some(top) = canvas_view - .request - .as_deref() - .and_then(|id| rows.top_of(view, id)) - { + if let Some(top) = canvas_view.request.as_deref().and_then(|id| rows.top_of(view, id)) { let size = vec2(width, context.card_height()); let rect = Rect::from_min_size(origin + vec2(0.0, top), size); ui.scroll_to_rect(rect, None); @@ -242,13 +211,7 @@ fn cards( let mut cell_ui = ui.new_child(UiBuilder::new().max_rect(rect).id_salt((section, cell))); match shown.cards.get(cell) { Some(shown_card) => { - card::show( - &mut cell_ui, - rect, - view.display(shown_card), - context, - (canvas_view, actions), - ); + card::show(&mut cell_ui, rect, view.display(shown_card), context, (canvas_view, actions)); } None => ghost(&mut cell_ui, rect, context.language, actions), } @@ -265,10 +228,10 @@ fn heading( let p = palette(ui.ctx()); let mut left = rect.left(); if let Some(SectionGroup::Priority { priority }) = section.group { - let mut dot_ui = ui.new_child(UiBuilder::new().max_rect(Rect::from_min_size( - pos2(left, rect.center().y - 4.0), - Vec2::splat(8.0), - ))); + let mut dot_ui = ui.new_child( + UiBuilder::new() + .max_rect(Rect::from_min_size(pos2(left, rect.center().y - 4.0), Vec2::splat(8.0))), + ); priority_dot(&mut dot_ui, priority); left += 8.0 + 8.0; } @@ -280,11 +243,7 @@ fn heading( let mut count = format!("· {}", section.cards.len()); if section.has_expiring_notes { count.push_str(" · "); - count.push_str(&i18n::translate( - language, - keys::sections::EXPIRING_HINT, - &[], - )); + count.push_str(&i18n::translate(language, keys::sections::EXPIRING_HINT, &[])); } let mut job = LayoutJob::default(); job.append( @@ -350,33 +309,16 @@ fn ghost(ui: &mut Ui, rect: Rect, language: i18n::Language, actions: &mut Action corner, ); let lit = response.hovered(); - let (edge, ink) = if lit { - (p.amber_dim, p.amber_text) - } else { - (p.line, p.text_2) - }; + let (edge, ink) = if lit { (p.amber_dim, p.amber_text) } else { (p.line, p.text_2) }; ui.painter().extend(dashed(rect, Stroke::new(1.0, edge))); let plus = widgets::text(ui, "+", font::DISPLAY, 400.0, FontFamily::Proportional, ink); - let label = widgets::text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Proportional, - ink, - ); + let label = widgets::text(ui, &words, font::LABEL, 400.0, FontFamily::Proportional, ink); let height = plus.size().y + 6.0 + label.size().y; let top = rect.center().y - height / 2.0; + ui.painter() + .galley(pos2(rect.center().x - plus.size().x / 2.0, top), plus.clone(), Color32::TRANSPARENT); ui.painter().galley( - pos2(rect.center().x - plus.size().x / 2.0, top), - plus.clone(), - Color32::TRANSPARENT, - ); - ui.painter().galley( - pos2( - rect.center().x - label.size().x / 2.0, - top + plus.size().y + 6.0, - ), + pos2(rect.center().x - label.size().x / 2.0, top + plus.size().y + 6.0), label, Color32::TRANSPARENT, ); @@ -388,13 +330,8 @@ fn ghost(ui: &mut Ui, rect: Rect, language: i18n::Language, actions: &mut Action /// The four sides of `rect`, dashed: egui strokes no dashed rectangle of its own. fn dashed(rect: Rect, stroke: Stroke) -> Vec { let rect = rect.shrink(0.5); - let corners = [ - rect.left_top(), - rect.right_top(), - rect.right_bottom(), - rect.left_bottom(), - rect.left_top(), - ]; + let corners = + [rect.left_top(), rect.right_top(), rect.right_bottom(), rect.left_bottom(), rect.left_top()]; Shape::dashed_line(&corners, stroke, 4.0, 3.0) } diff --git a/crates/ui/src/notes/canvas/rows.rs b/crates/ui/src/notes/canvas/rows.rs index e512f22d4..0ab896917 100644 --- a/crates/ui/src/notes/canvas/rows.rs +++ b/crates/ui/src/notes/canvas/rows.rs @@ -41,11 +41,7 @@ impl Rows { let columns = columns(width, grid); #[expect(clippy::cast_precision_loss, reason = "a handful of columns")] let card_width = ((width - grid * (columns - 1) as f32) / columns as f32).max(0.0); - let mut rows = Self { - columns, - card_width, - ..Self::default() - }; + let mut rows = Self { columns, card_width, ..Self::default() }; for (index, shown) in view.sections.iter().enumerate() { let cells = shown.cards.len() + usize::from(shown.show_create_ghost); let after = if cells == 0 { section } else { HEADING_GAP }; @@ -54,13 +50,7 @@ impl Rows { while first < cells { let last = first + columns >= cells; let gap = if last { section } else { grid }; - rows.push( - Row::Cards { - section: index, - first, - }, - card + gap, - ); + rows.push(Row::Cards { section: index, first }, card + gap); first += columns; } } @@ -88,40 +78,25 @@ impl Rows { /// The rows that cross `top..bottom`, with where each starts. /// Where the row holding note `id` starts, if the view holds it. pub fn top_of(&self, view: &NotesView, id: &str) -> Option { - let (section, at) = view - .sections - .iter() - .enumerate() - .find_map(|(section, shown)| { - shown - .cards - .iter() - .position(|card| card.id == id) - .map(|at| (section, at)) - })?; - self.all - .iter() - .zip(&self.tops) - .find_map(|(row, top)| match row { - Row::Cards { section: s, first } - if *s == section && (*first..*first + self.columns).contains(&at) => - { - Some(*top) - } - _ => None, - }) + let (section, at) = view.sections.iter().enumerate().find_map(|(section, shown)| { + shown.cards.iter().position(|card| card.id == id).map(|at| (section, at)) + })?; + self.all.iter().zip(&self.tops).find_map(|(row, top)| match row { + Row::Cards { section: s, first } + if *s == section && (*first..*first + self.columns).contains(&at) => + { + Some(*top) + } + _ => None, + }) } pub fn visible(&self, top: f32, bottom: f32) -> impl Iterator + '_ { - self.range(top, bottom) - .map(|index| (self.tops[index], self.all[index])) + self.range(top, bottom).map(|index| (self.tops[index], self.all[index])) } fn range(&self, top: f32, bottom: f32) -> Range { - let first = self - .tops - .partition_point(|&start| start <= top) - .saturating_sub(1); + let first = self.tops.partition_point(|&start| start <= top).saturating_sub(1); let end = self.tops.partition_point(|&start| start < bottom); first..end.max(first) } diff --git a/crates/ui/src/notes/canvas/shortcuts.rs b/crates/ui/src/notes/canvas/shortcuts.rs index 43b009ab4..2d22d473d 100644 --- a/crates/ui/src/notes/canvas/shortcuts.rs +++ b/crates/ui/src/notes/canvas/shortcuts.rs @@ -106,18 +106,10 @@ pub fn bound_to(bindings: &Bindings) -> Vec { }; let moved = rebindable(canvas) .filter(|_| binding.key != Key::Backspace) - .and_then(|id| { - crate::services::shortcuts::ACTIONS - .iter() - .find(|it| it.id == id) - }) + .and_then(|id| crate::services::shortcuts::ACTIONS.iter().find(|it| it.id == id)) .and_then(|action| bindings.keystroke(*action)); match moved { - Some((key, modifiers)) => Binding { - key, - modifiers, - ..binding.clone() - }, + Some((key, modifiers)) => Binding { key, modifiers, ..binding.clone() }, None => binding.clone(), } }) @@ -171,9 +163,7 @@ mod tests { table.iter().any(|binding| { binding.key == key && binding.action - == crate::action::Action::Notes(crate::notes::Action::Canvas( - super::CanvasKey::Pin, - )) + == crate::action::Action::Notes(crate::notes::Action::Canvas(super::CanvasKey::Pin)) }) }; assert!(pin(Key::J)); @@ -247,10 +237,7 @@ mod tests { press(&mut harness, Key::P); let view = harness.state().state.notes_query.view().unwrap(); - assert!( - view.cards().all(|card| !card.pinned), - "the same note, twice" - ); + assert!(view.cards().all(|card| !card.pinned), "the same note, twice"); } #[test] @@ -262,11 +249,7 @@ mod tests { press(&mut harness, Key::Delete); harness.get_by(|node| node.author_id() == Some("note-card-arming")); press(&mut harness, Key::Escape); - assert!( - harness - .query_by(|node| node.author_id() == Some("note-card-arming")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("note-card-arming")).is_none()); assert_eq!(cards(&harness), 1); press(&mut harness, Key::Delete); @@ -300,10 +283,7 @@ mod tests { press(&mut harness, Key::Escape); assert_eq!(harness.state().state.notes_query.typed(), ""); - assert_eq!( - harness.state().state.active_folder(), - Some(folder.id.as_str()) - ); + assert_eq!(harness.state().state.active_folder(), Some(folder.id.as_str())); press(&mut harness, Key::Escape); assert_eq!(harness.state().state.active_folder(), None); @@ -318,9 +298,37 @@ mod tests { settle(&mut harness); let opened = harness.state().state.editor.opened().unwrap(); - assert_eq!( - opened.note().unwrap().kind, - engine::notes::kind::NoteKind::Snippet - ); + assert_eq!(opened.note().unwrap().kind, engine::notes::kind::NoteKind::Snippet); + } + + /// Held, the key comes back at every frame: egui would walk the focus off the cards between + /// two, onto the edge of the rail. + #[test] + fn an_arrow_held_stays_on_the_cards() { + let (backend, profile) = notes(2); + let mut harness = area(backend, profile); + press(&mut harness, Key::ArrowDown); + let on_a_card = |harness: &Harness<'_, Bench>| { + harness + .query_all_by(|node| node.author_id() == Some("note-card-open")) + .any(|node| node.is_focused()) + }; + for pauses in 0..4 { + for key in [Key::ArrowRight, Key::ArrowLeft, Key::ArrowLeft, Key::ArrowLeft] { + harness.event(egui::Event::Key { + key, + physical_key: Some(key), + pressed: true, + repeat: false, + modifiers: Modifiers::NONE, + }); + harness.step(); + for _ in 0..pauses { + harness.step(); + } + } + settle(&mut harness); + assert!(on_a_card(&harness), "{pauses} frames between two keys"); + } } } diff --git a/crates/ui/src/notes/canvas/tests.rs b/crates/ui/src/notes/canvas/tests.rs index 8b8946f23..e8629f6c0 100644 --- a/crates/ui/src/notes/canvas/tests.rs +++ b/crates/ui/src/notes/canvas/tests.rs @@ -17,44 +17,36 @@ pub(super) struct Bench { pub(super) fn canvas(backend: Backend, profile: tempfile::TempDir) -> Harness<'static, Bench> { let mut state = AppState::new(crate::services::preferences::Preferences::default(), true); state.language = i18n::Language::En; - let mut harness = testing::harness() - .with_size(vec2(1_100.0, 700.0)) - .build_ui_state( - |ui, bench: &mut Bench| { - crate::theme::motion::set_reduced(ui.ctx(), true); - let now = chrono::Utc::now(); - let state = &mut bench.state; - state.notes.update(&mut state.revision, &mut state.errors); - state.caches.thumbnails.update(ui.ctx(), &bench.backend); - state.notes_query.update( - ui.ctx(), - &bench.backend, - now, - (None, None), - state.revision, - ); - show(ui, &bench.state, &mut bench.canvas, &mut bench.actions); - let ctx = ui.ctx().clone(); - for action in bench.actions.drain().collect::>() { - bench.state.apply(action, &ctx, &bench.backend); - } - }, - Bench { - backend, - state, - actions: Actions::default(), - canvas: CanvasView::default(), - _profile: profile, - }, - ); + let mut harness = testing::harness().with_size(vec2(1_100.0, 700.0)).build_ui_state( + |ui, bench: &mut Bench| { + crate::theme::motion::set_reduced(ui.ctx(), true); + let now = chrono::Utc::now(); + let state = &mut bench.state; + state.notes.update(&mut state.revision, &mut state.errors); + state.caches.thumbnails.update(ui.ctx(), &bench.backend); + state + .notes_query + .update(ui.ctx(), &bench.backend, now, (None, None), state.revision); + show(ui, &bench.state, &mut bench.canvas, &mut bench.actions); + let ctx = ui.ctx().clone(); + for action in bench.actions.drain().collect::>() { + bench.state.apply(action, &ctx, &bench.backend); + } + }, + Bench { + backend, + state, + actions: Actions::default(), + canvas: CanvasView::default(), + _profile: profile, + }, + ); testing::settle(&mut harness, |bench| &bench.backend); harness } fn cards(harness: &Harness<'_, Bench>) -> usize { - harness - .query_all_by(|node| node.author_id() == Some("note-card")) - .count() + harness.query_all_by(|node| node.author_id() == Some("note-card")).count() } #[test] @@ -69,10 +61,7 @@ fn the_notes_of_today_are_one_section_of_cards() { .query_all_by(|node| node.author_id() == Some("note-card")) .map(|card| card.accesskit_node().label()) .collect(); - assert!( - titles.contains(&Some("psql prod".to_string())), - "{titles:?}" - ); + assert!(titles.contains(&Some("psql prod".to_string())), "{titles:?}"); let headings: Vec<_> = harness .query_all_by(|node| node.author_id() == Some("note-section")) .map(|heading| heading.accesskit_node().label().unwrap_or_default()) @@ -88,18 +77,13 @@ fn of_thirty_thousand_notes_only_the_rows_in_view_are_drawn() { let mut harness = canvas(backend, profile); let first = cards(&harness); - harness - .get_by(|node| node.author_id() == Some("canvas")) - .scroll_down(); + harness.get_by(|node| node.author_id() == Some("canvas")).scroll_down(); testing::settle(&mut harness, |bench| &bench.backend); // Four columns at this width, four rows and a part in 700 px. assert!((4..=24).contains(&first), "{first} cards drawn"); assert!(cards(&harness) <= 24); - assert_eq!( - harness.state().state.notes_query.view().unwrap().matched, - 30_000 - ); + assert_eq!(harness.state().state.notes_query.view().unwrap().matched, 30_000); } #[test] @@ -110,11 +94,7 @@ fn a_library_without_notes_offers_the_card_to_create_one() { assert_eq!(cards(&harness), 0); harness.get_by(|node| node.author_id() == Some("create-ghost")); - assert!( - harness - .query_by(|node| node.author_id() == Some("canvas-no-results")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("canvas-no-results")).is_none()); } #[test] @@ -124,9 +104,7 @@ fn a_view_that_failed_offers_to_retry() { let mut harness = canvas(backend, profile); harness.get_by(|node| node.author_id() == Some("canvas-error")); let before = harness.state().state.revision; - harness - .get_by(|node| node.author_id() == Some("canvas-retry")) - .click(); + harness.get_by(|node| node.author_id() == Some("canvas-retry")).click(); harness.run(); assert_ne!(harness.state().state.revision, before); @@ -142,17 +120,135 @@ fn an_empty_folder_offers_the_card_a_note_is_created_from() { crate::notes::bench::click(&mut harness, "folder-option", "Runbooks"); - let present = |author_id: &str| { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() - }; + let present = |author_id: &str| harness.query_by(|node| node.author_id() == Some(author_id)).is_some(); assert!(!present("canvas-no-results"), "nothing was searched"); assert!(present("create-ghost")); crate::notes::bench::click_id(&mut harness, "create-ghost"); let opened = harness.state().state.editor.opened(); - let draft = opened - .and_then(|opened| opened.note()) - .expect("a draft opens"); + let draft = opened.and_then(|opened| opened.note()).expect("a draft opens"); assert_eq!(draft.folder_id.as_deref(), Some(runbooks.id.as_str())); } + +fn headings(harness: &Harness<'_, Bench>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("note-section")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() +} + +/// A snippet in SQL, urgent; a todo list with no level. +fn grouped(grouping: engine::notes::view::Grouping) -> Vec { + use engine::notes::kind::NoteKind; + use engine::notes::language::Language; + use engine::notes::model::NotePatch; + + let (backend, profile) = testing::unlocked(); + for (title, patch) in [ + ("sql", NotePatch { language: Some(Language::Sql), ..NotePatch::default() }), + ("list", NotePatch { kind: Some(NoteKind::Checklist), ..NotePatch::default() }), + ] { + let id = testing::note(&backend, title).id.clone(); + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + if title == "sql" { + let urgent = engine::notes::priority::Priority::Urgent; + engine::notes::set_priority(engine, &[id], urgent)?; + } + Ok::<_, engine::error::AppError>(()) + }) + .unwrap(); + } + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let arrangement = + crate::state::notes_query::Arrangement { grouping, ..bench.state.notes_query.arrangement() }; + bench.state.apply( + Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + headings(&harness) +} + +#[test] +fn a_section_is_named_by_what_it_gathers() { + use engine::notes::view::Grouping; + + for (grouping, named) in + [(Grouping::Format, "SQL"), (Grouping::Format, "TASKS"), (Grouping::Priority, "URGENT")] + { + let headings = grouped(grouping); + assert!(headings.iter().any(|heading| heading.contains(named)), "{grouping:?}: {headings:?}"); + } +} + +#[test] +fn a_priority_s_section_wears_its_dot() { + let urgent = palette(&egui::Context::default()).red; + let dotted = |grouping| { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "sql").id.clone(); + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::set_priority(engine, &[id], engine::notes::priority::Priority::Urgent) + }) + .unwrap(); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let arrangement = + crate::state::notes_query::Arrangement { grouping, ..bench.state.notes_query.arrangement() }; + bench.state.apply( + Action::Notes(crate::notes::Action::Arrange(arrangement)), + &egui::Context::default(), + &bench.backend, + ); + testing::settle(&mut harness, |bench| &bench.backend); + let top = harness + .query_all_by(|node| node.author_id() == Some("note-section")) + .next() + .unwrap() + .rect(); + harness.output().shapes.iter().any(|clipped| { + matches!(&clipped.shape, egui::Shape::Circle(circle) + if circle.fill == urgent && circle.center.y < top.bottom() && circle.center.y > top.top()) + }) + }; + + assert!(dotted(engine::notes::view::Grouping::Priority)); + assert!(!dotted(engine::notes::view::Grouping::None)); +} + +/// What is offered is what gives the cards back. +#[test] +fn nothing_found_offers_the_way_back_from_what_filters() { + use crate::notes::Action as Notes; + + for (facet, label) in [(false, keys::notes::CLEAR_SEARCH), (true, keys::notes::CLEAR_FILTERS)] { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql"); + let mut harness = canvas(backend, profile); + let bench = harness.state_mut(); + let (ctx, backend) = (egui::Context::default(), &bench.backend); + if facet { + let kind = crate::state::notes_query::Facet::Kind(engine::notes::kind::NoteKind::Drawing); + bench.state.apply(Action::Notes(Notes::Facet(kind)), &ctx, backend); + } else { + bench + .state + .apply(Action::Notes(Notes::Search("nowhere".to_owned())), &ctx, backend); + } + for _ in 0..40 { + harness.step(); + } + testing::settle(&mut harness, |bench| &bench.backend); + let button = harness.get_by(|node| node.author_id() == Some("canvas-clear-filters")); + let said = button.accesskit_node().label().unwrap_or_default(); + assert_eq!(said, i18n::translate(i18n::Language::En, label, &[])); + button.click(); + for _ in 0..40 { + harness.step(); + } + testing::settle(&mut harness, |bench| &bench.backend); + assert_eq!(cards(&harness), 1); + } +} diff --git a/crates/ui/src/notes/destinations.rs b/crates/ui/src/notes/destinations.rs index 209c7d231..ca8d83f1b 100644 --- a/crates/ui/src/notes/destinations.rs +++ b/crates/ui/src/notes/destinations.rs @@ -38,10 +38,7 @@ pub(super) struct Moving<'a> { pub(super) fn picker(ui: &mut Ui, moving: &Moving<'_>, author_id: &str) -> Option { let label = i18n::translate(moving.language, keys::notes::MOVE_TO, &[]); let mut offered = offered(ui, moving); - let places: Vec = offered - .iter_mut() - .filter_map(|(_, place)| place.take()) - .collect(); + let places: Vec = offered.iter_mut().filter_map(|(_, place)| place.take()).collect(); let picked = widgets::place_picker(ui, &places, (&label, author_id), moving.language)?; let (to, _) = offered.swap_remove(picked); (moving.here.as_ref() != Some(&to)).then_some(to) @@ -87,27 +84,18 @@ fn tree_of(ui: &Ui, moving: &Moving<'_>) -> Vec { let (to, place) = match row { Row::Space { space, .. } => { within.clone_from(&space.name); - let place = Place { - strong: true, - ..place(space.name.clone(), Lead::None) - }; + let place = Place { strong: true, ..place(space.name.clone(), Lead::None) }; (Destination::Space(space.id.clone()), place) } Row::Folder { folder, depth, .. } => { let path = lineage.path(&folder.id); - let parents = path - .iter() - .filter(|id| **id != folder.id) - .filter_map(name_of); + let parents = path.iter().filter(|id| **id != folder.id).filter_map(name_of); let parents = parents.map(|parent| parent.name.as_str()); let within: Vec<&str> = std::iter::once(within.as_str()).chain(parents).collect(); let place = Place { within: within.join(" › "), depth: depth + 1, - ..place( - folder.name.clone(), - Lead::Dot(super::ui::folder_hue(ui, folder.colour)), - ) + ..place(folder.name.clone(), Lead::Dot(super::ui::folder_hue(ui, folder.colour))) }; (Destination::Folder(folder.id.clone()), place) } @@ -120,13 +108,5 @@ fn tree_of(ui: &Ui, moving: &Moving<'_>) -> Vec { } fn place(name: String, lead: Lead) -> Place { - Place { - lead, - name, - within: String::new(), - depth: 0, - strong: false, - here: false, - again: false, - } + Place { lead, name, within: String::new(), depth: 0, strong: false, here: false, again: false } } diff --git a/crates/ui/src/notes/header/facets.rs b/crates/ui/src/notes/header/facets.rs index 9039f3705..69613c02f 100644 --- a/crates/ui/src/notes/header/facets.rs +++ b/crates/ui/src/notes/header/facets.rs @@ -5,9 +5,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Galley, Id, Key, Margin, Modifiers, Popup, - PopupCloseBehavior, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, - pos2, vec2, + Color32, CornerRadius, FontFamily, Galley, Id, Key, Margin, Modifiers, Popup, PopupCloseBehavior, Rect, + Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2, }; use engine::notes::kind::NoteKind; use engine::notes::priority::Priority; @@ -61,18 +60,15 @@ fn band(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) { #[expect(clippy::cast_possible_truncation, reason = "a few points")] let (side, above) = (spacing(ui.ctx()).canvas.round() as i8, gap::INSET as i8); let p = palette(ui.ctx()); - let shown = egui::Frame::new() - .inner_margin(Margin::symmetric(side, above)) - .show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap::SNUG; - draw(ui); - }); + let shown = egui::Frame::new().inner_margin(Margin::symmetric(side, above)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = gap::SNUG; + draw(ui); }); + }); let rect = shown.response.rect; - ui.painter() - .hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); } /// The rule between the groups and the way out of them. @@ -96,9 +92,7 @@ fn clear(ui: &mut Ui, language: Language, actions: &mut Actions) { let clicked = if ui.available_width() >= quiet_width(ui, &label) { words.show(ui).clicked() } else { - widgets::IconButton::new(Icon::X, &label, "clear-filters") - .show(ui) - .clicked() + widgets::IconButton::new(Icon::X, &label, "clear-filters").show(ui).clicked() }; if clicked { press(actions, Facet::Clear); @@ -107,14 +101,7 @@ fn clear(ui: &mut Ui, language: Language, actions: &mut Actions) { /// What the quiet button with its cross takes: its words, the icon and their insets. fn quiet_width(ui: &Ui, label: &str) -> f32 { - let words = widgets::text( - ui, - label, - font::LABEL, - 400.0, - FontFamily::Proportional, - Color32::WHITE, - ); + let words = widgets::text(ui, label, font::LABEL, 400.0, FontFamily::Proportional, Color32::WHITE); words.size().x + 16.0 + gap::SNUG + 2.0 * gap::SNUG } @@ -181,26 +168,14 @@ fn walk(ui: &Ui, entries: &[Id]) { /// A pill: the group's name, how many of its values are ticked, a chevron. Amber while it /// filters, `bg-3` while its menu is open. -fn trigger( - ui: &mut Ui, - (name, author_id): (&str, &str), - ticked: usize, - language: Language, -) -> Response { +fn trigger(ui: &mut Ui, (name, author_id): (&str, &str), ticked: usize, language: Language) -> Response { let p = palette(ui.ctx()); let family = FontFamily::Proportional; - let named = widgets::text(ui, name, font::CONTROL, 400.0, family.clone(), p.text_1) - .size() - .x; + let named = widgets::text(ui, name, font::CONTROL, 400.0, family.clone(), p.text_1).size().x; let figure = (ticked > 0).then(|| ticked.to_string()); - let counted = figure - .as_deref() - .map_or(0.0, |figure| COUNT_GAP + count_size(ui, figure).x); + let counted = figure.as_deref().map_or(0.0, |figure| COUNT_GAP + count_size(ui, figure).x); let chevron = 10.0; - let size = vec2( - gap::INSET + named + counted + gap::SNUG + chevron + gap::CONTROLS, - TRIGGER_HEIGHT, - ); + let size = vec2(gap::INSET + named + counted + gap::SNUG + chevron + gap::CONTROLS, TRIGGER_HEIGHT); let spoken = if ticked == 0 { name.to_owned() } else { @@ -223,45 +198,22 @@ fn trigger( let open = Popup::is_id_open(ui.ctx(), Popup::default_response_id(&response)); let on = ticked > 0; let hover = hovered(ui, &response); - let fill = if open { - p.bg_3 - } else { - towards(p.bg_2, p.bg_3, hover) - }; + let fill = if open { p.bg_3 } else { towards(p.bg_2, p.bg_3, hover) }; let edge = if on { p.amber_dim } else { p.line_soft }; - let ink = if on { - p.amber_text - } else { - towards(p.text_1, p.text_0, hover.max(if open { 1.0 } else { 0.0 })) - }; + let ink = + if on { p.amber_text } else { towards(p.text_1, p.text_0, hover.max(if open { 1.0 } else { 0.0 })) }; let rect = response.rect; - ui.painter().rect( - rect, - corner, - fill, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, fill, Stroke::new(1.0, edge), StrokeKind::Inside); let words = widgets::text(ui, name, font::CONTROL, 400.0, family, ink); let left = rect.left() + gap::INSET; - ui.painter().galley( - pos2(left, rect.center().y - words.size().y / 2.0), - words, - ink, - ); + ui.painter() + .galley(pos2(left, rect.center().y - words.size().y / 2.0), words, ink); if let Some(figure) = &figure { - paint_count( - ui, - figure, - (left + named + COUNT_GAP, rect.center().y), - (on, true), - ); + paint_count(ui, figure, (left + named + COUNT_GAP, rect.center().y), (on, true)); } let glyph = Rect::from_center_size( - pos2( - rect.right() - gap::CONTROLS - chevron / 2.0, - rect.center().y, - ), + pos2(rect.right() - gap::CONTROLS - chevron / 2.0, rect.center().y), Vec2::splat(chevron), ); icons::paint(ui, glyph, Icon::ChevronDown, ink); @@ -299,17 +251,9 @@ impl Value<'_> { let p = palette(ui.ctx()); let enabled = self.on || self.every || self.count > 0; let (on, label) = (self.on, self.words); - let role = if self.every { - Role::MenuItemRadio - } else { - Role::MenuItemCheckBox - }; + let role = if self.every { Role::MenuItemRadio } else { Role::MenuItemCheckBox }; let corner = CornerRadius::same(radius::CONTROL); - let sense = if enabled { - Sense::click() - } else { - Sense::hover() - }; + let sense = if enabled { Sense::click() } else { Sense::hover() }; let response = interact( ui, vec2(ui.available_width(), VALUE_HEIGHT), @@ -332,52 +276,31 @@ impl Value<'_> { 0.0 }; if lit > 0.0 { - ui.painter() - .rect_filled(rect, corner, p.bg_3.gamma_multiply(lit)); + ui.painter().rect_filled(rect, corner, p.bg_3.gamma_multiply(lit)); } let fade = |colour: Color32| { - if enabled { - colour - } else { - colour.gamma_multiply(0.5) - } + if enabled { colour } else { colour.gamma_multiply(0.5) } }; let mut left = rect.left() + gap::CONTROLS; tick_box(ui, (left, rect.center().y), on, fade); left += BOX + gap::CONTROLS; paint_lead(ui, &self.lead, left, rect.center().y); left += lead_width(ui, &self.lead); - let ink = fade(if on { - p.amber_text - } else { - towards(p.text_1, p.text_0, lit) - }); - let words = widgets::text( - ui, - self.words, - font::META, - 400.0, - FontFamily::Monospace, - ink, - ); + let ink = fade(if on { p.amber_text } else { towards(p.text_1, p.text_0, lit) }); + let words = widgets::text(ui, self.words, font::META, 400.0, FontFamily::Monospace, ink); let named = words.size().x; let figure = self.count.to_string(); let counted = count_size(ui, &figure).x; let at = (rect.right() - gap::CONTROLS - counted, rect.center().y); // A tag longer than the widest menu stops short of its count, named whole in its tooltip. let room = Rect::from_x_y_ranges(left..=at.0 - gap::SNUG, rect.y_range()); - ui.painter() - .with_clip_rect(room.intersect(ui.clip_rect())) - .galley( - pos2(left, rect.center().y - words.size().y / 2.0), - words, - ink, - ); - paint_count(ui, &figure, at, (on, enabled)); - widgets::menu_needs( - ui, - left - rect.left() + named + gap::GROUPS + counted + gap::CONTROLS, + ui.painter().with_clip_rect(room.intersect(ui.clip_rect())).galley( + pos2(left, rect.center().y - words.size().y / 2.0), + words, + ink, ); + paint_count(ui, &figure, at, (on, enabled)); + widgets::menu_needs(ui, left - rect.left() + named + gap::GROUPS + counted + gap::CONTROLS); let clicked = response.clicked(); if named > room.width() { widgets::tooltip(response, label); @@ -398,24 +321,13 @@ fn tick_box(ui: &Ui, (left, middle): (f32, f32), on: bool, fade: impl Fn(Color32 ui.painter().rect_filled(rect, corner, fade(p.amber_fill)); icons::paint(ui, rect.shrink(2.0), Icon::Check, fade(p.amber_ink)); } else { - ui.painter().rect_stroke( - rect, - corner, - Stroke::new(1.5, fade(p.line)), - StrokeKind::Inside, - ); + ui.painter() + .rect_stroke(rect, corner, Stroke::new(1.5, fade(p.line)), StrokeKind::Inside); } } fn count_galley(ui: &Ui, figure: &str, ink: Color32) -> std::sync::Arc { - widgets::text( - ui, - figure, - font::CAPTION, - 400.0, - FontFamily::Proportional, - ink, - ) + widgets::text(ui, figure, font::CAPTION, 400.0, FontFamily::Proportional, ink) } fn count_size(ui: &Ui, figure: &str) -> Vec2 { @@ -425,23 +337,13 @@ fn count_size(ui: &Ui, figure: &str) -> Vec2 { /// The count on a fill of its own: a tag ending in a digit does not run into it. fn paint_count(ui: &Ui, figure: &str, (left, middle): (f32, f32), (on, enabled): (bool, bool)) { let p = palette(ui.ctx()); - let (fill, ink) = if on { - (p.amber_fill.gamma_multiply(0.15), p.amber_text) - } else { - (p.bg_3, p.text_2) - }; - let (fill, ink) = if enabled { - (fill, ink) - } else { - (fill.gamma_multiply(0.5), ink.gamma_multiply(0.5)) - }; + let (fill, ink) = if on { (p.amber_fill.gamma_multiply(0.15), p.amber_text) } else { (p.bg_3, p.text_2) }; + let (fill, ink) = if enabled { (fill, ink) } else { (fill.gamma_multiply(0.5), ink.gamma_multiply(0.5)) }; let size = count_size(ui, figure); let rect = Rect::from_min_size(pos2(left, middle - size.y / 2.0), size); - ui.painter() - .rect_filled(rect, CornerRadius::same(u8::MAX), fill); + ui.painter().rect_filled(rect, CornerRadius::same(u8::MAX), fill); let galley = count_galley(ui, figure, ink); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, ink); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, ink); } fn lead_width(ui: &Ui, lead: &Lead) -> f32 { @@ -455,14 +357,7 @@ fn lead_width(ui: &Ui, lead: &Lead) -> f32 { } fn badge_size(ui: &Ui, words: &str) -> Vec2 { - let galley = widgets::text( - ui, - words, - font::BADGE, - 700.0, - FontFamily::Monospace, - Color32::WHITE, - ); + let galley = widgets::text(ui, words, font::BADGE, 700.0, FontFamily::Monospace, Color32::WHITE); galley.size() + vec2(12.0, 4.0) } @@ -488,11 +383,8 @@ fn paint_lead(ui: &Ui, lead: &Lead, left: f32, middle: f32) { StrokeKind::Inside, ); let galley = widgets::text(ui, words, font::BADGE, 700.0, FontFamily::Monospace, *hue); - ui.painter().galley( - pos2(left + gap::SNUG, middle - galley.size().y / 2.0), - galley, - *hue, - ); + ui.painter() + .galley(pos2(left + gap::SNUG, middle - galley.size().y / 2.0), galley, *hue); } } } @@ -511,26 +403,13 @@ fn all( (count, on): (u32, bool), entries: &mut Vec, ) -> bool { - let clicked = Value { - words, - author_id, - count, - lead, - on, - every: true, - } - .show(ui, entries); + let clicked = Value { words, author_id, count, lead, on, every: true }.show(ui, entries); widgets::menu_line(ui); clicked } /// Each kind with what it holds in the space. -fn kinds( - ui: &mut Ui, - (view, facets, everything): Counted<'_>, - language: Language, - actions: &mut Actions, -) { +fn kinds(ui: &mut Ui, (view, facets, everything): Counted<'_>, language: Language, actions: &mut Actions) { let none = facets.kinds.is_empty(); if everything == 0 && none { return; @@ -538,38 +417,27 @@ fn kinds( let tr = |key| i18n::translate(language, key, &[]); let name = tr(keys::notes::KINDS); let ticked = facets.kinds.len(); - group( - ui, - (&name, "facet-menu-kind"), - ticked, - language, - |ui, entries| { - let every = tr(keys::notes::KIND_ALL); - if all( - ui, - (&every, "kind-chip-all", Lead::Room(TILE)), - (everything, none), - entries, - ) { - press(actions, Facet::AllKinds); - } - for counted in &view.kind_counts { - let words = tr(kind_key(counted.value)); - let author_id = format!("kind-chip-{}", counted.value.as_str()); - let value = Value { - words: &words, - author_id: &author_id, - count: counted.count, - lead: Lead::Kind(counted.value), - on: facets.kinds.contains(&counted.value), - every: false, - }; - if value.show(ui, entries) { - press(actions, Facet::Kind(counted.value)); - } + group(ui, (&name, "facet-menu-kind"), ticked, language, |ui, entries| { + let every = tr(keys::notes::KIND_ALL); + if all(ui, (&every, "kind-chip-all", Lead::Room(TILE)), (everything, none), entries) { + press(actions, Facet::AllKinds); + } + for counted in &view.kind_counts { + let words = tr(kind_key(counted.value)); + let author_id = format!("kind-chip-{}", counted.value.as_str()); + let value = Value { + words: &words, + author_id: &author_id, + count: counted.count, + lead: Lead::Kind(counted.value), + on: facets.kinds.contains(&counted.value), + every: false, + }; + if value.show(ui, entries) { + press(actions, Facet::Kind(counted.value)); } - }, - ); + } + }); } fn kind_key(kind: NoteKind) -> Words { @@ -603,53 +471,37 @@ fn priorities( let tr = |key| i18n::translate(language, key, &[]); let name = tr(keys::notes::PRIORITIES); let ticked = facets.priorities.len(); - group( - ui, - (&name, "facet-menu-priority"), - ticked, - language, - |ui, entries| { - let every = tr(keys::notes::PRIORITY_ALL); - if all( - ui, - (&every, "priority-chip-all", Lead::Room(BARS_WIDTH)), - (everything, none), - entries, - ) { - press(actions, Facet::AllPriorities); - } - for counted in levels { - let key = match counted.value { - Priority::Urgent => keys::notes::priority::URGENT, - Priority::High => keys::notes::priority::HIGH, - Priority::Medium => keys::notes::priority::MEDIUM, - Priority::Low | Priority::None => keys::notes::priority::LOW, - }; - let words = tr(key); - let author_id = format!("priority-chip-{}", counted.value.as_str()); - let value = Value { - words: &words, - author_id: &author_id, - count: counted.count, - lead: Lead::Priority(counted.value), - on: facets.priorities.contains(&counted.value), - every: false, - }; - if value.show(ui, entries) { - press(actions, Facet::Priority(counted.value)); - } + group(ui, (&name, "facet-menu-priority"), ticked, language, |ui, entries| { + let every = tr(keys::notes::PRIORITY_ALL); + if all(ui, (&every, "priority-chip-all", Lead::Room(BARS_WIDTH)), (everything, none), entries) { + press(actions, Facet::AllPriorities); + } + for counted in levels { + let key = match counted.value { + Priority::Urgent => keys::notes::priority::URGENT, + Priority::High => keys::notes::priority::HIGH, + Priority::Medium => keys::notes::priority::MEDIUM, + Priority::Low | Priority::None => keys::notes::priority::LOW, + }; + let words = tr(key); + let author_id = format!("priority-chip-{}", counted.value.as_str()); + let value = Value { + words: &words, + author_id: &author_id, + count: counted.count, + lead: Lead::Priority(counted.value), + on: facets.priorities.contains(&counted.value), + every: false, + }; + if value.show(ui, entries) { + press(actions, Facet::Priority(counted.value)); } - }, - ); + } + }); } /// The space's tags with what each holds; they scroll, « Manage » stays under them. -fn tags( - ui: &mut Ui, - (view, facets, everything): Counted<'_>, - language: Language, - actions: &mut Actions, -) { +fn tags(ui: &mut Ui, (view, facets, everything): Counted<'_>, language: Language, actions: &mut Actions) { if view.available_tags.is_empty() { return; } @@ -657,75 +509,51 @@ fn tags( let name = tr(keys::notes::TAGS); let none = facets.tags.is_empty(); let ticked = facets.tags.len(); - group( - ui, - (&name, "facet-menu-tag"), - ticked, - language, - |ui, entries| { - let every = tr(keys::notes::TAG_ALL); - if all( - ui, - (&every, "tag-all", Lead::None), - (everything, none), - entries, - ) { - press(actions, Facet::AllTags); - } - egui::ScrollArea::vertical() - .id_salt("tag-menu") - .max_height(TAGS_HEIGHT) - .show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 0.0; - for tag in &view.available_tags { - let count = view - .tag_counts - .iter() - .find(|counted| &counted.value == tag) - .map_or(0, |counted| counted.count); - let on = facets.tags.contains(tag); - let value = Value { - words: tag, - author_id: "tag-pill", - count, - lead: Lead::None, - on, - every: false, - }; - if value.show(ui, entries) { - press(actions, Facet::Tag(tag.clone())); - } + group(ui, (&name, "facet-menu-tag"), ticked, language, |ui, entries| { + let every = tr(keys::notes::TAG_ALL); + if all(ui, (&every, "tag-all", Lead::None), (everything, none), entries) { + press(actions, Facet::AllTags); + } + egui::ScrollArea::vertical() + .id_salt("tag-menu") + .max_height(TAGS_HEIGHT) + .show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + for tag in &view.available_tags { + let count = view + .tag_counts + .iter() + .find(|counted| &counted.value == tag) + .map_or(0, |counted| counted.count); + let on = facets.tags.contains(tag); + let value = Value { + words: tag, + author_id: "tag-pill", + count, + lead: Lead::None, + on, + every: false, + }; + if value.show(ui, entries) { + press(actions, Facet::Tag(tag.clone())); } - }); - widgets::menu_line(ui); - // The library's tag manager: it acts on exactly the tags listed above. - let manage = tr(keys::notes::MANAGE_TAGS); - let entry = widgets::icon_entry( - ui, - (Icon::Pencil, None), - &manage, - "tag-manage", - (false, false), - ); - entries.push(entry.id); - if entry.clicked() { - ui.close(); - actions.push(Action::Notes(crate::notes::Action::Tags( - crate::notes::Tags::Open, - ))); - } - }, - ); + } + }); + widgets::menu_line(ui); + // The library's tag manager: it acts on exactly the tags listed above. + let manage = tr(keys::notes::MANAGE_TAGS); + let entry = widgets::icon_entry(ui, (Icon::Pencil, None), &manage, "tag-manage", (false, false)); + entries.push(entry.id); + if entry.clicked() { + ui.close(); + actions.push(Action::Notes(crate::notes::Action::Tags(crate::notes::Tags::Open))); + } + }); } /// Each format after its badge, which carries its hue: tinted amber when ticked, it would lose /// the very clue it is known by, so the box and the words say it instead. -fn formats( - ui: &mut Ui, - (view, facets, everything): Counted<'_>, - language: Language, - actions: &mut Actions, -) { +fn formats(ui: &mut Ui, (view, facets, everything): Counted<'_>, language: Language, actions: &mut Actions) { if view.available_languages.is_empty() { return; } @@ -733,43 +561,32 @@ fn formats( let name = tr(keys::notes::LANGUAGES); let none = facets.languages.is_empty(); let ticked = facets.languages.len(); - group( - ui, - (&name, "facet-menu-language"), - ticked, - language, - |ui, entries| { - let every = tr(keys::notes::LANGUAGE_ALL); - if all( - ui, - (&every, "language-all", Lead::None), - (everything, none), - entries, - ) { - press(actions, Facet::AllLanguages); - } - for format in &view.available_languages { - let count = view - .language_counts - .iter() - .find(|counted| counted.value == *format) - .map_or(0, |counted| counted.count); - let hue = crate::notes::ui::language_hue(ui, *format); - let badge = crate::notes::language::label(*format).to_owned(); - let value = Value { - words: crate::notes::language::name(*format), - author_id: "language-chip", - count, - lead: Lead::Badge(badge, hue), - on: facets.languages.contains(format), - every: false, - }; - if value.show(ui, entries) { - press(actions, Facet::Language(*format)); - } + group(ui, (&name, "facet-menu-language"), ticked, language, |ui, entries| { + let every = tr(keys::notes::LANGUAGE_ALL); + if all(ui, (&every, "language-all", Lead::None), (everything, none), entries) { + press(actions, Facet::AllLanguages); + } + for format in &view.available_languages { + let count = view + .language_counts + .iter() + .find(|counted| counted.value == *format) + .map_or(0, |counted| counted.count); + let hue = crate::notes::ui::language_hue(ui, *format); + let badge = crate::notes::language::label(*format).to_owned(); + let value = Value { + words: crate::notes::language::name(*format), + author_id: "language-chip", + count, + lead: Lead::Badge(badge, hue), + on: facets.languages.contains(format), + every: false, + }; + if value.show(ui, entries) { + press(actions, Facet::Language(*format)); } - }, - ); + } + }); } #[cfg(test)] @@ -793,10 +610,7 @@ mod tests { kind, ..NotePatch::default() }; - let (ops, note) = ( - patch(Some(vec!["ops".into()]), None), - patch(None, Some(NoteKind::Note)), - ); + let (ops, note) = (patch(Some(vec!["ops".into()]), None), patch(None, Some(NoteKind::Note))); engine::db::run_here(backend.engine(), move |engine| { engine::notes::update_note(engine, &tagged, &ops)?; engine::notes::update_note(engine, &prose, ¬e) @@ -808,15 +622,11 @@ mod tests { } fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } fn rect_of(harness: &Harness<'_, Bench>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } /// The words painted inside `within`, and where each stands. @@ -827,9 +637,7 @@ mod tests { .filter_map(|clipped| match &clipped.shape { egui::Shape::Text(text) => { let rect = text.galley.rect.translate(text.pos.to_vec2()); - within - .contains_rect(rect) - .then(|| (text.galley.text().to_owned(), rect)) + within.contains_rect(rect).then(|| (text.galley.text().to_owned(), rect)) } _ => None, }) @@ -841,10 +649,7 @@ mod tests { .query_all_by(|node| node.author_id() == Some(author_id)) .map(|node| { let words = painted(harness, node.rect()); - words - .last() - .map(|(text, _)| text.clone()) - .unwrap_or_default() + words.last().map(|(text, _)| text.clone()).unwrap_or_default() }) .collect() } @@ -860,17 +665,7 @@ mod tests { .iter() .flat_map(|kind| names(&harness, &format!("kind-chip-{kind}"))) .collect(); - assert_eq!( - values, - [ - "All", - "Snippets", - "Notes", - "Tasks", - "Calculations", - "Drawings" - ] - ); + assert_eq!(values, ["All", "Snippets", "Notes", "Tasks", "Calculations", "Drawings"]); assert_eq!(count_in(&harness, "kind-chip-all"), ["3"]); assert_eq!(count_in(&harness, "kind-chip-snippet"), ["2"]); assert_eq!(count_in(&harness, "kind-chip-note"), ["1"]); @@ -885,29 +680,12 @@ mod tests { click_id(&mut harness, "kind-chip-note"); assert_eq!(cards(&harness), 1); - assert!( - harness - .state() - .state - .notes_query - .facets() - .kinds - .contains(&NoteKind::Note) - ); - assert!( - has(&harness, "kind-chip-all"), - "the menu stays open on a tick" - ); + assert!(harness.state().state.notes_query.facets().kinds.contains(&NoteKind::Note)); + assert!(has(&harness, "kind-chip-all"), "the menu stays open on a tick"); let toggle = harness.get_by(|node| node.author_id() == Some("facets-toggle")); - assert!( - toggle.accesskit_node().is_disabled(), - "it holds open while a value is ticked" - ); + assert!(toggle.accesskit_node().is_disabled(), "it holds open while a value is ticked"); let menu = harness.get_by(|node| node.author_id() == Some("facet-menu-kind")); - assert_eq!( - menu.accesskit_node().label().as_deref(), - Some("Type, 1 ticked") - ); + assert_eq!(menu.accesskit_node().label().as_deref(), Some("Type, 1 ticked")); click_id(&mut harness, "kind-chip-all"); @@ -952,9 +730,7 @@ mod tests { assert!(!has(&harness, "kind-chip-all"), "the menu closed"); assert_eq!(cards(&harness), 2, "the value stays ticked"); assert!( - harness - .get_by(|node| node.author_id() == Some("facet-menu-kind")) - .is_focused(), + harness.get_by(|node| node.author_id() == Some("facet-menu-kind")).is_focused(), "the focus is back on the group's control" ); @@ -966,17 +742,13 @@ mod tests { #[test] fn the_keys_open_a_menu_walk_it_and_tick() { let mut harness = three(); - harness - .get_by(|node| node.author_id() == Some("facet-menu-kind")) - .focus(); + harness.get_by(|node| node.author_id() == Some("facet-menu-kind")).focus(); settle(&mut harness); harness.key_press(egui::Key::Space); settle(&mut harness); assert!( - harness - .get_by(|node| node.author_id() == Some("kind-chip-all")) - .is_focused(), + harness.get_by(|node| node.author_id() == Some("kind-chip-all")).is_focused(), "the first value takes the focus" ); harness.key_press(egui::Key::ArrowDown); @@ -996,22 +768,14 @@ mod tests { /// Every control of the band on one line, inside the area, a value of each group ticked. fn one_line(harness: &Harness<'_, Bench>) { - let ids = [ - "facet-menu-kind", - "facet-menu-tag", - "facet-menu-language", - "clear-filters", - ]; + let ids = ["facet-menu-kind", "facet-menu-tag", "facet-menu-language", "clear-filters"]; let rects: Vec = ids.iter().map(|id| rect_of(harness, id)).collect(); let middle = rects[0].center().y; let width = harness.ctx.content_rect().width(); for (id, rect) in ids.iter().zip(&rects) { assert!((rect.center().y - middle).abs() < 1.0, "{id} {rect:?}"); assert!(rect.right() <= width, "{id} runs past {width}: {rect:?}"); - assert!( - rect.width() >= 24.0 && rect.height() >= 24.0, - "{id} {rect:?}" - ); + assert!(rect.width() >= 24.0 && rect.height() >= 24.0, "{id} {rect:?}"); } } @@ -1041,10 +805,7 @@ mod tests { let ids: Vec = (0..4) .map(|n| testing::note(&backend, &format!("v2 n°{n}")).id.clone()) .collect(); - let tagged = NotePatch { - tags: Some(vec!["v2".into()]), - ..NotePatch::default() - }; + let tagged = NotePatch { tags: Some(vec!["v2".into()]), ..NotePatch::default() }; engine::db::run_here(backend.engine(), move |engine| { for id in &ids { engine::notes::update_note(engine, id, &tagged)?; @@ -1057,16 +818,9 @@ mod tests { click_id(&mut harness, "facet-menu-tag"); let pill = harness.get_by(|node| node.author_id() == Some("tag-pill")); - assert_eq!( - pill.accesskit_node().label().as_deref(), - Some("v2"), - "the count stays out" - ); + assert_eq!(pill.accesskit_node().label().as_deref(), Some("v2"), "the count stays out"); let words = painted(&harness, pill.rect()); - assert!( - words.iter().all(|(text, _)| !text.starts_with('#')), - "{words:?}" - ); + assert!(words.iter().all(|(text, _)| !text.starts_with('#')), "{words:?}"); let rect_of = |text: &str| { words .iter() @@ -1076,21 +830,135 @@ mod tests { }; let (name, count) = (rect_of("v2"), rect_of("4")); let p = crate::theme::palette(&harness.ctx); - let badge = harness - .output() - .shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Rect(shape) - if shape.fill == p.bg_3 - && shape.rect.contains_rect(count) - && shape.rect.width() < pill.rect().width() / 2.0 => - { - Some(shape.rect) - } - _ => None, - }); + let badge = harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Rect(shape) + if shape.fill == p.bg_3 + && shape.rect.contains_rect(count) + && shape.rect.width() < pill.rect().width() / 2.0 => + { + Some(shape.rect) + } + _ => None, + }); let badge = badge.expect("the count sits on a badge of its own"); assert!(badge.left() > name.right(), "{name:?} {badge:?}"); } + + /// Two notes of one tag, language and level each, and one with none; the band open. + fn faceted() -> Harness<'static, Bench> { + use engine::notes::language::Language; + use engine::notes::priority::Priority; + + let (backend, profile) = testing::unlocked(); + for (title, tag, language, priority) in [ + ("a", "ops", Language::Sh, Priority::High), + ("b", "ops", Language::Sh, Priority::High), + ("c", "db", Language::Sql, Priority::Low), + ] { + let id = testing::note(&backend, title).id.clone(); + let patch = NotePatch { + tags: Some(vec![tag.to_owned()]), + language: Some(language), + ..NotePatch::default() + }; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + engine::notes::set_priority(engine, &[id], priority) + }) + .unwrap(); + } + testing::note(&backend, "bare"); + let mut harness = area(backend, profile); + click_id(&mut harness, "facets-toggle"); + harness + } + + /// A value narrows, the two of a group widen, « All » gives every card back. + #[test] + fn each_group_narrows_by_its_values_and_all_undoes_it() { + for (menu, values, every) in [ + ("facet-menu-priority", "priority-chip-high", "priority-chip-all"), + ("facet-menu-tag", "tag-pill", "tag-all"), + ("facet-menu-language", "language-chip", "language-all"), + ] { + let mut harness = faceted(); + assert_eq!(cards(&harness), 4); + click_id(&mut harness, menu); + let value = harness.query_all_by(|node| node.author_id() == Some(values)).last().unwrap(); + value.click(); + settle(&mut harness); + let narrowed = cards(&harness); + assert!(narrowed == 1 || narrowed == 2, "{menu}: {narrowed}"); + assert!(has(&harness, every), "{menu} stays open"); + + click_id(&mut harness, every); + assert_eq!(cards(&harness), 4, "{menu}"); + } + } + + #[test] + fn two_levels_ticked_show_the_notes_of_either() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-priority"); + click_id(&mut harness, "priority-chip-high"); + assert_eq!(cards(&harness), 2); + click_id(&mut harness, "priority-chip-low"); + assert_eq!(cards(&harness), 3); + click_id(&mut harness, "priority-chip-high"); + assert_eq!(cards(&harness), 1); + } + + /// From the most pressing, each with its count; « none » is no level. + #[test] + fn the_levels_go_from_the_most_pressing_down() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-priority"); + let levels: Vec = harness + .query_all_by(|node| node.author_id().is_some_and(|id| id.starts_with("priority-chip-"))) + .filter_map(|node| node.accesskit_node().author_id().map(str::to_owned)) + .collect(); + + assert_eq!( + levels, + [ + "priority-chip-all", + "priority-chip-urgent", + "priority-chip-high", + "priority-chip-medium", + "priority-chip-low", + ] + ); + } + + /// Nothing to narrow by, nothing offered. + #[test] + fn a_group_with_no_value_is_not_offered() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "bare"); + let mut harness = area(backend, profile); + click_id(&mut harness, "facets-toggle"); + + assert!(has(&harness, "facet-menu-kind")); + assert!(!has(&harness, "facet-menu-priority") && !has(&harness, "facet-menu-tag")); + } + + #[test] + fn the_arrows_walk_a_menu_up_as_well_as_down() { + let mut harness = faceted(); + click_id(&mut harness, "facet-menu-kind"); + let focused = |harness: &Harness<'_, Bench>| { + harness + .query_all_by(|node| node.author_id().is_some_and(|id| id.starts_with("kind-chip-"))) + .position(|node| node.is_focused()) + }; + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + harness.key_press(egui::Key::ArrowDown); + settle(&mut harness); + let down = focused(&harness).unwrap(); + harness.key_press(egui::Key::ArrowUp); + settle(&mut harness); + + assert_eq!(focused(&harness), Some(down - 1)); + } } diff --git a/crates/ui/src/notes/header/layout.rs b/crates/ui/src/notes/header/layout.rs index e0f540d39..e67fa4f36 100644 --- a/crates/ui/src/notes/header/layout.rs +++ b/crates/ui/src/notes/header/layout.rs @@ -16,14 +16,8 @@ struct Floor { two_rows: f32, } -const SEARCH: Floor = Floor { - one_row: 220.0, - two_rows: 140.0, -}; -const SWITCHER: Floor = Floor { - one_row: 110.0, - two_rows: 72.0, -}; +const SEARCH: Floor = Floor { one_row: 220.0, two_rows: 140.0 }; +const SWITCHER: Floor = Floor { one_row: 110.0, two_rows: 72.0 }; /// What does not narrow, as last drawn, gaps inside each group included: the same in one row /// and in two. @@ -53,11 +47,7 @@ pub(super) fn plan(width: f32, fixed: Fixed, switchers: &[f32], new_note: f32) - // The search gives way first, then the switchers' names. let search = (room - natural).clamp(SEARCH.one_row, SEARCH_WIDEST); let switcher = share(room - search, count, SWITCHER.one_row); - return Plan { - two_rows: false, - search, - switcher, - }; + return Plan { two_rows: false, search, switcher }; } let first = width - fixed.place - new_note - GAP; Plan { @@ -82,10 +72,7 @@ mod tests { (a - b).abs() < 0.01 } - const FIXED: Fixed = Fixed { - place: 200.0, - look: 300.0, - }; + const FIXED: Fixed = Fixed { place: 200.0, look: 300.0 }; #[test] fn the_search_gives_way_before_the_switchers_then_two_rows() { @@ -112,9 +99,6 @@ mod tests { fn without_switchers_only_the_search_narrows() { let plan = plan(1_100.0, FIXED, &[], 140.0); assert!(!plan.two_rows); - assert!(same( - plan.search, - SEARCH_WIDEST.min(1_100.0 - 500.0 - 140.0 - 20.0) - )); + assert!(same(plan.search, SEARCH_WIDEST.min(1_100.0 - 500.0 - 140.0 - 20.0))); } } diff --git a/crates/ui/src/notes/header/mod.rs b/crates/ui/src/notes/header/mod.rs index 4ff0fbbea..55ebba90a 100644 --- a/crates/ui/src/notes/header/mod.rs +++ b/crates/ui/src/notes/header/mod.rs @@ -56,11 +56,8 @@ pub(super) fn show( #[expect(clippy::cast_possible_truncation, reason = "a few points")] let grid = s.grid.round() as i8; let language = state.language; - let switchers = if switchers_shown(state) { - switchers::natural_widths(ui, state).to_vec() - } else { - Vec::new() - }; + let switchers = + if switchers_shown(state) { switchers::natural_widths(ui, state).to_vec() } else { Vec::new() }; let new_note = new_note::width(ui, language); let width = ui.available_width() - 2.0 * BAR_INSET; let plan = layout::plan(width, view.fixed, &switchers, new_note); @@ -80,33 +77,19 @@ pub(super) fn show( #[expect(clippy::cast_possible_truncation, reason = "a few points")] let (inset, above) = (BAR_INSET as i8, ((BAR_HEIGHT - BAR_TOGGLE) / 2.0) as i8); let shown = egui::Frame::new() - .inner_margin(Margin { - left: inset, - right: inset, - top: above, - bottom: grid, - }) + .inner_margin(Margin { left: inset, right: inset, top: above, bottom: grid }) .show(ui, |ui| { ui.spacing_mut().item_spacing = Vec2::new(GAP, gap::CONTROLS); let facets = (open, pressed); if plan.two_rows { let _ = row(ui, |ui| { - fixed.place = group(ui, |ui| { - where_one_is(ui, state, view, plan.switcher, actions) - }); + fixed.place = group(ui, |ui| where_one_is(ui, state, view, plan.switcher, actions)); new_note_at_end(ui, state, new_note, actions); }); if ticked.is_empty() { view.look_height = row(ui, |ui| { fixed.look = group(ui, |ui| { - how_one_looks( - ui, - state, - (plan.search, facets), - view, - focus_search, - actions, - ) + how_one_looks(ui, state, (plan.search, facets), view, focus_search, actions) }); }); } else { @@ -114,18 +97,9 @@ pub(super) fn show( } } else if ticked.is_empty() { view.look_height = row(ui, |ui| { - fixed.place = group(ui, |ui| { - where_one_is(ui, state, view, plan.switcher, actions) - }); + fixed.place = group(ui, |ui| where_one_is(ui, state, view, plan.switcher, actions)); fixed.look = group(ui, |ui| { - how_one_looks( - ui, - state, - (plan.search, facets), - view, - focus_search, - actions, - ) + how_one_looks(ui, state, (plan.search, facets), view, focus_search, actions) }); new_note_at_end(ui, state, new_note, actions); }); @@ -142,8 +116,7 @@ pub(super) fn show( } let rect = shown.response.rect; let p = palette(ui.ctx()); - ui.painter() - .hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); if open { ui.add_space(gap::HAIRLINE); ui.scope(|ui| { @@ -164,10 +137,7 @@ fn switchers_shown(state: &AppState) -> bool { fn row(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) -> f32 { let size = Vec2::new(ui.available_width(), ROW_HEIGHT); let layout = egui::Layout::left_to_right(egui::Align::Center); - ui.allocate_ui_with_layout(size, layout, draw) - .response - .rect - .height() + ui.allocate_ui_with_layout(size, layout, draw).response.rect.height() } /// A group of controls side by side; answers the width of what in it does not narrow. @@ -214,16 +184,11 @@ fn how_one_looks( (NoteFilter::Untriaged, keys::filters::UNTRIAGED), ] .map(|(filter, key)| (filter, i18n::translate(language, key, &[]))); - let filters: Vec<(NoteFilter, &str)> = filters - .iter() - .map(|(filter, label)| (*filter, label.as_str())) - .collect(); + let filters: Vec<(NoteFilter, &str)> = + filters.iter().map(|(filter, label)| (*filter, label.as_str())).collect(); search(ui, state, width, focus_search, actions); let mut chosen = state.notes_query.filter(); - if Segmented::new(&filters, "quick-filter") - .show(ui, &mut chosen) - .changed() - { + if Segmented::new(&filters, "quick-filter").show(ui, &mut chosen).changed() { push(actions, crate::notes::Action::SetFilter(chosen)); } sort::show(ui, state, actions); @@ -239,22 +204,11 @@ fn facets_toggle(ui: &mut Ui, open: bool, pressed: usize, language: i18n::Langua let label = i18n::translate(language, keys::filters::FACETS_LABEL, &[]); let enabled = !(open && pressed > 0); let count = (pressed > 0).then(|| { - widgets::text( - ui, - &pressed.to_string(), - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.amber_text, - ) + widgets::text(ui, &pressed.to_string(), font::CAPTION, 600.0, FontFamily::Proportional, p.amber_text) }); let counted = count.as_ref().map_or(0.0, |galley| galley.size().x + 4.0); let corner = CornerRadius::same(radius::CONTROL); - let sense = if enabled { - Sense::click() - } else { - Sense::hover() - }; + let sense = if enabled { Sense::click() } else { Sense::hover() }; let response = interact( ui, Vec2::new(14.0 + 16.0 + counted, 32.0), @@ -267,11 +221,7 @@ fn facets_toggle(ui: &mut Ui, open: bool, pressed: usize, language: i18n::Langua }, corner, ); - let hover = if enabled { - widgets::hovered(ui, &response) - } else { - 0.0 - }; + let hover = if enabled { widgets::hovered(ui, &response) } else { 0.0 }; let lit = if open { 1.0 } else { hover }; let rect = response.rect; ui.painter().rect( @@ -281,14 +231,9 @@ fn facets_toggle(ui: &mut Ui, open: bool, pressed: usize, language: i18n::Langua Stroke::new(1.0, widgets::towards(p.line_soft, p.amber_dim, lit)), StrokeKind::Inside, ); - let ink = if open { - p.amber_text - } else { - widgets::towards(p.text_1, p.text_0, hover) - }; + let ink = if open { p.amber_text } else { widgets::towards(p.text_1, p.text_0, hover) }; let left = rect.center().x - f32::midpoint(16.0, counted); - let glyph = - egui::Rect::from_min_size(egui::pos2(left, rect.center().y - 8.0), Vec2::splat(16.0)); + let glyph = egui::Rect::from_min_size(egui::pos2(left, rect.center().y - 8.0), Vec2::splat(16.0)); crate::theme::icons::paint(ui, glyph, Icon::Filter, ink); if let Some(count) = count { let rect_count = egui::Rect::from_min_size( @@ -318,12 +263,7 @@ fn where_one_is( let label = i18n::translate(state.language, keys::sidebar::TOGGLE, &[]); let shown = state.settings.rail_shown; if widgets::SquareButton::new(Icon::Sidebar, &label, "library-rail-toggle") - .keys( - state - .settings - .bindings - .of(crate::services::shortcuts::RAIL_ACTION), - ) + .keys(state.settings.bindings.of(crate::services::shortcuts::RAIL_ACTION)) .pressed(shown) .show(ui) .clicked() @@ -332,13 +272,8 @@ fn where_one_is( } // Away from the filters and the primary action: a view on the notes, not a filter. let trash = i18n::translate(state.language, keys::notes::TRASH, &[]); - if widgets::SquareButton::new(Icon::Trash, &trash, "trash-open") - .show(ui) - .clicked() - { - actions.push(Action::Notes(crate::notes::Action::Trash( - crate::notes::Trash::Open, - ))); + if widgets::SquareButton::new(Icon::Trash, &trash, "trash-open").show(ui).clicked() { + actions.push(Action::Notes(crate::notes::Action::Trash(crate::notes::Trash::Open))); } let open = state.active_folder().and_then(|id| state.folders.find(id)); if let Some(folder) = open { @@ -360,36 +295,18 @@ fn push(actions: &mut Actions, action: crate::notes::Action) { actions.push(Action::Notes(action)); } -fn search( - ui: &mut Ui, - state: &AppState, - width: f32, - focus_search: &mut bool, - actions: &mut Actions, -) { +fn search(ui: &mut Ui, state: &AppState, width: f32, focus_search: &mut bool, actions: &mut Actions) { let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let query = &state.notes_query; let mut typed = query.typed().to_owned(); // Zero results is the answer that matters most: said, never left quiet. The board's own // count while it shows: it dims what the list would drop. - let matched = if state.board_place().is_some() { - state.board.matched() - } else { - query.matched() - }; - let matched = matched.map(|count| { - i18n::translate( - language, - keys::notes::SEARCH_MATCHED, - &[("count", count.into())], - ) - }); - let (label, hint, clear) = ( - tr(keys::notes::SEARCH_LABEL), - tr(keys::notes::SEARCH_PLACEHOLDER), - tr(keys::notes::CLEAR_SEARCH), - ); + let matched = if state.board_place().is_some() { state.board.matched() } else { query.matched() }; + let matched = matched + .map(|count| i18n::translate(language, keys::notes::SEARCH_MATCHED, &[("count", count.into())])); + let (label, hint, clear) = + (tr(keys::notes::SEARCH_LABEL), tr(keys::notes::SEARCH_PLACEHOLDER), tr(keys::notes::CLEAR_SEARCH)); let key = "Ctrl+K"; let searched = SearchField::new(&mut typed, &label, "search-input") .hint(&hint) @@ -403,8 +320,7 @@ fn search( field.request_focus(); } // Down from the field to what it found: the first card. - if widgets::takes_keys(ui, &field) && ui.input(|input| input.key_pressed(egui::Key::ArrowDown)) - { + if widgets::takes_keys(ui, &field) && ui.input(|input| input.key_pressed(egui::Key::ArrowDown)) { push( actions, crate::notes::Action::Canvas(crate::notes::canvas::shortcuts::CanvasKey::Move( @@ -435,20 +351,8 @@ fn view_switch(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.horizontal(|ui| { let space = state.spaces.active_space(); let on_board = state.board_place().is_some(); - let list = option( - ui, - &tr(keys::board::LIST_VIEW), - "view-list", - !on_board, - true, - ); - let board = option( - ui, - &tr(keys::board::BOARD_VIEW), - "view-board", - on_board, - space.is_some(), - ); + let list = option(ui, &tr(keys::board::LIST_VIEW), "view-list", !on_board, true); + let board = option(ui, &tr(keys::board::BOARD_VIEW), "view-board", on_board, space.is_some()); if space.is_none() { widgets::tooltip(board.clone(), &tr(keys::board::NEEDS_ASPACE)); } @@ -466,20 +370,9 @@ fn view_switch(ui: &mut Ui, state: &AppState, actions: &mut Actions) { fn option(ui: &mut Ui, label: &str, author_id: &str, on: bool, enabled: bool) -> Response { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - label, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, label, font::LABEL, 400.0, FontFamily::Proportional, p.text_2); let corner = CornerRadius::same(radius::CONTROL); - let sense = if enabled { - Sense::click() - } else { - Sense::hover() - }; + let sense = if enabled { Sense::click() } else { Sense::hover() }; let response = interact( ui, galley.size() + Vec2::new(24.0, 10.0), @@ -499,21 +392,10 @@ fn option(ui: &mut Ui, label: &str, author_id: &str, on: bool, enabled: bool) -> } else { (Color32::TRANSPARENT, p.text_2) }; - let ink = if enabled { - ink - } else { - ink.gamma_multiply(0.45) - }; - ui.painter().rect( - response.rect, - corner, - fill, - Stroke::NONE, - StrokeKind::Inside, - ); + let ink = if enabled { ink } else { ink.gamma_multiply(0.45) }; + ui.painter().rect(response.rect, corner, fill, Stroke::NONE, StrokeKind::Inside); let galley = widgets::text(ui, label, font::LABEL, 400.0, FontFamily::Proportional, ink); - ui.painter() - .galley(response.rect.center() - galley.size() / 2.0, galley, ink); + ui.painter().galley(response.rect.center() - galley.size() / 2.0, galley, ink); response } diff --git a/crates/ui/src/notes/header/new_note.rs b/crates/ui/src/notes/header/new_note.rs index ec1d7d914..d590c499c 100644 --- a/crates/ui/src/notes/header/new_note.rs +++ b/crates/ui/src/notes/header/new_note.rs @@ -2,8 +2,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Role, Sense, - Stroke, Ui, Vec2, WidgetInfo, pos2, + CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, RectAlign, Response, Role, Sense, Stroke, Ui, + Vec2, WidgetInfo, pos2, }; use engine::notes::kind::NoteKind; use i18n::{Key, keys}; @@ -17,31 +17,11 @@ use crate::widgets::{self, SplitButton, SplitKind, interact}; /// Each kind and its words, in the menu's order. const KINDS: [(NoteKind, Key, Key); 5] = [ - ( - NoteKind::Snippet, - keys::notes::NEW_SNIPPET, - keys::notes::kind_lines::SNIPPET, - ), - ( - NoteKind::Note, - keys::notes::NEW_RICH_NOTE, - keys::notes::kind_lines::NOTE, - ), - ( - NoteKind::Checklist, - keys::notes::NEW_CHECKLIST, - keys::notes::kind_lines::CHECKLIST, - ), - ( - NoteKind::Calc, - keys::notes::NEW_CALC, - keys::notes::kind_lines::CALC, - ), - ( - NoteKind::Drawing, - keys::notes::NEW_DRAWING, - keys::notes::kind_lines::DRAWING, - ), + (NoteKind::Snippet, keys::notes::NEW_SNIPPET, keys::notes::kind_lines::SNIPPET), + (NoteKind::Note, keys::notes::NEW_RICH_NOTE, keys::notes::kind_lines::NOTE), + (NoteKind::Checklist, keys::notes::NEW_CHECKLIST, keys::notes::kind_lines::CHECKLIST), + (NoteKind::Calc, keys::notes::NEW_CALC, keys::notes::kind_lines::CALC), + (NoteKind::Drawing, keys::notes::NEW_DRAWING, keys::notes::kind_lines::DRAWING), ]; const MENU_WIDTH: f32 = 340.0; @@ -57,11 +37,7 @@ pub(super) fn width(ui: &Ui, language: i18n::Language) -> f32 { } fn split<'a>(label: &'a str, kinds: &'a str) -> SplitButton<'a> { - SplitButton::new( - (label, "new-note"), - (kinds, "new-note-kind"), - SplitKind::Primary, - ) + SplitButton::new((label, "new-note"), (kinds, "new-note-kind"), SplitKind::Primary) } pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { @@ -81,16 +57,8 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.spacing_mut().item_spacing.y = gap::LINE; let p = palette(ui.ctx()); let title = tr(keys::notes::CREATE_MENU_TITLE).to_uppercase(); - let galley = widgets::text( - ui, - &title, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, _) = - ui.allocate_exact_size(Vec2::new(galley.size().x, 22.0), Sense::hover()); + let galley = widgets::text(ui, &title, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); + let (rect, _) = ui.allocate_exact_size(Vec2::new(galley.size().x, 22.0), Sense::hover()); ui.painter() .galley(pos2(rect.left() + 10.0, rect.top() + 6.0), galley, p.text_2); for (kind, name, line) in KINDS { @@ -131,17 +99,9 @@ fn kind_item(ui: &mut Ui, kind: NoteKind, (name, line): (&str, &str), keys: &str tile(ui, rect.min + Vec2::splat(PADDING), kind); let left = rect.left() + PADDING + TILE + GAP; let top = rect.top() + PADDING; - let name = widgets::text( - ui, - name, - font::READING, - 600.0, - FontFamily::Proportional, - p.text_1, - ); + let name = widgets::text(ui, name, font::READING, 600.0, FontFamily::Proportional, p.text_1); ui.painter().galley(pos2(left, top), name, p.text_1); - ui.painter() - .galley(pos2(left, top + NAME_HEIGHT + 3.0), line, p.text_2); + ui.painter().galley(pos2(left, top + NAME_HEIGHT + 3.0), line, p.text_2); key_caps(ui, keys, rect.right() - PADDING, rect.center().y); response } @@ -155,20 +115,11 @@ fn tile(ui: &Ui, at: egui::Pos2, kind: NoteKind) { fn key_cap_text(ui: &Ui, word: &str) -> std::sync::Arc { let colour = palette(ui.ctx()).text_1; - widgets::text( - ui, - word, - font::CAPTION, - 400.0, - FontFamily::Monospace, - colour, - ) + widgets::text(ui, word, font::CAPTION, 400.0, FontFamily::Monospace, colour) } fn key_caps_width(ui: &Ui, keys: &str) -> f32 { - keys.split('+') - .map(|word| key_cap_text(ui, word).size().x + 12.0 + 3.0) - .sum() + keys.split('+').map(|word| key_cap_text(ui, word).size().x + 12.0 + 3.0).sum() } /// One cap a key, the last ending at `right`. @@ -186,8 +137,7 @@ fn key_caps(ui: &Ui, keys: &str, right: f32, middle: f32) { Stroke::new(1.0, p.line), egui::StrokeKind::Inside, ); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, p.text_1); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text_1); right = rect.left() - 3.0; } } diff --git a/crates/ui/src/notes/header/selection.rs b/crates/ui/src/notes/header/selection.rs index f1a4c3116..04524d88b 100644 --- a/crates/ui/src/notes/header/selection.rs +++ b/crates/ui/src/notes/header/selection.rs @@ -16,13 +16,8 @@ use crate::theme::icons::Icon; use crate::theme::palette; use crate::widgets::{self, Button, IconButton, Kind, MenuItem, TextField}; -const LEVELS: [Priority; 5] = [ - Priority::None, - Priority::Low, - Priority::Medium, - Priority::High, - Priority::Urgent, -]; +const LEVELS: [Priority; 5] = + [Priority::None, Priority::Low, Priority::Medium, Priority::High, Priority::Urgent]; const GAP: f32 = gap::CONTROLS; const TAG_WIDTH: f32 = 120.0; @@ -56,11 +51,7 @@ fn shown(state: &AppState) -> Vec> { return state .board .cards() - .map(|entry| Shown { - id: &entry.note.id, - pinned: entry.note.pinned, - tags: &entry.note.tags, - }) + .map(|entry| Shown { id: &entry.note.id, pinned: entry.note.pinned, tags: &entry.note.tags }) .collect(); } state @@ -68,11 +59,7 @@ fn shown(state: &AppState) -> Vec> { .view() .map(|view| { view.cards() - .map(|card| Shown { - id: &card.id, - pinned: card.pinned, - tags: &card.tags, - }) + .map(|card| Shown { id: &card.id, pinned: card.pinned, tags: &card.tags }) .collect() }) .unwrap_or_default() @@ -108,16 +95,10 @@ pub(super) fn show( let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let cards = shown(state); - let ticked: Vec<&Shown<'_>> = cards - .iter() - .filter(|card| checked.iter().any(|id| id == card.id)) - .collect(); + let ticked: Vec<&Shown<'_>> = + cards.iter().filter(|card| checked.iter().any(|id| id == card.id)).collect(); let all_pinned = ticked.iter().all(|card| card.pinned); - let pin = tr(if all_pinned { - keys::selection::UNPIN - } else { - keys::selection::PIN - }); + let pin = tr(if all_pinned { keys::selection::UNPIN } else { keys::selection::PIN }); let kept = kept(ui, state, (view, &pin, checked.len()), room); ui.spacing_mut().item_spacing = vec2(GAP, 0.0); count(ui, checked.len(), language); @@ -135,50 +116,31 @@ pub(super) fn show( } more(ui, state, (view, &ticked, &pin, all_pinned), kept, actions); let clear = tr(keys::selection::CLEAR); - if IconButton::new(Icon::X, &clear, "selection-clear") - .show(ui) - .clicked() - { + if IconButton::new(Icon::X, &clear, "selection-clear").show(ui).clicked() { actions.push(Action::Notes(crate::notes::Action::ClearSelection)); } } /// The count, the trash, « … » and the cross always; then, while they hold, the tag field, the /// pin and the move — given up the other way round. A move with no space to go to takes no room. -fn kept( - ui: &Ui, - state: &AppState, - (view, pin, count): (&SelectionView, &str, usize), - room: f32, -) -> usize { +fn kept(ui: &Ui, state: &AppState, (view, pin, count): (&SelectionView, &str, usize), room: f32) -> usize { let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let ink = palette(ui.ctx()).text_1; let width = |label: &str, size: f32, weight: f32| { - widgets::text(ui, label, size, weight, FontFamily::Proportional, ink) - .size() - .x + widgets::text(ui, label, size, weight, FontFamily::Proportional, ink).size().x }; let button = |label: &str| width(label, 12.0, 400.0) + 24.0; - let delete = - button(&tr(keys::selection::DELETE)).max(button(&tr(keys::selection::DELETE_CONFIRM))); + let delete = button(&tr(keys::selection::DELETE)).max(button(&tr(keys::selection::DELETE_CONFIRM))); let counted = width(&count_words(count, language), 12.5, 600.0) + 4.0; let icons = 2.0 * (widgets::MIN_TARGET + 8.0); // While it is asked for, the tag field takes the trash's place. - let (tag, delete) = if view.tagging { - (0.0, TAG_WIDTH) - } else { - (TAG_WIDTH, delete) - }; + let (tag, delete) = if view.tagging { (0.0, TAG_WIDTH) } else { (TAG_WIDTH, delete) }; let mut left = room - counted - icons - delete - 3.0 * GAP; let wanted = [ tag, button(pin), - if state.spaces.spaces().is_empty() { - 0.0 - } else { - button(&tr(keys::selection::MOVE_TO)) - }, + if state.spaces.spaces().is_empty() { 0.0 } else { button(&tr(keys::selection::MOVE_TO)) }, ]; wanted .iter() @@ -228,14 +190,7 @@ fn count_words(count: usize, language: i18n::Language) -> String { fn count(ui: &mut Ui, count: usize, language: i18n::Language) { let p = palette(ui.ctx()); let words = count_words(count, language); - let galley = widgets::text( - ui, - &words, - font::BODY, - 600.0, - FontFamily::Proportional, - p.amber_text, - ); + let galley = widgets::text(ui, &words, font::BODY, 600.0, FontFamily::Proportional, p.amber_text); let (rect, response) = ui.allocate_exact_size(galley.size() + vec2(4.0, 0.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "selection-count"); @@ -243,17 +198,9 @@ fn count(ui: &mut Ui, count: usize, language: i18n::Language) { } /// A tag typed then Enter, onto every ticked note. -fn tag_field( - ui: &mut Ui, - view: &mut SelectionView, - actions: &mut Actions, - language: i18n::Language, -) { +fn tag_field(ui: &mut Ui, view: &mut SelectionView, actions: &mut Actions, language: i18n::Language) { let tr = |key| i18n::translate(language, key, &[]); - let (label, hint) = ( - tr(keys::selection::ADD_TAG_LABEL), - tr(keys::selection::ADD_TAG_PLACEHOLDER), - ); + let (label, hint) = (tr(keys::selection::ADD_TAG_LABEL), tr(keys::selection::ADD_TAG_PLACEHOLDER)); let field = ui .allocate_ui(vec2(TAG_WIDTH, 32.0), |ui| { TextField::new(&mut view.tag_draft, &label, "selection-tag") @@ -278,11 +225,7 @@ fn tag_field( /// Two clicks: the first arms it. fn delete(ui: &mut Ui, view: &mut SelectionView, actions: &mut Actions, language: i18n::Language) { - let key = if view.confirm_delete { - keys::selection::DELETE_CONFIRM - } else { - keys::selection::DELETE - }; + let key = if view.confirm_delete { keys::selection::DELETE_CONFIRM } else { keys::selection::DELETE }; let delete = i18n::translate(language, key, &[]); let deleting = Button::new(&delete, "selection-delete") .kind(Kind::Destructive) @@ -305,10 +248,7 @@ fn named<'a>(words: impl Iterator, prefix: &str) -> Vec<(String, } fn entries(named: &[(String, String)]) -> Vec> { - named - .iter() - .map(|(words, author_id)| MenuItem::new(words, author_id)) - .collect() + named.iter().map(|(words, author_id)| MenuItem::new(words, author_id)).collect() } /// « … »: the priority, the tags to take off, the copy, and what the row had no room for. @@ -323,10 +263,8 @@ fn more( let tr = |key| i18n::translate(language, key, &[]); let spaces = state.spaces.spaces(); let levels: Vec = LEVELS.iter().map(|level| tr(level_key(*level))).collect(); - let mut carried: Vec<&str> = ticked - .iter() - .flat_map(|card| card.tags.iter().map(String::as_str)) - .collect(); + let mut carried: Vec<&str> = + ticked.iter().flat_map(|card| card.tags.iter().map(String::as_str)).collect(); carried.sort_unstable(); carried.dedup(); let priorities = named(levels.iter().map(String::as_str), "selection-more-priority"); @@ -368,11 +306,7 @@ fn more( let Some(picked) = widgets::menu(&trigger, &items) else { return; }; - let rank = |prefix: &str| { - picked - .strip_prefix(prefix) - .and_then(|rest| rest.parse::().ok()) - }; + let rank = |prefix: &str| picked.strip_prefix(prefix).and_then(|rest| rest.parse::().ok()); if picked == "selection-more-move" { Popup::open_id(ui.ctx(), places_id); } else if let Some(level) = rank("selection-more-priority-").and_then(|at| LEVELS.get(at)) { @@ -401,6 +335,7 @@ fn level_key(level: Priority) -> i18n::Key { #[cfg(test)] mod tests { + use super::*; use egui::Modifiers; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -454,11 +389,7 @@ mod tests { #[test] fn no_bar_until_a_card_is_ticked_then_it_counts_them() { let (mut harness, _) = three(); - assert!( - harness - .query_by(|node| node.author_id() == Some("selection-count")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("selection-count")).is_none()); ctrl_click(&mut harness, "one"); ctrl_click(&mut harness, "two"); @@ -509,11 +440,7 @@ mod tests { assert_eq!(cards(&harness), 3); click_id(&mut harness, "selection-delete"); assert_eq!(cards(&harness), 2); - assert!( - harness - .query_by(|node| node.author_id() == Some("selection-count")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("selection-count")).is_none()); } #[test] @@ -535,8 +462,7 @@ mod tests { .unwrap(); harness .get_by(|node| { - node.author_id() == Some("note-card-open") - && node.label().as_deref() == Some(title.as_str()) + node.author_id() == Some("note-card-open") && node.label().as_deref() == Some(title.as_str()) }) .click_modifiers(Modifiers::SHIFT); settle(&mut harness); @@ -544,11 +470,7 @@ mod tests { harness.key_press(egui::Key::Escape); settle(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("selection-count")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("selection-count")).is_none()); } fn card_box(harness: &Harness<'_, Bench>, title: &str) -> egui::accesskit::Rect { @@ -575,11 +497,7 @@ mod tests { .accesskit_node() .bounding_box() .unwrap(); - assert!( - row.y1 < first, - "the row ends at {}, the cards start at {first}", - row.y1 - ); + assert!(row.y1 < first, "the row ends at {}, the cards start at {first}", row.y1); } #[test] @@ -592,11 +510,7 @@ mod tests { harness.set_size(egui::vec2(640.0, 700.0)); settle(&mut harness); ctrl_click(&mut harness, "one"); - assert!( - harness - .query_by(|node| node.author_id() == Some("selection-move")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("selection-move")).is_none()); click_id(&mut harness, "selection-more"); click_id(&mut harness, "selection-more-move"); @@ -605,4 +519,99 @@ mod tests { assert_eq!(stored(&harness, &one).space_id, archive.id); } + + fn more(harness: &mut Harness<'_, Bench>, entry: &str) { + click_id(harness, "selection-more"); + click_id(harness, entry); + } + + /// By its sub-menu: the entry opens it, the rank in it is chosen. + fn more_of(harness: &mut Harness<'_, Bench>, entry: &str, rank: usize) { + click_id(harness, "selection-more"); + harness.get_by(|node| node.author_id() == Some(entry)).focus(); + settle(harness); + harness.key_press(egui::Key::ArrowRight); + settle(harness); + click_id(harness, &format!("{entry}-{rank}")); + } + + #[test] + fn every_ticked_note_takes_the_level_chosen() { + let (mut harness, [one, two, three]) = three(); + ctrl_click(&mut harness, "one"); + ctrl_click(&mut harness, "two"); + for (rank, level) in LEVELS.into_iter().enumerate() { + more_of(&mut harness, "selection-more-priority", rank); + assert_eq!(stored(&harness, &one).priority, level); + assert_eq!(stored(&harness, &two).priority, level); + } + assert_eq!(stored(&harness, &three).priority, Priority::None); + } + + /// The tags any of them carries, each once, in their order. + #[test] + fn a_tag_of_any_ticked_note_can_be_taken_off() { + let (mut harness, [one, two, _]) = three(); + for (id, tags) in [(&one, ["ops", "db"]), (&two, ["ops", "api"])] { + let (id, tags) = (id.clone(), tags.map(str::to_owned).to_vec()); + let patch = engine::notes::model::NotePatch { tags: Some(tags), ..Default::default() }; + engine::db::run_here(harness.state().backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch) + }) + .unwrap(); + } + let bench = harness.state_mut(); + bench.state.apply( + Action::Notes(crate::notes::Action::Reload), + &egui::Context::default(), + &bench.backend, + ); + settle(&mut harness); + ctrl_click(&mut harness, "one"); + ctrl_click(&mut harness, "two"); + more_of(&mut harness, "selection-more-untag", 2); + + assert_eq!(stored(&harness, &one).tags, ["db"]); + assert_eq!(stored(&harness, &two).tags, ["api"]); + } + + #[test] + fn with_no_tag_to_take_off_it_is_not_offered() { + let (mut harness, _) = three(); + ctrl_click(&mut harness, "one"); + click_id(&mut harness, "selection-more"); + + let offered = |id: &str| harness.query_by(|node| node.author_id() == Some(id)).is_some(); + assert!(offered("selection-more-priority") && !offered("selection-more-untag")); + } + + #[test] + fn the_ticked_notes_are_copied_as_markdown() { + let (mut harness, _) = three(); + ctrl_click(&mut harness, "one"); + more(&mut harness, "selection-more-copy"); + crate::notes::bench::until(&mut harness, "it is copied", |harness| { + harness.state().state.status.latest().is_some() + }); + } + + /// Narrow, the row keeps the count: the rest is asked for under « … ». + #[test] + fn narrow_the_tag_and_the_pin_are_asked_for_under_more() { + let (mut harness, [one, ..]) = three(); + harness.set_size(egui::vec2(640.0, 700.0)); + settle(&mut harness); + ctrl_click(&mut harness, "one"); + more(&mut harness, "selection-more-pin"); + assert!(stored(&harness, &one).pinned); + more(&mut harness, "selection-more-pin"); + assert!(!stored(&harness, &one).pinned); + + // Narrower still: a rail drawn wide leaves the canvas little. + harness.set_size(egui::vec2(500.0, 700.0)); + settle(&mut harness); + more(&mut harness, "selection-more-tag"); + crate::notes::bench::type_and_enter(&mut harness, "selection-tag", "ops"); + assert_eq!(stored(&harness, &one).tags, ["ops"]); + } } diff --git a/crates/ui/src/notes/header/sort.rs b/crates/ui/src/notes/header/sort.rs index cea297530..195bde940 100644 --- a/crates/ui/src/notes/header/sort.rs +++ b/crates/ui/src/notes/header/sort.rs @@ -4,8 +4,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, Response, Role, Sense, Stroke, - StrokeKind, Ui, Vec2, WidgetInfo, pos2, + CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, + Vec2, WidgetInfo, pos2, }; use engine::notes::view::{Grouping, NoteOrder, SortDirection, SortKey}; use i18n::{Key, keys}; @@ -46,11 +46,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { /// 32 × 32, a glyph; the order in words once the window is wide enough for it. fn trigger(ui: &mut Ui, label: &str, now: &str, words: bool) -> Response { let p = palette(ui.ctx()); - let width = if words { - widgets::arrowed(ui, None, now, font::LABEL, p.text_1) + 14.0 - } else { - 32.0 - }; + let width = if words { widgets::arrowed(ui, None, now, font::LABEL, p.text_1) + 14.0 } else { 32.0 }; let corner = CornerRadius::same(radius::CONTROL); let response = interact( ui, @@ -62,27 +58,12 @@ fn trigger(ui: &mut Ui, label: &str, now: &str, words: bool) -> Response { ); let open = Popup::is_id_open(ui.ctx(), Popup::default_response_id(&response)); let lit = open || response.hovered(); - let (edge, ink) = if lit { - (p.amber_dim, p.amber_text) - } else { - (p.line_soft, p.text_1) - }; - ui.painter().rect( - response.rect, - corner, - p.bg_2, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + let (edge, ink) = if lit { (p.amber_dim, p.amber_text) } else { (p.line_soft, p.text_1) }; + ui.painter() + .rect(response.rect, corner, p.bg_2, Stroke::new(1.0, edge), StrokeKind::Inside); if words { let rect = response.rect; - widgets::arrowed( - ui, - Some(pos2(rect.left() + 7.0, rect.center().y)), - now, - font::LABEL, - ink, - ); + widgets::arrowed(ui, Some(pos2(rect.left() + 7.0, rect.center().y)), now, font::LABEL, ink); } else { let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(16.0)); icons::paint(ui, glyph, Icon::ArrowUpDown, ink); @@ -98,38 +79,17 @@ fn menu(ui: &mut Ui, now: Arrangement, language: i18n::Language) -> Option Option Option, author_id: &str, on: bool) -> bool { let p = palette(ui.ctx()); let corner = CornerRadius::same(radius::CONTROL); - let role = if author_id == "sort-pinned-first" { - Role::MenuItemCheckBox - } else { - Role::MenuItemRadio - }; + let role = if author_id == "sort-pinned-first" { Role::MenuItemCheckBox } else { Role::MenuItemRadio }; let response = interact( ui, Vec2::new(ui.available_width(), 26.0), @@ -193,17 +136,10 @@ fn item(ui: &mut Ui, label: &str, hint: Option<&str>, author_id: &str, on: bool) } let ink = if on { p.text_0 } else { p.text_1 }; if on { - let glyph = - Rect::from_center_size(pos2(rect.left() + 14.0, rect.center().y), Vec2::splat(12.0)); + let glyph = Rect::from_center_size(pos2(rect.left() + 14.0, rect.center().y), Vec2::splat(12.0)); icons::paint(ui, glyph, Icon::Check, p.amber_text); } - let words = widgets::arrowed( - ui, - Some(pos2(rect.left() + 28.0, rect.center().y)), - label, - font::BODY, - ink, - ); + let words = widgets::arrowed(ui, Some(pos2(rect.left() + 28.0, rect.center().y)), label, font::BODY, ink); let mut needed = 28.0 + words + 8.0; if let Some(hint) = hint { let width = widgets::arrowed(ui, None, hint, font::META, p.text_2); diff --git a/crates/ui/src/notes/header/switchers.rs b/crates/ui/src/notes/header/switchers.rs index 05da9c3f5..9205ef60a 100644 --- a/crates/ui/src/notes/header/switchers.rs +++ b/crates/ui/src/notes/header/switchers.rs @@ -4,8 +4,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, Response, Role, Sense, Stroke, - StrokeKind, Ui, Vec2, WidgetInfo, pos2, + CornerRadius, FontFamily, Popup, PopupCloseBehavior, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, + Vec2, WidgetInfo, pos2, }; use engine::folders::model::{Folder, Lineage}; use i18n::keys; @@ -58,14 +58,7 @@ pub(super) fn natural_widths(ui: &Ui, state: &AppState) -> [f32; 2] { fn switch_width(ui: &Ui, name: &str) -> f32 { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, name, font::BODY, 400.0, FontFamily::Proportional, p.text_0); galley.size().x.min(NAME_WIDTH) + 44.0 } @@ -82,13 +75,7 @@ pub(super) fn space_switcher( let spaces = &state.spaces; let active = spaces.active_space(); let name = space_name(state); - let button = switch( - ui, - &tr(keys::notes::SPACE_SWITCHER_LABEL), - &name, - "space-switcher", - widest, - ); + let button = switch(ui, &tr(keys::notes::SPACE_SWITCHER_LABEL), &name, "space-switcher", widest); let width = button.rect.width(); let shown = Popup::menu(&button) .frame(widgets::menu_frame(ui.ctx())) @@ -111,15 +98,11 @@ pub(super) fn space_switcher( } } Menu::Space(edit) => { - let Some(space) = spaces.spaces().iter().find(|space| space.id == edit.id) - else { + let Some(space) = spaces.spaces().iter().find(|space| space.id == edit.id) else { return; }; - let others: Vec<_> = spaces - .spaces() - .iter() - .filter(|other| other.id != space.id) - .collect(); + let others: Vec<_> = + spaces.spaces().iter().filter(|other| other.id != space.id).collect(); let contents = spaces.contents(&space.id); if panel::space(ui, edit, space, &others, contents, language, actions) { ui.close(); @@ -139,18 +122,10 @@ pub(super) fn space_switcher( ); let mark = space.pinned.then_some(Mark::Pin); let on = active == Some(space.id.as_str()); - let (chosen, edit) = row( - ui, - (&space.name, "space-option"), - (&options, "space-edit"), - mark, - on, - ); + let (chosen, edit) = + row(ui, (&space.name, "space-option"), (&options, "space-edit"), mark, on); if chosen.clicked() { - push( - actions, - crate::notes::Action::ChooseSpace(Some(space.id.clone())), - ); + push(actions, crate::notes::Action::ChooseSpace(Some(space.id.clone()))); ui.close(); } if edit.clicked() { @@ -189,13 +164,7 @@ pub(super) fn folder_switcher( .filter(|folder| space.is_none_or(|space| folder.space_id == space)) .collect(); let name = folder_name(state); - let button = switch( - ui, - &tr(keys::folders::SWITCHER_LABEL), - &name, - "folder-switcher", - widest, - ); + let button = switch(ui, &tr(keys::folders::SWITCHER_LABEL), &name, "folder-switcher", widest); let width = button.rect.width(); let shown = Popup::menu(&button) .frame(widgets::menu_frame(ui.ctx())) @@ -261,24 +230,12 @@ fn folder_list( ui.close(); } for folder in folders { - let options = i18n::translate( - language, - keys::folders::OPTIONS_LABEL, - &[("name", folder.name.as_str().into())], - ); + let options = + i18n::translate(language, keys::folders::OPTIONS_LABEL, &[("name", folder.name.as_str().into())]); let mark = Some(Mark::Swatch(folder_hue(ui, folder.colour))); - let (chosen, edit) = row( - ui, - (&folder.name, "folder-option"), - (&options, "folder-edit"), - mark, - false, - ); + let (chosen, edit) = row(ui, (&folder.name, "folder-option"), (&options, "folder-edit"), mark, false); if chosen.clicked() { - push( - actions, - crate::notes::Action::ChooseFolder(folder.id.clone()), - ); + push(actions, crate::notes::Action::ChooseFolder(folder.id.clone())); ui.close(); } if edit.clicked() { @@ -292,11 +249,7 @@ fn folder_list( *menu = Menu::Creating(Draft::default()); } } else { - note( - ui, - &tr(keys::folders::NEEDS_ASPACE), - "folder-create-blocked", - ); + note(ui, &tr(keys::folders::NEEDS_ASPACE), "folder-create-blocked"); } } @@ -316,21 +269,10 @@ pub(super) fn breadcrumb( .spaces() .iter() .find(|space| space.id == folder.space_id) - .map_or_else( - || i18n::translate(language, keys::notes::ALL_SPACES, &[]), - |space| space.name.clone(), - ); - let back = crumb( - ui, - &format!("‹ {space_name}"), - "folder-breadcrumb-back", - None, - ); + .map_or_else(|| i18n::translate(language, keys::notes::ALL_SPACES, &[]), |space| space.name.clone()); + let back = crumb(ui, &format!("‹ {space_name}"), "folder-breadcrumb-back", None); if back.clicked() { - push( - actions, - crate::notes::Action::ChooseSpace(Some(folder.space_id.clone())), - ); + push(actions, crate::notes::Action::ChooseSpace(Some(folder.space_id.clone()))); } separator(ui, "/"); let inside: Vec<&Folder> = state @@ -339,11 +281,7 @@ pub(super) fn breadcrumb( .iter() .filter(|other| other.space_id == folder.space_id) .collect(); - let lineage = Lineage::new( - inside - .iter() - .map(|other| (other.id.clone(), other.parent_id.clone())), - ); + let lineage = Lineage::new(inside.iter().map(|other| (other.id.clone(), other.parent_id.clone()))); let path = lineage.path(&folder.id); for id in path.iter().take(path.len().saturating_sub(1)) { let Some(above) = inside.iter().find(|other| other.id == *id) else { @@ -351,40 +289,22 @@ pub(super) fn breadcrumb( }; let hue = folder_hue(ui, above.colour); if crumb(ui, &above.name, "folder-breadcrumb-step", Some(hue)).clicked() { - push( - actions, - crate::notes::Action::ChooseFolder(above.id.clone()), - ); + push(actions, crate::notes::Action::ChooseFolder(above.id.clone())); } separator(ui, "›"); } let hue = folder_hue(ui, folder.colour); - let galley = widgets::text( - ui, - &folder.name, - font::BODY, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, &folder.name, font::BODY, 600.0, FontFamily::Proportional, p.text_0); let (rect, here) = ui.allocate_exact_size(galley.size() + Vec2::new(14.0, 8.0), Sense::hover()); here.widget_info(|| WidgetInfo::labeled(Role::Label, true, &folder.name)); widgets::address(ui, &here, "folder-breadcrumb-name"); let swatch = Rect::from_center_size(pos2(rect.left() + 4.0, rect.center().y), Vec2::splat(8.0)); + ui.painter().rect_filled(swatch, CornerRadius::same(radius::MARK), hue); ui.painter() - .rect_filled(swatch, CornerRadius::same(radius::MARK), hue); - ui.painter().galley( - pos2(rect.left() + 14.0, rect.center().y - galley.size().y / 2.0), - galley, - p.text_0, - ); - let options = i18n::translate( - language, - keys::folders::OPTIONS_LABEL, - &[("name", folder.name.as_str().into())], - ); - let menu = - widgets::IconButton::new(Icon::Ellipsis, &options, "folder-breadcrumb-menu").show(ui); + .galley(pos2(rect.left() + 14.0, rect.center().y - galley.size().y / 2.0), galley, p.text_0); + let options = + i18n::translate(language, keys::folders::OPTIONS_LABEL, &[("name", folder.name.as_str().into())]); + let menu = widgets::IconButton::new(Icon::Ellipsis, &options, "folder-breadcrumb-menu").show(ui); let shown = Popup::menu(&menu) .frame(widgets::menu_frame(ui.ctx())) .close_behavior(PopupCloseBehavior::CloseOnClickOutside) @@ -404,14 +324,7 @@ pub(super) fn breadcrumb( /// A switcher's button: its name cut to its room, and the chevron. fn switch(ui: &mut Ui, label: &str, name: &str, author_id: &str, widest: f32) -> Response { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - name, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, name, font::BODY, 400.0, FontFamily::Proportional, p.text_0); let width = switch_width(ui, name).min(widest); let room = width - 44.0; let corner = CornerRadius::same(radius::MENU); @@ -423,37 +336,21 @@ fn switch(ui: &mut Ui, label: &str, name: &str, author_id: &str, widest: f32) -> || WidgetInfo::labeled(Role::Button, true, label), corner, ); - let lit = - response.hovered() || Popup::is_id_open(ui.ctx(), Popup::default_response_id(&response)); + let lit = response.hovered() || Popup::is_id_open(ui.ctx(), Popup::default_response_id(&response)); let edge = if lit { p.amber_dim } else { p.line_soft }; let rect = response.rect; - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, p.bg_2, Stroke::new(1.0, edge), StrokeKind::Inside); let left = rect.left() + 12.0; - let shown = if galley.size().x > room { - cut(ui, name, room) - } else { - galley - }; - let text_rect = Rect::from_min_size( - pos2(left, rect.center().y - shown.size().y / 2.0), - shown.size(), - ); + let shown = if galley.size().x > room { cut(ui, name, room) } else { galley }; + let text_rect = Rect::from_min_size(pos2(left, rect.center().y - shown.size().y / 2.0), shown.size()); // In a child: allocated in the row, the name would bring the row's cursor back. let mut inside = ui.new_child(egui::UiBuilder::new().max_rect(text_rect)); let named = inside.allocate_rect(text_rect, Sense::hover()); named.widget_info(|| WidgetInfo::labeled(Role::Label, true, name)); widgets::address(&inside, &named, &format!("{author_id}-name")); ui.painter().galley(text_rect.min, shown, p.text_0); - let chevron = Rect::from_center_size( - pos2(rect.right() - 16.0, rect.center().y), - Vec2::splat(12.0), - ); + let chevron = Rect::from_center_size(pos2(rect.right() - 16.0, rect.center().y), Vec2::splat(12.0)); icons::paint(ui, chevron, Icon::ArrowDown, p.text_2); response } @@ -462,10 +359,7 @@ fn cut(ui: &Ui, words: &str, width: f32) -> std::sync::Arc { let p = palette(ui.ctx()); let mut job = egui::text::LayoutJob::single_section( words.to_owned(), - egui::TextFormat::simple( - egui::FontId::new(font::BODY, FontFamily::Proportional), - p.text_0, - ), + egui::TextFormat::simple(egui::FontId::new(font::BODY, FontFamily::Proportional), p.text_0), ); job.wrap = egui::text::TextWrapping { max_width: width, @@ -507,14 +401,7 @@ fn row( .inner } -fn entry( - ui: &mut Ui, - width: f32, - label: &str, - author_id: &str, - mark: Option, - on: bool, -) -> Response { +fn entry(ui: &mut Ui, width: f32, label: &str, author_id: &str, mark: Option, on: bool) -> Response { let p = palette(ui.ctx()); let corner = CornerRadius::same(radius::CONTROL); let response = interact( @@ -527,8 +414,7 @@ fn entry( ); let rect = response.rect; if on { - ui.painter() - .rect_filled(rect, corner, p.amber_text.gamma_multiply(0.08)); + ui.painter().rect_filled(rect, corner, p.amber_text.gamma_multiply(0.08)); } else if response.hovered() { ui.painter().rect_filled(rect, corner, p.bg_3); } @@ -548,29 +434,20 @@ fn entry( } Some(Mark::Swatch(hue)) => { let swatch = Rect::from_center_size(pos2(left + 4.0, middle), Vec2::splat(8.0)); - ui.painter() - .rect_filled(swatch, CornerRadius::same(radius::MARK), hue); + ui.painter().rect_filled(swatch, CornerRadius::same(radius::MARK), hue); left += 14.0; } None => {} } let galley = cut(ui, label, rect.right() - 8.0 - left); - ui.painter() - .galley(pos2(left, middle - galley.size().y / 2.0), galley, ink); + ui.painter().galley(pos2(left, middle - galley.size().y / 2.0), galley, ink); response } /// A step of the breadcrumb: a quiet button, its folder's hue before it. fn crumb(ui: &mut Ui, label: &str, author_id: &str, hue: Option) -> Response { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - label, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, label, font::BODY, 400.0, FontFamily::Proportional, p.text_1); let swatch = if hue.is_some() { 14.0 } else { 0.0 }; let corner = CornerRadius::same(radius::CONTROL); let response = interact( @@ -589,17 +466,12 @@ fn crumb(ui: &mut Ui, label: &str, author_id: &str, hue: Option) p.text_1 }; if let Some(hue) = hue { - let at = - Rect::from_center_size(pos2(rect.left() + 11.0, rect.center().y), Vec2::splat(8.0)); - ui.painter() - .rect_filled(at, CornerRadius::same(radius::MARK), hue); + let at = Rect::from_center_size(pos2(rect.left() + 11.0, rect.center().y), Vec2::splat(8.0)); + ui.painter().rect_filled(at, CornerRadius::same(radius::MARK), hue); } let galley = widgets::text(ui, label, font::BODY, 400.0, FontFamily::Proportional, ink); ui.painter().galley( - pos2( - rect.left() + 7.0 + swatch, - rect.center().y - galley.size().y / 2.0, - ), + pos2(rect.left() + 7.0 + swatch, rect.center().y - galley.size().y / 2.0), galley, ink, ); @@ -608,33 +480,16 @@ fn crumb(ui: &mut Ui, label: &str, author_id: &str, hue: Option) fn separator(ui: &mut Ui, mark: &str) { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - mark, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, mark, font::BODY, 400.0, FontFamily::Proportional, p.text_2); let (rect, _) = ui.allocate_exact_size(galley.size() + Vec2::new(4.0, 0.0), Sense::hover()); - ui.painter() - .galley(rect.min + Vec2::new(2.0, 0.0), galley, p.text_2); + ui.painter().galley(rect.min + Vec2::new(2.0, 0.0), galley, p.text_2); } fn note(ui: &mut Ui, words: &str, author_id: &str) { let p = palette(ui.ctx()); - let galley = widgets::text( - ui, - words, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, response) = - ui.allocate_exact_size(galley.size() + Vec2::new(20.0, 10.0), Sense::hover()); + let galley = widgets::text(ui, words, font::META, 400.0, FontFamily::Proportional, p.text_2); + let (rect, response) = ui.allocate_exact_size(galley.size() + Vec2::new(20.0, 10.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); widgets::address(ui, &response, author_id); - ui.painter() - .galley(rect.min + Vec2::new(10.0, 5.0), galley, p.text_2); + ui.painter().galley(rect.min + Vec2::new(10.0, 5.0), galley, p.text_2); } diff --git a/crates/ui/src/notes/header/tests.rs b/crates/ui/src/notes/header/tests.rs index 5944da2f5..42b08307d 100644 --- a/crates/ui/src/notes/header/tests.rs +++ b/crates/ui/src/notes/header/tests.rs @@ -1,17 +1,16 @@ //! The header over a real core: what it asks changes what the canvas shows. +use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use engine::notes::model::NotePatch; -use engine::notes::view::Grouping; +use engine::notes::view::{Grouping, SortKey}; -use crate::notes::bench::{area, cards, click, click_id, remembered, settle, until}; -use crate::state::notes_query::{ARRANGEMENT_KEY, Arrangement}; +use crate::notes::bench::{Bench, area, cards, click, click_id, remembered, settle, until}; +use crate::state::notes_query::{ARRANGEMENT_KEY, Arrangement, DIRECTIONS, SORT_KEYS, natural_order}; use crate::testing; fn headings(harness: &egui_kittest::Harness<'_, crate::notes::bench::Bench>) -> usize { - harness - .query_all_by(|node| node.author_id() == Some("note-section")) - .count() + harness.query_all_by(|node| node.author_id() == Some("note-section")).count() } #[test] @@ -25,9 +24,7 @@ fn a_search_narrows_the_canvas_once_the_keys_rest_and_its_cross_empties_it() { harness .get_by(|node| node.author_id() == Some("search-input")) .type_text("PSQL"); - until(&mut harness, "the search narrowed the canvas", |harness| { - cards(harness) == 1 - }); + until(&mut harness, "the search narrowed the canvas", |harness| cards(harness) == 1); let matched = harness .get_by(|node| node.author_id() == Some("search-matched")) @@ -37,11 +34,7 @@ fn a_search_narrows_the_canvas_once_the_keys_rest_and_its_cross_empties_it() { assert_eq!(matched, "1 result"); click_id(&mut harness, "search-clear"); assert_eq!(cards(&harness), 2); - assert!( - harness - .query_by(|node| node.author_id() == Some("search-matched")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("search-matched")).is_none()); } #[test] @@ -55,9 +48,7 @@ fn nothing_found_is_still_a_count() { .get_by(|node| node.author_id() == Some("search-input")) .type_text("nothing matches this"); until(&mut harness, "the canvas says nothing matches", |harness| { - harness - .query_by(|node| node.author_id() == Some("canvas-no-results")) - .is_some() + harness.query_by(|node| node.author_id() == Some("canvas-no-results")).is_some() }); let matched = harness @@ -73,14 +64,9 @@ fn the_quick_filter_keeps_the_pinned_notes() { let (backend, profile) = testing::unlocked(); let pinned = testing::note(&backend, "pinned").id.clone(); testing::note(&backend, "loose"); - let patch = NotePatch { - pinned: Some(true), - ..NotePatch::default() - }; - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &pinned, &patch) - }) - .unwrap(); + let patch = NotePatch { pinned: Some(true), ..NotePatch::default() }; + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &pinned, &patch)) + .unwrap(); let mut harness = area(backend, profile); assert_eq!(cards(&harness), 2); @@ -104,10 +90,7 @@ fn a_grouping_chosen_lays_the_canvas_out_and_is_the_librarys() { // The menu stays open: order, direction and grouping are set together. harness.get_by(|node| node.author_id() == Some("sort-pinned-first")); let mut stored = crate::services::preferences::Preferences::default(); - stored.set( - ARRANGEMENT_KEY, - &remembered(&harness, ARRANGEMENT_KEY).unwrap(), - ); + stored.set(ARRANGEMENT_KEY, &remembered(&harness, ARRANGEMENT_KEY).unwrap()); assert_eq!(Arrangement::read(&stored).grouping, Grouping::None); } @@ -119,11 +102,7 @@ fn ctrl_k_puts_the_caret_in_the_search() { harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::K); settle(&mut harness); - assert!( - harness - .get_by(|node| node.author_id() == Some("search-input")) - .is_focused() - ); + assert!(harness.get_by(|node| node.author_id() == Some("search-input")).is_focused()); } #[test] @@ -146,25 +125,14 @@ fn the_switchers_take_the_rails_place_when_it_is_put_away() { testing::note(&backend, "in home"); let work = crate::notes::bench::space(&backend, "Work"); let mut harness = area(backend, profile); - assert!( - harness - .query_by(|node| node.author_id() == Some("space-switcher")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("space-switcher")).is_none()); hide_the_rail(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("space-option")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("space-option")).is_none()); click_id(&mut harness, "space-switcher"); click(&mut harness, "space-option", "Work"); - assert_eq!( - harness.state().state.spaces.active_space(), - Some(work.id.as_str()) - ); + assert_eq!(harness.state().state.spaces.active_space(), Some(work.id.as_str())); let name = harness .get_by(|node| node.author_id() == Some("space-switcher-name")) .accesskit_node() @@ -209,10 +177,7 @@ fn a_folder_open_is_a_breadcrumb_back_to_its_space() { .unwrap_or_default(); assert_eq!(here, "api"); click(&mut harness, "folder-breadcrumb-step", "Runbooks"); - assert_eq!( - harness.state().state.active_folder(), - Some(runbooks.id.as_str()) - ); + assert_eq!(harness.state().state.active_folder(), Some(runbooks.id.as_str())); click_id(&mut harness, "folder-breadcrumb-back"); assert_eq!(harness.state().state.active_folder(), None); harness.get_by(|node| node.author_id() == Some("folder-switcher")); @@ -228,10 +193,7 @@ fn the_kind_menu_opens_a_draft_of_its_kind() { click_id(&mut harness, "new-note-checklist"); let opened = harness.state().state.editor.opened().unwrap(); - assert_eq!( - opened.note().unwrap().kind, - engine::notes::kind::NoteKind::Checklist - ); + assert_eq!(opened.note().unwrap().kind, engine::notes::kind::NoteKind::Checklist); harness.get_by(|node| node.author_id() == Some("editor-title")); } @@ -239,10 +201,7 @@ fn the_kind_menu_opens_a_draft_of_its_kind() { #[test] fn a_moved_new_note_key_is_the_one_shown() { use crate::services::shortcuts::{ACTIONS, Bindings}; - let action = *ACTIONS - .iter() - .find(|action| action.id == "canvas.newSnippet") - .unwrap(); + let action = *ACTIONS.iter().find(|action| action.id == "canvas.newSnippet").unwrap(); let mut bindings = Bindings::default(); bindings.set(action, "Ctrl+Alt+N".to_owned()); @@ -251,3 +210,242 @@ fn a_moved_new_note_key_is_the_one_shown() { bindings.of(action) ); } + +// The order + +fn arrangement(harness: &Harness<'_, Bench>) -> Arrangement { + harness.state().state.notes_query.arrangement() +} + +fn sorting() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "psql prod"); + let mut harness = area(backend, profile); + click_id(&mut harness, "sort-trigger"); + harness +} + +fn choose(harness: &mut Harness<'_, Bench>, author_id: &str, rank: usize) { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .nth(rank) + .unwrap() + .click(); + settle(harness); +} + +/// The newest first, the titles from A, the most urgent first. +#[test] +fn a_sort_key_starts_the_way_it_reads_first() { + for (rank, key) in SORT_KEYS.into_iter().enumerate() { + let mut harness = sorting(); + let (grouping, pinned_first) = (arrangement(&harness).grouping, arrangement(&harness).pinned_first); + choose(&mut harness, "sort-key", rank); + + let now = arrangement(&harness); + assert_eq!(now.order, natural_order(key), "{key:?}"); + assert_eq!((now.grouping, now.pinned_first), (grouping, pinned_first), "{key:?}"); + } +} + +#[test] +fn the_direction_turns_round_without_the_key() { + let mut harness = sorting(); + for (rank, direction) in DIRECTIONS.into_iter().enumerate().rev() { + choose(&mut harness, "sort-direction", rank); + let order = arrangement(&harness).order; + assert_eq!((order.direction, order.key), (direction, SortKey::Modified)); + } +} + +#[test] +fn the_pinned_notes_stand_first_or_not() { + let mut harness = sorting(); + let before = arrangement(&harness).pinned_first; + choose(&mut harness, "sort-pinned-first", 0); + assert_eq!(arrangement(&harness).pinned_first, !before); + choose(&mut harness, "sort-pinned-first", 0); + assert_eq!(arrangement(&harness).pinned_first, before); +} + +/// It is a choice of the menu, not a way back to the key's own direction. +#[test] +fn the_key_in_force_chosen_again_changes_nothing() { + let mut harness = sorting(); + choose(&mut harness, "sort-direction", 1); + let before = arrangement(&harness); + let rank = SORT_KEYS.iter().position(|key| *key == before.order.key).unwrap(); + choose(&mut harness, "sort-key", rank); + + assert_eq!(arrangement(&harness), before); +} + +#[test] +fn a_wide_window_says_the_order_in_words() { + let mut harness = sorting(); + let said = |harness: &Harness<'_, Bench>| { + harness.get_by(|node| node.author_id() == Some("sort-trigger")).rect().width() + }; + assert!(said(&harness) <= 32.0); + harness.set_size(egui::vec2(1_400.0, 700.0)); + settle(&mut harness); + + assert!(said(&harness) > 60.0); +} + +// The switchers + +/// A library of two spaces, the rail put away, the switcher `id` open. +fn switching(id: &str) -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "in home"); + crate::notes::bench::space(&backend, "Work"); + let home = crate::notes::bench::spaces_of_backend(&backend)[0].clone(); + crate::notes::bench::folder(&backend, &home, None, "Runbooks"); + let mut harness = area(backend, profile); + hide_the_rail(&mut harness); + click_id(&mut harness, id); + harness +} + +fn present(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn retype(harness: &mut Harness<'_, Bench>, author_id: &str, words: &str) { + harness.get_by(|node| node.author_id() == Some(author_id)).focus(); + settle(harness); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + crate::notes::bench::type_and_enter(harness, author_id, words); +} + +#[test] +fn every_space_is_one_choice_of_the_switcher() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "space-switcher"); + click_id(&mut harness, "space-option-all"); + + assert_eq!(harness.state().state.spaces.active_space(), None); + assert!(!present(&harness, "space-option"), "it closed"); +} + +#[test] +fn a_space_is_renamed_and_pinned_from_its_options() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-edit", "Options for space Work"); + click_id(&mut harness, "space-pin"); + let work = |harness: &Harness<'_, Bench>| { + let spaces = crate::notes::bench::spaces_of(harness); + spaces + .into_iter() + .find(|space| space.name == "Work" || space.name == "Job") + .unwrap() + }; + assert!(work(&harness).pinned); + + retype(&mut harness, "space-rename-input", "Job"); + assert_eq!(work(&harness).name, "Job"); + assert!(!present(&harness, "space-rename-input"), "Enter closed it"); +} + +#[test] +fn a_space_deleted_hands_its_notes_to_the_other_once_confirmed() { + let mut harness = switching("space-switcher"); + let home = crate::notes::bench::spaces_of(&harness) + .into_iter() + .find(|space| space.name != "Work") + .unwrap(); + click(&mut harness, "space-edit", &format!("Options for space {}", home.name)); + click_id(&mut harness, "space-delete"); + assert_eq!(crate::notes::bench::spaces_of(&harness).len(), 2, "asked first"); + click_id(&mut harness, "space-delete"); + + let spaces = crate::notes::bench::spaces_of(&harness); + assert_eq!(spaces.iter().map(|space| space.name.as_str()).collect::>(), ["Work"]); + assert_eq!(cards(&harness), 1); +} + +/// Opened again, it is the list. +#[test] +fn a_panel_left_open_is_not_there_the_next_time() { + for (switcher, edit, name, field) in [ + ("space-switcher", "space-edit", "Options for space Work", "space-rename-input"), + ("folder-switcher", "folder-edit", "Options for folder Runbooks", "folder-rename-input"), + ] { + let mut harness = switching(switcher); + click(&mut harness, edit, name); + assert!(present(&harness, field)); + harness.key_press(egui::Key::Escape); + settle(&mut harness); + click_id(&mut harness, switcher); + assert!(!present(&harness, field) && present(&harness, edit), "{switcher}"); + } +} + +#[test] +fn a_folder_is_made_in_the_space_shown() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "folder-switcher"); + click_id(&mut harness, "folder-create-open"); + crate::notes::bench::type_and_enter(&mut harness, "folder-create-input", "Backlog"); + + let work = harness.state().state.spaces.active_space().unwrap().to_owned(); + let folders = harness.state().state.folders.list(); + let made = folders.iter().find(|folder| folder.name == "Backlog").unwrap(); + assert_eq!((made.space_id.as_str(), made.parent_id.as_deref()), (work.as_str(), None)); +} + +/// Across every space, nothing says which one it would be in. +#[test] +fn no_folder_is_made_across_every_space() { + let harness = switching("folder-switcher"); + + assert!(present(&harness, "folder-option"), "every folder is listed"); + assert!(present(&harness, "folder-create-blocked")); + assert!(!present(&harness, "folder-create-open")); +} + +#[test] +fn the_folder_switcher_lists_the_folders_of_the_space_shown() { + let mut harness = switching("space-switcher"); + click(&mut harness, "space-option", "Work"); + click_id(&mut harness, "folder-switcher"); + assert!(!present(&harness, "folder-option")); + + click_id(&mut harness, "folder-option-all"); + assert!(!present(&harness, "folder-option-all"), "it closed"); +} + +#[test] +fn a_folder_is_renamed_and_deleted_from_its_options() { + let mut harness = switching("folder-switcher"); + click(&mut harness, "folder-edit", "Options for folder Runbooks"); + retype(&mut harness, "folder-rename-input", "Guides"); + let named = |harness: &Harness<'_, Bench>| -> Vec { + let folders = harness.state().state.folders.list(); + folders.iter().map(|folder| folder.name.clone()).collect() + }; + assert_eq!(named(&harness), ["Guides"]); + + click_id(&mut harness, "folder-switcher"); + click(&mut harness, "folder-edit", "Options for folder Guides"); + click_id(&mut harness, "folder-delete"); + assert_eq!(named(&harness).len(), 1, "asked first"); + click_id(&mut harness, "folder-delete"); + assert!(named(&harness).is_empty()); +} + +#[test] +fn the_folder_open_is_told_from_the_breadcrumb() { + let mut harness = switching("folder-switcher"); + click(&mut harness, "folder-option", "Runbooks"); + click_id(&mut harness, "folder-breadcrumb-menu"); + retype(&mut harness, "folder-rename-input", "Guides"); + + assert_eq!(harness.state().state.folders.list()[0].name, "Guides"); +} diff --git a/crates/ui/src/notes/language.rs b/crates/ui/src/notes/language.rs index 8f11f50a3..b4c8d9685 100644 --- a/crates/ui/src/notes/language.rs +++ b/crates/ui/src/notes/language.rs @@ -76,11 +76,7 @@ pub fn name(language: Language) -> &'static str { /// The name, where the label does not already say it. pub fn hint(language: Language) -> &'static str { let name = name(language); - if name.eq_ignore_ascii_case(label(language)) { - "" - } else { - name - } + if name.eq_ignore_ascii_case(label(language)) { "" } else { name } } pub fn hue(language: Language) -> Hue { @@ -155,18 +151,8 @@ mod tests { assert!(text::highlight::has_syntax(name), "{language:?}: {name}"); } } - let common = [ - Language::Json, - Language::Ts, - Language::Py, - Language::Rs, - Language::Sql, - ]; - assert!( - common - .into_iter() - .all(|language| syntax(language).is_some()) - ); + let common = [Language::Json, Language::Ts, Language::Py, Language::Rs, Language::Sql]; + assert!(common.into_iter().all(|language| syntax(language).is_some())); assert_eq!(syntax(Language::Txt), None); } diff --git a/crates/ui/src/notes/mod.rs b/crates/ui/src/notes/mod.rs index 2069a2fbd..c5ac9620b 100644 --- a/crates/ui/src/notes/mod.rs +++ b/crates/ui/src/notes/mod.rs @@ -314,16 +314,9 @@ pub enum Trash { #[derive(Debug, Clone, PartialEq, Eq)] pub enum BoardGesture { /// `folder`: the zone under the card, `None` the ground, which files it in the board's root. - DropCard { - note_id: String, - folder: Option, - at: engine::folders::board::BoardPoint, - }, + DropCard { note_id: String, folder: Option, at: engine::folders::board::BoardPoint }, /// Moved or resized: a frame, either way. - MoveZone { - folder_id: String, - frame: engine::folders::board::BoardFrame, - }, + MoveZone { folder_id: String, frame: engine::folders::board::BoardFrame }, /// A band on the empty ground, which asks for a name. DrawZone(engine::folders::board::BoardFrame), /// The cards a right-button sweep went over, ticked. @@ -332,10 +325,7 @@ pub enum BoardGesture { SelectFolder(String), /// Let go of over a row of the rail: filed there at any depth, `None` the top of the space. /// Offered back: it may land out of sight. - FileOnRail { - note_id: String, - folder: Option, - }, + FileOnRail { note_id: String, folder: Option }, } /// What the selection bar does to every ticked note at once. @@ -382,24 +372,16 @@ pub fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Action &i18n::translate(state.language, i18n::keys::areas::NOTES, &[]), ); let rail = (state.settings.rail_shown, state.settings.rail_width); - let rest = view - .rail_width - .beside(ui, region, rail, "library-rail-edge", |ui| { - sidebar::show(ui, state, &mut view.sidebar, actions); - }); + let rest = view.rail_width.beside(ui, region, rail, "library-rail-edge", |ui| { + sidebar::show(ui, state, &mut view.sidebar, actions); + }); // Above the cards and the note, beside each other or the note alone: it never moves. let below = header_above(ui, rest, state, view, actions); let (cards, editor) = beside_the_cards(below, state, view.panel_width); if let Some(cards) = cards { show_cards(ui, cards, state, view, actions); } - overlays::editor::show( - ui, - editor, - state, - (&mut view.editor, &mut view.explorer_layout), - actions, - ); + overlays::editor::show(ui, editor, state, (&mut view.editor, &mut view.explorer_layout), actions); if let (Some(_), Some(editor)) = (cards, editor) { panel_edge(ui, editor, view, actions); } @@ -424,11 +406,7 @@ const CARDS_MIN: f32 = 2.0 * 220.0 + 12.0 + 2.0 * 24.0; /// Where the cards and the note open go: side by side, or the note over the whole area once /// expanded or when the window is too narrow for both. -fn beside_the_cards( - rest: Rect, - state: &AppState, - moving: Option, -) -> (Option, Option) { +fn beside_the_cards(rest: Rect, state: &AppState, moving: Option) -> (Option, Option) { // Open, read or still being read: the panel keeps its place while the next note is read. let editing = state.editor.is_open(); if !editing { @@ -465,48 +443,24 @@ fn panel_edge(ui: &mut Ui, editor: Rect, view: &mut View, actions: &mut Actions) let resting = !ui.input(|input| input.pointer.any_down()); if let Some(width) = view.panel_width.filter(|_| resting) { view.panel_width = None; - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a width on screen" - )] - actions.push(Asked::App(AppAction::SetEditorPanelWidth( - width.round() as u16 - ))); + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a width on screen")] + actions.push(Asked::App(AppAction::SetEditorPanelWidth(width.round() as u16))); } } fn show_cards(ui: &mut Ui, room: Rect, state: &AppState, view: &mut View, actions: &mut Actions) { let mut canvas_ui = ui.new_child(UiBuilder::new().max_rect(room)); // A card dragged on the board can be let go of over a row of the rail, which lights. - view.canvas.rail = if state.settings.rail_shown { - view.sidebar.rows().to_vec() - } else { - Vec::new() - }; + view.canvas.rail = if state.settings.rail_shown { view.sidebar.rows().to_vec() } else { Vec::new() }; canvas::show(&mut canvas_ui, state, &mut view.canvas, actions); view.sidebar.card_over = view.canvas.over_rail.take(); } /// The header at the top of `room`: what is left under it. -fn header_above( - ui: &mut Ui, - room: Rect, - state: &AppState, - view: &mut View, - actions: &mut Actions, -) -> Rect { +fn header_above(ui: &mut Ui, room: Rect, state: &AppState, view: &mut View, actions: &mut Actions) -> Rect { let mut header_ui = ui.new_child(UiBuilder::new().max_rect(room)); - header::show( - &mut header_ui, - state, - (&mut view.header, &mut view.focus_search), - actions, - ); - Rect::from_min_max( - egui::pos2(room.left(), header_ui.min_rect().bottom()), - room.max, - ) + header::show(&mut header_ui, state, (&mut view.header, &mut view.focus_search), actions); + Rect::from_min_max(egui::pos2(room.left(), header_ui.min_rect().bottom()), room.max) } /// « Snippets », the heading of a kind's section. diff --git a/crates/ui/src/notes/overlays/editor/attachments.rs b/crates/ui/src/notes/overlays/editor/attachments.rs index 0f0b06b1b..df0933aec 100644 --- a/crates/ui/src/notes/overlays/editor/attachments.rs +++ b/crates/ui/src/notes/overlays/editor/attachments.rs @@ -45,19 +45,12 @@ pub(super) fn show( item(ui, state, attachment, confirming, actions); } if attachments.list().is_empty() { - let hint = i18n::translate( - language, - keys::attachments::DROP_HINT, - &[("limit", MAX_MEGABYTES.into())], - ); + let hint = + i18n::translate(language, keys::attachments::DROP_HINT, &[("limit", MAX_MEGABYTES.into())]); let response = ui.label(RichText::new(hint).size(font::META).color(p.text_2)); widgets::address(ui, &response, "attachment-empty"); } - let key = if attachments.is_busy() { - keys::attachments::ADDING - } else { - keys::attachments::ADD - }; + let key = if attachments.is_busy() { keys::attachments::ADDING } else { keys::attachments::ADD }; let words = i18n::translate(language, key, &[]); let add = Button::new(&words, "attachment-add").enabled(!attachments.is_busy()); if add.kind(Kind::Outline).show(ui).clicked() { @@ -107,10 +100,7 @@ fn item( } } let words = tr(keys::attachments::SAVE); - if IconButton::new(Icon::ArrowDown, &words, "attachment-save") - .show(ui) - .clicked() - { + if IconButton::new(Icon::ArrowDown, &words, "attachment-save").show(ui).clicked() { ask(actions, Asked::Save(id.clone())); } let armed = confirming.as_deref() == Some(id.as_str()); @@ -163,8 +153,7 @@ fn name_button(ui: &mut Ui, state: &AppState, attachment: &Attachment) -> egui:: keys::attachments::OPEN, &[("name", attachment.file_name.as_str().into())], ); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); widgets::address(ui, &response, "attachment-open"); response }) @@ -186,8 +175,7 @@ fn preview(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let (rect, response) = ui.allocate_exact_size(size, Sense::click()); paint(ui, rect, texture.id()); let label = zoom_label(language, &attachment.file_name); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(label)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); widgets::address(ui, &response, "attachment-zoom"); if response.on_hover_cursor(egui::CursorIcon::ZoomIn).clicked() { ask(actions, Asked::Zoom(true)); @@ -208,9 +196,7 @@ fn zoom_label(language: Language, name: &str) -> String { } pub(in crate::notes::overlays) fn paint(ui: &Ui, rect: Rect, texture: egui::TextureId) { - egui::Image::new((texture, rect.size())) - .corner_radius(6) - .paint_at(ui, rect); + egui::Image::new((texture, rect.size())).corner_radius(6).paint_at(ui, rect); } /// As big as it is, or as fits: never enlarged. diff --git a/crates/ui/src/notes/overlays/editor/attachments/tests.rs b/crates/ui/src/notes/overlays/editor/attachments/tests.rs index 4caf86206..65b89c838 100644 --- a/crates/ui/src/notes/overlays/editor/attachments/tests.rs +++ b/crates/ui/src/notes/overlays/editor/attachments/tests.rs @@ -11,11 +11,10 @@ use crate::testing; type Harness = egui_kittest::Harness<'static, Bench>; const PNG: [u8; 67] = [ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, - 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0xe4, 0xfb, 0xcf, 0x50, - 0x0f, 0x00, 0x03, 0x86, 0x01, 0x80, 0x5a, 0x34, 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, - 0x4e, 0x44, 0xae, + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, + 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0xe4, 0xfb, 0xcf, 0x50, 0x0f, 0x00, 0x03, + 0x86, 0x01, 0x80, 0x5a, 0x34, 0x7d, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, ]; #[derive(Default)] @@ -78,9 +77,7 @@ fn paste_image(harness: &mut Harness) { } fn has(harness: &Harness, id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(id)).is_some() } fn text_file(folder: &Path) -> PathBuf { @@ -261,9 +258,7 @@ fn a_draft_is_written_for_the_file_dropped_on_it() { let space = testing::note(&backend, "seed").space_id.clone(); let mut harness = expanded_area(backend, profile); let state = &mut harness.state_mut().state; - state - .editor - .draft(engine::notes::kind::NoteKind::Snippet, space, None); + state.editor.draft(engine::notes::kind::NoteKind::Snippet, space, None); settle(&mut harness); let folder = tempfile::tempdir().unwrap(); @@ -278,9 +273,7 @@ fn a_draft_is_written_for_the_file_dropped_on_it() { fn another_note_shows_its_own_files() { let (mut harness, id, folder) = opened(); drop_file(&mut harness, &image_file(folder.path())); - let other = testing::note(&harness.state().backend, "another") - .id - .clone(); + let other = testing::note(&harness.state().backend, "another").id.clone(); harness.state_mut().state.editor.open(other); settle(&mut harness); diff --git a/crates/ui/src/notes/overlays/editor/body.rs b/crates/ui/src/notes/overlays/editor/body.rs index 24cc3cdeb..cddf9e96a 100644 --- a/crates/ui/src/notes/overlays/editor/body.rs +++ b/crates/ui/src/notes/overlays/editor/body.rs @@ -35,14 +35,8 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, note: &DisplayNote, body: &mut let p = palette(ui.ctx()); let language = state.language; let (font, hint) = match note.kind { - NoteKind::Note => ( - FontId::new(font::SUBTITLE, FontFamily::Proportional), - keys::editor::EMPTY_RICH, - ), - _ => ( - FontId::new(font::READING, FontFamily::Monospace), - keys::editor::EMPTY_BODY, - ), + NoteKind::Note => (FontId::new(font::SUBTITLE, FontFamily::Proportional), keys::editor::EMPTY_RICH), + _ => (FontId::new(font::READING, FontFamily::Monospace), keys::editor::EMPTY_BODY), }; let label = i18n::translate(language, keys::editor::CONTENT_LABEL, &[]); let size = ui.available_size(); @@ -82,10 +76,7 @@ pub(super) fn stats( i18n::translate( language, keys::editor::CHECKLIST_STATS, - &[ - ("done", count(done).into()), - ("total", count(items.len()).into()), - ], + &[("done", count(done).into()), ("total", count(items.len()).into())], ) } NoteKind::Note => i18n::translate( @@ -93,11 +84,9 @@ pub(super) fn stats( keys::editor::NOTE_STATS, &[("count", count(text::count_words(typed)).into())], ), - NoteKind::Drawing => i18n::translate( - language, - keys::editor::DRAWING_STATS, - &[("count", count(shapes).into())], - ), + NoteKind::Drawing => { + i18n::translate(language, keys::editor::DRAWING_STATS, &[("count", count(shapes).into())]) + } NoteKind::Snippet | NoteKind::Calc => { let head = if note.kind == NoteKind::Calc { i18n::translate(language, keys::notes::kind_tag::CALC, &[]) diff --git a/crates/ui/src/notes/overlays/editor/calc.rs b/crates/ui/src/notes/overlays/editor/calc.rs index bdfb2b175..713de0b22 100644 --- a/crates/ui/src/notes/overlays/editor/calc.rs +++ b/crates/ui/src/notes/overlays/editor/calc.rs @@ -63,9 +63,7 @@ impl CalcView { } let first = self.editor.buffer.line_of(selection.start); let last = self.editor.buffer.line_of(selection.end); - (first..=last) - .filter_map(|line| u32::try_from(line).ok()) - .collect() + (first..=last).filter_map(|line| u32::try_from(line).ok()).collect() } /// A click picks one, Shift a range from the last one picked, Ctrl one more or one less. @@ -143,19 +141,12 @@ pub(super) fn show( if let Some(due) = view.evaluate_at { if now >= due { view.evaluate_at = None; - actions.push(super::editor(Editing::Evaluate { - session, - text: view.text(), - })); + actions.push(super::editor(Editing::Evaluate { session, text: view.text() })); } else { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(due - now)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(due - now)); } } - Shown { - changed: shown.changed, - left: shown.left, - } + Shown { changed: shown.changed, left: shown.left } } struct Field { @@ -164,12 +155,7 @@ struct Field { left: bool, } -fn sheet_field( - ui: &mut Ui, - view: &mut CalcView, - sheet: Option<&CalcSheet>, - language: Language, -) -> Field { +fn sheet_field(ui: &mut Ui, view: &mut CalcView, sheet: Option<&CalcSheet>, language: Language) -> Field { let p = palette(ui.ctx()); let colours = |line: usize, text: &str| colours_of(p, sheet, line, text); let label = i18n::translate(language, keys::calc::editor::LABEL, &[]); @@ -178,10 +164,7 @@ fn sheet_field( let hover = |at: usize| hovered(&text, sheet, at, language); let caret = view.editor.buffer.selection().head; let (from, items) = completions(&text, caret, sheet, language); - let completion = (!items.is_empty()).then_some(Completion { - from, - items: &items, - }); + let completion = (!items.is_empty()).then_some(Completion { from, items: &items }); let output = EditorView::new(&mut view.editor, &label, "editor-body") .hint(&hint) .language(language) @@ -190,11 +173,7 @@ fn sheet_field( .hover(&hover) .completion(completion) .show(ui); - Field { - rows: output.rows, - changed: output.changed.is_some(), - left: output.response.lost_focus(), - } + Field { rows: output.rows, changed: output.changed.is_some(), left: output.response.lost_focus() } } /// The core's spans, in UTF-16 units of the line, as `char` ranges in their colours. @@ -257,30 +236,19 @@ fn completions( .iter() .rposition(|character| *character == '\n') .map_or(0, |at| at + 1); - let before: String = text - .chars() - .skip(start_of_line) - .take(caret - start_of_line) - .collect(); + let before: String = text.chars().skip(start_of_line).take(caret - start_of_line).collect(); if before.trim_start().starts_with('#') || before.contains("//") { return (caret, Vec::new()); } let line = text.chars().take(caret).filter(|it| *it == '\n').count(); - let dimension = sheet - .and_then(|sheet| sheet.rows.get(line)) - .and_then(|row| row.converting); + let dimension = sheet.and_then(|sheet| sheet.rows.get(line)).and_then(|row| row.converting); if let Some(typed) = calc::conversion_start(&before) { let from = caret - typed.chars().count(); - let units = dimension.map_or_else(Vec::new, |dimension| { - calc::units_for(dimension, typed, language) - }); + let units = dimension.map_or_else(Vec::new, |dimension| calc::units_for(dimension, typed, language)); return (from, units); } let typed = calc::typed_word(&before); - ( - caret - typed.chars().count(), - calc::complete(typed, language), - ) + (caret - typed.chars().count(), calc::complete(typed, language)) } /// A name hovered says its exact value, where it was given and where it is read. @@ -311,11 +279,8 @@ fn hovered(text: &str, sheet: Option<&CalcSheet>, at: usize, language: Language) .iter() .rfind(|variable| variable.name == name && variable.line <= index)?; let value = calc::exact(&variable.value, language); - let defined = i18n::translate( - language, - keys::calc::editor::DEFINED, - &[("line", (variable.line + 1).into())], - ); + let defined = + i18n::translate(language, keys::calc::editor::DEFINED, &[("line", (variable.line + 1).into())]); let used = used_on(&variable.uses, language); Some(format!("{name} = {value}\n{defined} · {used}")) } @@ -323,18 +288,10 @@ fn hovered(text: &str, sheet: Option<&CalcSheet>, at: usize, language: Language) fn used_on(uses: &[u32], language: Language) -> String { match uses { [] => i18n::translate(language, keys::calc::editor::UNUSED, &[]), - [line] => i18n::translate( - language, - keys::calc::editor::USED_ONCE, - &[("line", (line + 1).into())], - ), + [line] => i18n::translate(language, keys::calc::editor::USED_ONCE, &[("line", (line + 1).into())]), lines => { let lines: Vec = lines.iter().map(|line| (line + 1).to_string()).collect(); - i18n::translate( - language, - keys::calc::editor::USED_MANY, - &[("lines", lines.join(", ").into())], - ) + i18n::translate(language, keys::calc::editor::USED_MANY, &[("lines", lines.join(", ").into())]) } } } @@ -347,19 +304,8 @@ fn results(ui: &mut Ui, view: &mut CalcView, sheet: &CalcSheet, rows: &[Row], fo continue; }; match row_of(sheet, line) { - Some(CalcLine::Value { - value, - name, - aggregate, - places, - .. - }) => { - let shown = Result { - value, - places: *places, - named: name.is_some(), - aggregate: *aggregate, - }; + Some(CalcLine::Value { value, name, aggregate, places, .. }) => { + let shown = Result { value, places: *places, named: name.is_some(), aggregate: *aggregate }; value_cell(ui, view, sheet, (row, line), &shown, format); } Some(CalcLine::Error { error }) => failure_cell(ui, row, error, language), @@ -392,11 +338,7 @@ fn value_cell( let approx = if written.approx { "≈ " } else { "" }; let words = format!("{approx}{}", written.text); let selected = view.picked.contains(&line); - let ink = if shown.named && !selected { - p.text_1 - } else { - p.text_0 - }; + let ink = if shown.named && !selected { p.text_1 } else { p.text_0 }; let galley = widgets::text(ui, &words, FONT, 400.0, FontFamily::Monospace, ink); let width = galley.size().x.min(RESULTS_WIDTH - COPY_SIZE - 8.0); let cell = Rect::from_min_max( @@ -404,14 +346,11 @@ fn value_cell( egui::pos2(right, row.rect.bottom()), ); if selected { - ui.painter() - .rect_filled(cell, 5.0, p.pink.gamma_multiply(0.16)); + ui.painter().rect_filled(cell, 5.0, p.pink.gamma_multiply(0.16)); } - ui.painter() - .galley(egui::pos2(cell.left() + 4.0, cell.top()), galley, ink); + ui.painter().galley(egui::pos2(cell.left() + 4.0, cell.top()), galley, ink); if shown.aggregate { - ui.painter() - .hline(cell.x_range(), cell.top(), Stroke::new(1.0, p.text_1)); + ui.painter().hline(cell.x_range(), cell.top(), Stroke::new(1.0, p.text_1)); } let response = ui.allocate_rect(cell, Sense::click()); crate::widgets::pointer(ui, &response); @@ -437,20 +376,10 @@ fn value_cell( fn failure_cell(ui: &mut Ui, row: &Row, error: &CalcError, language: Language) { let p = palette(ui.ctx()); let words = calc::error(error, language); - let galley = widgets::text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.red, - ); + let galley = widgets::text(ui, &words, font::LABEL, 400.0, FontFamily::Proportional, p.red); let size = galley.size(); let right = row.rect.right() - 8.0; - let rect = Rect::from_min_size( - egui::pos2(right - size.x.min(RESULTS_WIDTH), row.rect.top()), - size, - ); + let rect = Rect::from_min_size(egui::pos2(right - size.x.min(RESULTS_WIDTH), row.rect.top()), size); ui.painter().galley(rect.min, galley, p.red); let response = ui.allocate_rect(rect, Sense::hover()); ui.ctx() @@ -459,34 +388,18 @@ fn failure_cell(ui: &mut Ui, row: &Row, error: &CalcError, language: Language) { } /// Every decimal kept, with its thousands never grouped: a sheet reads it back. -fn copy_button( - ui: &mut Ui, - view: &mut CalcView, - value: &CalcValue, - beside: Rect, - language: Language, -) { +fn copy_button(ui: &mut Ui, view: &mut CalcView, value: &CalcValue, beside: Rect, language: Language) { let exact = calc::exact(value, language); - let words = i18n::translate( - language, - keys::calc::editor::COPY_RESULT, - &[("value", exact.as_str().into())], - ); + let words = + i18n::translate(language, keys::calc::editor::COPY_RESULT, &[("value", exact.as_str().into())]); let at = Rect::from_min_size( egui::pos2(beside.left() - COPY_SIZE - 2.0, beside.top()), Vec2::splat(COPY_SIZE), ); let mut cell = ui.new_child(egui::UiBuilder::new().max_rect(at)); - if IconButton::new(Icon::Copy, &words, "calc-copy") - .show(&mut cell) - .clicked() - { + if IconButton::new(Icon::Copy, &words, "calc-copy").show(&mut cell).clicked() { ui.ctx().copy_text(exact.clone()); - let said = i18n::translate( - language, - keys::calc::editor::COPIED, - &[("value", exact.into())], - ); + let said = i18n::translate(language, keys::calc::editor::COPIED, &[("value", exact.into())]); view.said = Some((said, ui.input(|input| input.time) + SAID_FOR)); } } @@ -505,16 +418,8 @@ fn footer( let names = sheet.map_or(0, distinct_names); let counts = format!( "{} · {}", - i18n::translate( - language, - keys::calc::editor::LINES, - &[("count", lines.into())] - ), - i18n::translate( - language, - keys::calc::editor::VARIABLES, - &[("count", names.into())] - ), + i18n::translate(language, keys::calc::editor::LINES, &[("count", lines.into())]), + i18n::translate(language, keys::calc::editor::VARIABLES, &[("count", names.into())]), ); let summary = summary(ui, view, sheet, format); ui.horizontal_centered(|ui| { @@ -553,44 +458,25 @@ fn decimals(ui: &mut Ui, state: &AppState, actions: &mut Actions) { .show(ui, &mut chosen) .changed() { - actions.push(crate::notes::overlays::editor::editor(Editing::Decimals( - chosen, - ))); + actions.push(crate::notes::overlays::editor::editor(Editing::Decimals(chosen))); } let family = FontFamily::Proportional; - ui.label(widgets::text( - ui, - &label, - font::CONTROL, - 400.0, - family, - p.text_2, - )); + ui.label(widgets::text(ui, &label, font::CONTROL, 400.0, family, p.text_2)); } fn distinct_names(sheet: &CalcSheet) -> u32 { - let names: BTreeSet<&str> = sheet - .variables - .iter() - .map(|variable| variable.name.as_str()) - .collect(); + let names: BTreeSet<&str> = sheet.variables.iter().map(|variable| variable.name.as_str()).collect(); u32::try_from(names.len()).unwrap_or(u32::MAX) } /// What the footer says on its right: what was copied, or what the lines chosen add up to. -fn summary( - ui: &Ui, - view: &mut CalcView, - sheet: Option<&CalcSheet>, - format: Format, -) -> Option { +fn summary(ui: &Ui, view: &mut CalcView, sheet: Option<&CalcSheet>, format: Format) -> Option { let language = format.language; let now = ui.input(|input| input.time); match &view.said { Some((_, until)) if *until <= now => view.said = None, Some((said, until)) => { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(until - now)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(until - now)); return Some(said.clone()); } None => {} @@ -600,11 +486,7 @@ fn summary( return None; } let count = u32::try_from(chosen.len()).unwrap_or(u32::MAX); - let selected = i18n::translate( - language, - keys::calc::editor::SELECTED, - &[("count", count.into())], - ); + let selected = i18n::translate(language, keys::calc::editor::SELECTED, &[("count", count.into())]); let tr = |key| i18n::translate(language, key, &[]); let said = match api::notes::calc_summary(sheet?, &chosen) { CalcSummary::NothingToAdd => tr(keys::calc::editor::NOTHING_TO_ADD), diff --git a/crates/ui/src/notes/overlays/editor/calc/tests.rs b/crates/ui/src/notes/overlays/editor/calc/tests.rs index 0fcb7ea82..5c6d16c23 100644 --- a/crates/ui/src/notes/overlays/editor/calc/tests.rs +++ b/crates/ui/src/notes/overlays/editor/calc/tests.rs @@ -10,23 +10,17 @@ use crate::testing; type Harness = egui_kittest::Harness<'static, Bench>; /// No result here is rounded: `≈` is in no embedded font, and the harness refuses a system's. -const SHEET: &str = - "# Budget\nhébergement = 100,52 €\ndomaines = 4,99 €\nmensuel = total\ndistance + 3 Go"; +const SHEET: &str = "# Budget\nhébergement = 100,52 €\ndomaines = 4,99 €\nmensuel = total\ndistance + 3 Go"; /// A sheet holding `text`, open in the editor and computed. fn opened(text: &str) -> (Harness, String) { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "budget").id.clone(); - let patch = NotePatch { - kind: Some(NoteKind::Calc), - content: Some(text.to_owned()), - ..NotePatch::default() - }; + let patch = + NotePatch { kind: Some(NoteKind::Calc), content: Some(text.to_owned()), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = area(backend, profile); harness.state_mut().state.editor.open(id.clone()); settle(&mut harness); @@ -42,10 +36,7 @@ fn values(harness: &Harness, id: &str) -> Vec { } fn value(harness: &Harness, id: &str) -> String { - harness - .get_by(|node| node.author_id() == Some(id)) - .value() - .unwrap_or_default() + harness.get_by(|node| node.author_id() == Some(id)).value().unwrap_or_default() } fn click_result(harness: &mut Harness, at: usize, modifiers: Modifiers) { @@ -59,12 +50,10 @@ fn click_result(harness: &mut Harness, at: usize, modifiers: Modifiers) { fn stored(harness: &Harness, id: &str) -> String { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() - .content - .clone() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + .content + .clone() } #[test] @@ -96,11 +85,7 @@ fn a_result_clicked_is_summed_and_clicked_again_is_let_go() { assert!(said.contains("sum"), "{said}"); click_result(&mut harness, 0, Modifiers::NONE); - assert!( - harness - .query_by(|node| node.author_id() == Some("calc-summary")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("calc-summary")).is_none()); } #[test] @@ -158,19 +143,15 @@ fn what_is_typed_is_computed_and_written_on_close() { fn a_result_is_copied_whole_and_the_footer_says_so() { let (mut harness, _) = opened("100,5 €"); - harness - .get_by(|node| node.author_id() == Some("calc-result")) - .hover(); + harness.get_by(|node| node.author_id() == Some("calc-result")).hover(); settle(&mut harness); - harness - .get_by(|node| node.author_id() == Some("calc-copy")) - .click(); + harness.get_by(|node| node.author_id() == Some("calc-copy")).click(); let mut copied = false; for _ in 0..4 { harness.step(); - copied |= harness.output().platform_output.commands.iter().any(|command| { - matches!(command, egui::OutputCommand::CopyText(text) if text.starts_with("100.5")) - }); + copied |= harness.output().platform_output.commands.iter().any( + |command| matches!(command, egui::OutputCommand::CopyText(text) if text.starts_with("100.5")), + ); } assert!(copied); settle(&mut harness); @@ -180,11 +161,7 @@ fn a_result_is_copied_whole_and_the_footer_says_so() { #[test] fn the_copy_icon_waits_for_the_pointer() { let (mut harness, _) = opened("1\n2"); - assert!( - harness - .query_by(|node| node.author_id() == Some("calc-copy")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("calc-copy")).is_none()); harness .get_all_by(|node| node.author_id() == Some("calc-result")) @@ -193,12 +170,7 @@ fn the_copy_icon_waits_for_the_pointer() { .hover(); settle(&mut harness); - assert_eq!( - harness - .get_all_by(|node| node.author_id() == Some("calc-copy")) - .count(), - 1 - ); + assert_eq!(harness.get_all_by(|node| node.author_id() == Some("calc-copy")).count(), 1); } /// The note's own copy, not a result's: its results follow as comments. @@ -206,9 +178,7 @@ fn the_copy_icon_waits_for_the_pointer() { fn copying_the_sheet_writes_its_results_as_comments() { let (mut harness, _) = opened("2 + 2\nune phrase"); - harness - .get_by(|node| node.author_id() == Some("editor-copy")) - .click(); + harness.get_by(|node| node.author_id() == Some("editor-copy")).click(); let mut copied = None; for _ in 0..60 { harness.step(); @@ -240,3 +210,83 @@ fn where_a_name_is_read_is_said() { assert_eq!(used_on(&[2], Language::En), "used on line 3"); assert_eq!(used_on(&[2, 4], Language::En), "used on lines 3, 5"); } + +fn computed(text: &str) -> engine::notes::calc::CalcSheet { + let today = chrono::NaiveDate::from_ymd_opt(2026, 11, 4).unwrap(); + engine::notes::calc::evaluate(text, today) +} + +fn proposed(text: &str) -> (usize, Vec) { + let sheet = computed(text); + super::completions(text, text.chars().count(), Some(&sheet), i18n::Language::En) +} + +/// The units of the line's kind after a conversion word, the words of the table elsewhere. +#[test] +fn what_is_proposed_follows_what_is_before_the_caret() { + let (from, units) = proposed("a = 1\n3 km in m"); + assert_eq!(from, "a = 1\n3 km in ".len()); + assert!(units.contains(&"mi".to_owned()) && !units.contains(&"kg".to_owned()), "{units:?}"); + + let (from, words) = proposed("2\ntod"); + assert_eq!((from, words), (2, vec!["today".to_owned()])); + for text in ["# tod", "2 // tod", "2\n"] { + assert!(proposed(text).1.is_empty(), "{text}"); + } + let (_, units) = super::completions("3 km in m", 9, None, i18n::Language::En); + assert!(units.is_empty(), "not computed yet"); +} + +#[test] +fn a_name_hovered_says_its_value_where_it_was_given_and_where_it_is_read() { + let text = "é = 1\nprix = 1234.5 €\nprix × 2\nautre = 3"; + let sheet = computed(text); + let said = |at| super::hovered(text, Some(&sheet), at, i18n::Language::En); + let name = text.find("prix = ").unwrap() - 1; + + for at in [name, name + 4, text.chars().count() - "prix × 2\nautre = 3".chars().count() + 1] { + let words = said(at).unwrap_or_default().replace('\u{a0}', " "); + assert!( + words.starts_with("prix = 1234.5 €\n") && words.contains('2') && words.contains('3'), + "{at}: {words}" + ); + } + assert_eq!(said(name + 8), None, "a number"); + let unused = said(text.chars().count() - "autre = 3".len()).unwrap(); + assert!(unused.contains(&used_on(&[], i18n::Language::En)), "{unused}"); + assert_eq!(super::hovered(text, None, name, i18n::Language::En), None); +} + +/// Given twice, the one above. +#[test] +fn a_name_given_again_is_the_last_one_above() { + let text = "a = 1\na\na = 2\na"; + let sheet = computed(text); + let said = |line: usize| { + let at = text.split('\n').take(line).map(|it| it.len() + 1).sum(); + super::hovered(text, Some(&sheet), at, i18n::Language::En).unwrap() + }; + + assert!(said(1).starts_with("a = 1\n")); + assert!(said(3).starts_with("a = 2\n")); +} + +#[test] +fn each_kind_of_word_has_its_colour() { + use engine::notes::calc::TokenKind; + + let p = crate::theme::palette(&egui::Context::default()); + for (kind, colour) in [ + (TokenKind::Number, p.amber_text), + (TokenKind::Unit, p.teal), + (TokenKind::Operator, p.text_1), + (TokenKind::Keyword, p.purple), + (TokenKind::Name, p.blue), + (TokenKind::Date, p.green), + (TokenKind::Comment, p.text_2), + (TokenKind::Heading, p.text_0), + (TokenKind::Error, p.red), + ] { + assert_eq!(super::colour(p, kind), colour); + } +} diff --git a/crates/ui/src/notes/overlays/editor/checklist.rs b/crates/ui/src/notes/overlays/editor/checklist.rs index f4f9b1511..d6a6e7168 100644 --- a/crates/ui/src/notes/overlays/editor/checklist.rs +++ b/crates/ui/src/notes/overlays/editor/checklist.rs @@ -7,8 +7,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::text::{CCursor, CCursorRange}; use egui::text_edit::TextEditState; use egui::{ - Align, CornerRadius, Event, FontFamily, FontId, Id, Key, Layout, Modifiers, Rect, Role, Sense, - Stroke, TextEdit, Ui, Vec2, WidgetInfo, + Align, CornerRadius, Event, FontFamily, FontId, Id, Key, Layout, Modifiers, Rect, Role, Sense, Stroke, + TextEdit, Ui, Vec2, WidgetInfo, }; use engine::notes::checklist::ChecklistItem; use i18n::{Language, keys}; @@ -51,10 +51,7 @@ impl Shown { impl ChecklistView { pub(super) fn of(items: &[ChecklistItem]) -> Self { - Self { - items: items.to_vec(), - ..Self::default() - } + Self { items: items.to_vec(), ..Self::default() } } fn move_item(&mut self, from: usize, to: usize) -> bool { @@ -79,12 +76,7 @@ enum RowKey { /// The list; `true` once something is to be written. `filters`: the tasks shown can be narrowed /// to those left to do or those done, and a row is dragged only while all are shown. -pub(super) fn show( - ui: &mut Ui, - view: &mut ChecklistView, - language: Language, - filters: bool, -) -> bool { +pub(super) fn show(ui: &mut Ui, view: &mut ChecklistView, language: Language, filters: bool) -> bool { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); let mut changed = false; @@ -106,10 +98,8 @@ pub(super) fn show( for (rank, &index) in shown.iter().enumerate() { #[expect(clippy::cast_precision_loss, reason = "a list's length")] let top = rows_top + rank as f32 * (ROW + 2.0); - let rect = Rect::from_min_size( - egui::pos2(ui.max_rect().left(), top), - Vec2::new(ui.available_width(), ROW), - ); + let rect = + Rect::from_min_size(egui::pos2(ui.max_rect().left(), top), Vec2::new(ui.available_width(), ROW)); let mut row_ui = ui.new_child( egui::UiBuilder::new() .id_salt(("checklist-row-ui", index)) @@ -165,10 +155,7 @@ pub(super) fn show( if view.shown == Shown::Done { view.shown = Shown::All; } - view.items.push(ChecklistItem { - text: String::new(), - done: false, - }); + view.items.push(ChecklistItem { text: String::new(), done: false }); view.focus = Some((view.items.len() - 1, 0)); changed = true; } @@ -199,11 +186,7 @@ fn drag( let (from, _) = view.dragging.filter(|(from, _)| *from == index)?; if let Some(pointer) = ui.ctx().pointer_latest_pos() { let slot = ((pointer.y - rows_top) / (ROW + 2.0)).floor().max(0.0); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a row" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a row")] let to = (slot as usize).min(view.items.len() - 1); view.dragging = Some((from, to)); } @@ -255,10 +238,7 @@ fn row( let label = i18n::translate( language, keys::editor::ITEM_LABEL, - &[( - "position", - u32::try_from(index + 1).unwrap_or(u32::MAX).into(), - )], + &[("position", u32::try_from(index + 1).unwrap_or(u32::MAX).into())], ); let hint = i18n::translate(language, keys::editor::ITEM_PLACEHOLDER, &[]); let field = ui.add_sized( @@ -271,8 +251,7 @@ fn row( .text_color(if done { p.text_2 } else { p.text_0 }) .font(FontId::new(font::READING, FontFamily::Proportional)), ); - ui.ctx() - .accesskit_node_builder(field.id, |node| node.set_label(label.clone())); + ui.ctx().accesskit_node_builder(field.id, |node| node.set_label(label.clone())); address(ui, &field, "checklist-text"); if done { strike(ui, &field, &view.items[index].text); @@ -286,10 +265,7 @@ fn row( outcome = Some(Outcome::Left); } let remove = named(keys::editor::REMOVE_ITEM); - if IconButton::new(Icon::X, &remove, "checklist-remove") - .show(ui) - .clicked() - { + if IconButton::new(Icon::X, &remove, "checklist-remove").show(ui).clicked() { outcome = Some(Outcome::Removed); } (outcome, grip) @@ -306,11 +282,8 @@ fn tick(ui: &mut Ui, done: bool, label: &str) -> egui::Response { || WidgetInfo::selected(Role::CheckBox, true, done, label), CornerRadius::same(radius::TAG), ); - let (fill, edge) = if done { - (p.amber_fill, p.amber_text) - } else { - (egui::Color32::TRANSPARENT, p.text_2) - }; + let (fill, edge) = + if done { (p.amber_fill, p.amber_text) } else { (egui::Color32::TRANSPARENT, p.text_2) }; let tick = egui::Rect::from_center_size(check.rect.center(), Vec2::splat(14.0)); ui.painter().rect( tick, @@ -334,11 +307,8 @@ fn strike(ui: &Ui, field: &egui::Response, text: &str) { .size() .x; let y = field.rect.center().y; - ui.painter().hline( - field.rect.left()..=field.rect.left() + width, - y, - Stroke::new(1.0, p.text_2), - ); + ui.painter() + .hline(field.rect.left()..=field.rect.left() + width, y, Stroke::new(1.0, p.text_2)); } /// Enter, Backspace at the start, a paste of several lines and Alt+↑/↓, taken from the field's @@ -350,10 +320,8 @@ fn row_keys(ui: &Ui, id: Id, text: &str) -> Option { let caret = TextEditState::load(ui.ctx(), id) .and_then(|state| state.cursor.char_range()) .unwrap_or_else(|| CCursorRange::one(CCursor::new(text.chars().count()))); - let (start, end) = ( - caret.primary.index.min(caret.secondary.index), - caret.primary.index.max(caret.secondary.index), - ); + let (start, end) = + (caret.primary.index.min(caret.secondary.index), caret.primary.index.max(caret.secondary.index)); if let Some(by) = alt_arrows(ui) { return Some(RowKey::Move(by)); } @@ -363,11 +331,7 @@ fn row_keys(ui: &Ui, id: Id, text: &str) -> Option { } if start.0 == 0 && end.0 == 0 && input.key_pressed(Key::Backspace) { input.consume_key(Modifiers::NONE, Key::Backspace); - return Some(if text.is_empty() { - RowKey::Remove - } else { - RowKey::Join - }); + return Some(if text.is_empty() { RowKey::Remove } else { RowKey::Join }); } let pasted = input .events @@ -419,9 +383,7 @@ fn row_id(index: usize) -> Id { fn place_caret(ui: &Ui, id: Id, at: usize) { let mut state = TextEditState::load(ui.ctx(), id).unwrap_or_default(); - state - .cursor - .set_char_range(Some(CCursorRange::one(CCursor::new(at)))); + state.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(at)))); state.store(ui.ctx(), id); } @@ -446,18 +408,10 @@ fn apply(view: &mut ChecklistView, index: usize, outcome: Outcome) -> bool { } Outcome::Key(RowKey::Split(at)) => { let text = view.items[index].text.clone(); - let cut = text - .char_indices() - .nth(at) - .map_or(text.len(), |(byte, _)| byte); + let cut = text.char_indices().nth(at).map_or(text.len(), |(byte, _)| byte); text[..cut].clone_into(&mut view.items[index].text); - view.items.insert( - index + 1, - ChecklistItem { - text: text[cut..].to_owned(), - done: false, - }, - ); + view.items + .insert(index + 1, ChecklistItem { text: text[cut..].to_owned(), done: false }); view.focus = Some((index + 1, 0)); true } @@ -514,40 +468,27 @@ fn pasted_item(line: &str) -> ChecklistItem { .and_then(|rest| rest.strip_prefix(['.', ')'])) }) .map_or(trimmed, str::trim_start); - let boxed = unmarked - .strip_prefix("[ ]") - .map(|rest| (rest, false)) - .or_else(|| { - unmarked - .strip_prefix("[x]") - .or_else(|| unmarked.strip_prefix("[X]")) - .map(|rest| (rest, true)) - }); + let boxed = unmarked.strip_prefix("[ ]").map(|rest| (rest, false)).or_else(|| { + unmarked + .strip_prefix("[x]") + .or_else(|| unmarked.strip_prefix("[X]")) + .map(|rest| (rest, true)) + }); match boxed { - Some((rest, done)) if rest.starts_with(char::is_whitespace) => ChecklistItem { - text: rest.trim().to_owned(), - done, - }, + Some((rest, done)) if rest.starts_with(char::is_whitespace) => { + ChecklistItem { text: rest.trim().to_owned(), done } + } _ => ChecklistItem { - text: if unmarked.len() < trimmed.len() { - unmarked - } else { - trimmed - } - .trim_end() - .to_owned(), + text: if unmarked.len() < trimmed.len() { unmarked } else { trimmed } + .trim_end() + .to_owned(), done: false, }, } } /// The bar and « 2/5 tâches », then — `narrowing` — the choice of the tasks shown. -fn progress( - ui: &mut Ui, - items: &[ChecklistItem], - language: Language, - narrowing: Option<&mut Shown>, -) { +fn progress(ui: &mut Ui, items: &[ChecklistItem], language: Language, narrowing: Option<&mut Shown>) { let p = palette(ui.ctx()); let done = items.iter().filter(|item| item.done).count(); let total = items.len(); @@ -563,36 +504,19 @@ fn progress( (Shown::Open, tr(keys::editor::tasks_shown::OPEN)), (Shown::Done, tr(keys::editor::tasks_shown::DONE)), ]; - let options: Vec<(Shown, &str)> = names - .iter() - .map(|(shown, name)| (*shown, name.as_str())) - .collect(); + let options: Vec<(Shown, &str)> = names.iter().map(|(shown, name)| (*shown, name.as_str())).collect(); let choice = Segmented::new(&options, "checklist-shown"); ui.horizontal(|ui| { - let galley = widgets::text( - ui, - &words, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); - let choice_width = if narrowing.is_some() { - choice.width(ui) + 10.0 - } else { - 0.0 - }; + let galley = widgets::text(ui, &words, font::META, 400.0, FontFamily::Monospace, p.text_2); + let choice_width = if narrowing.is_some() { choice.width(ui) + 10.0 } else { 0.0 }; let width = ui.available_width() - galley.size().x - 10.0 - choice_width; let (track, _) = ui.allocate_exact_size(Vec2::new(width.max(40.0), 6.0), Sense::hover()); - ui.painter() - .rect_filled(track, CornerRadius::same(radius::TAG), p.bg_3); + ui.painter().rect_filled(track, CornerRadius::same(radius::TAG), p.bg_3); if total > 0 { #[expect(clippy::cast_precision_loss, reason = "a list's length")] let share = done as f32 / total as f32; - let fill = - Rect::from_min_size(track.min, Vec2::new(track.width() * share, track.height())); - ui.painter() - .rect_filled(fill, CornerRadius::same(radius::TAG), p.amber_fill); + let fill = Rect::from_min_size(track.min, Vec2::new(track.width() * share, track.height())); + ui.painter().rect_filled(fill, CornerRadius::same(radius::TAG), p.amber_fill); } let response = ui.label(galley); address(ui, &response, "checklist-progress"); diff --git a/crates/ui/src/notes/overlays/editor/checklist/tests.rs b/crates/ui/src/notes/overlays/editor/checklist/tests.rs index b6e8856fb..ecf487d60 100644 --- a/crates/ui/src/notes/overlays/editor/checklist/tests.rs +++ b/crates/ui/src/notes/overlays/editor/checklist/tests.rs @@ -11,10 +11,7 @@ use crate::testing; type Harness = egui_kittest::Harness<'static, Bench>; fn item(text: &str, done: bool) -> ChecklistItem { - ChecklistItem { - text: text.into(), - done, - } + ChecklistItem { text: text.into(), done } } /// A list holding `items`, open in the editor. @@ -28,10 +25,8 @@ fn list(items: &[ChecklistItem]) -> (Harness, String) { ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = area(backend, profile); // A list's card is mostly its ticks: it opens as Enter on the card opens it. harness.state_mut().state.editor.open(id.clone()); @@ -41,15 +36,13 @@ fn list(items: &[ChecklistItem]) -> (Harness, String) { fn stored(harness: &Harness, id: &str) -> Vec<(String, bool)> { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() - .items - .clone() - .into_iter() - .map(|item| (item.text, item.done)) - .collect() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + .items + .clone() + .into_iter() + .map(|item| (item.text, item.done)) + .collect() } fn rows(harness: &Harness) -> Vec { @@ -74,10 +67,7 @@ fn press(harness: &mut Harness, modifiers: Modifiers, key: Key) { } fn owned(pairs: &[(&str, bool)]) -> Vec<(String, bool)> { - pairs - .iter() - .map(|(text, done)| ((*text).to_owned(), *done)) - .collect() + pairs.iter().map(|(text, done)| ((*text).to_owned(), *done)).collect() } #[test] @@ -92,10 +82,7 @@ fn a_task_added_and_typed_is_written_on_close_and_a_tick_at_once() { .type_text("bread"); settle(&mut harness); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - owned(&[("milk", false), ("bread", false)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("milk", false), ("bread", false)])); harness.state_mut().state.editor.open(id.clone()); settle(&mut harness); @@ -105,10 +92,7 @@ fn a_task_added_and_typed_is_written_on_close_and_a_tick_at_once() { .unwrap() .click(); settle(&mut harness); - assert_eq!( - stored(&harness, &id), - owned(&[("milk", false), ("bread", true)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("milk", false), ("bread", true)])); let progress = harness .get_by(|node| node.author_id() == Some("checklist-progress")) .accesskit_node() @@ -128,10 +112,7 @@ fn enter_splits_a_task_at_the_caret_and_backspace_joins_it_back() { press(&mut harness, Modifiers::NONE, Key::Enter); assert_eq!(rows(&harness), ["milk", "bread"]); - assert_eq!( - stored(&harness, &id), - owned(&[("milk", false), ("bread", false)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("milk", false), ("bread", false)])); press(&mut harness, Modifiers::NONE, Key::Backspace); assert_eq!(rows(&harness), ["milkbread"]); @@ -159,19 +140,12 @@ fn backspace_in_an_empty_task_removes_it_and_the_cross_does_too() { fn lines_pasted_are_tasks_their_boxes_read() { let (mut harness, id) = list(&[item("x", false)]); click_id(&mut harness, "checklist-add"); - harness.event(Event::Paste( - "- [x] ship it\n\n- [ ] tag it\n3. announce".into(), - )); + harness.event(Event::Paste("- [x] ship it\n\n- [ ] tag it\n3. announce".into())); settle(&mut harness); assert_eq!( stored(&harness, &id), - owned(&[ - ("x", false), - ("ship it", true), - ("tag it", false), - ("announce", false) - ]) + owned(&[("x", false), ("ship it", true), ("tag it", false), ("announce", false)]) ); } @@ -180,10 +154,7 @@ fn alt_arrows_move_a_task_and_the_grip_drags_it() { let (mut harness, id) = list(&[item("a", false), item("b", false), item("c", false)]); focus_row(&mut harness, 0); press(&mut harness, Modifiers::ALT, Key::ArrowDown); - assert_eq!( - stored(&harness, &id), - owned(&[("b", false), ("a", false), ("c", false)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("b", false), ("a", false), ("c", false)])); let grips: Vec = harness .query_all_by(|node| node.author_id() == Some("checklist-grip")) @@ -201,10 +172,7 @@ fn alt_arrows_move_a_task_and_the_grip_drags_it() { harness.drop_at(to); settle(&mut harness); - assert_eq!( - stored(&harness, &id), - owned(&[("a", false), ("c", false), ("b", false)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("a", false), ("c", false), ("b", false)])); } #[test] @@ -227,10 +195,7 @@ fn a_box_clicked_while_a_row_is_typed_in_is_ticked() { .click(); settle(&mut harness); - assert_eq!( - stored(&harness, &id), - owned(&[("milk", true), ("eggs", false)]) - ); + assert_eq!(stored(&harness, &id), owned(&[("milk", true), ("eggs", false)])); } fn texts(harness: &Harness) -> Vec { @@ -245,11 +210,7 @@ fn texts(harness: &Harness) -> Vec { #[test] fn expanded_the_tasks_shown_narrow_to_those_open_or_done() { let (mut harness, _) = list(&[item("milk", true), item("bread", false)]); - assert!( - harness - .query_by(|node| node.author_id() == Some("checklist-shown-0")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("checklist-shown-0")).is_none()); harness.state_mut().state.settings.editor_fullscreen = true; settle(&mut harness); @@ -259,9 +220,94 @@ fn expanded_the_tasks_shown_narrow_to_those_open_or_done() { assert_eq!(texts(&harness), ["milk"]); click_id(&mut harness, "checklist-add"); - assert_eq!( - texts(&harness), - ["milk", "bread", ""], - "a task added shows them all" - ); + assert_eq!(texts(&harness), ["milk", "bread", ""], "a task added shows them all"); +} + +/// The list, the row and the caret it leaves, and whether there is something to write. +type Done = (Vec<(String, bool)>, Option<(usize, usize)>, bool); + +fn view(items: &[(&str, bool)]) -> super::ChecklistView { + super::ChecklistView { + items: items.iter().map(|(text, done)| item(text, *done)).collect(), + ..super::ChecklistView::default() + } +} + +fn after(items: &[(&str, bool)], index: usize, outcome: super::Outcome) -> Done { + let mut view = view(items); + let written = super::apply(&mut view, index, outcome); + let items = view.items.into_iter().map(|item| (item.text, item.done)).collect(); + (items, view.focus, written) +} + +#[test] +fn each_thing_a_row_asks_is_done_to_the_list() { + use super::{Outcome, RowKey}; + + let two = [("un", false), ("deux", true)]; + let end = usize::MAX; + for (index, outcome, items, focus, written) in [ + (1, Outcome::Toggled, vec![("un", false), ("deux", false)], None, true), + (1, Outcome::Removed, vec![("un", false)], Some((0, end)), true), + (0, Outcome::Removed, vec![("deux", true)], Some((0, end)), true), + (0, Outcome::Left, two.to_vec(), None, true), + (0, Outcome::Dropped(1), vec![("deux", true), ("un", false)], None, true), + (0, Outcome::Dropped(0), two.to_vec(), None, false), + (0, Outcome::Dropped(2), two.to_vec(), None, false), + (0, Outcome::Key(RowKey::Move(-1)), two.to_vec(), None, false), + ( + 1, + Outcome::Key(RowKey::Split(2)), + vec![("un", false), ("de", true), ("ux", false)], + Some((2, 0)), + true, + ), + ( + 1, + Outcome::Key(RowKey::Split(9)), + vec![("un", false), ("deux", true), ("", false)], + Some((2, 0)), + true, + ), + (1, Outcome::Key(RowKey::Join), vec![("undeux", false)], Some((0, 2)), true), + (0, Outcome::Key(RowKey::Join), two.to_vec(), None, false), + (1, Outcome::Key(RowKey::Remove), vec![("un", false)], Some((0, end)), true), + (0, Outcome::Key(RowKey::Paste(Vec::new())), two.to_vec(), None, true), + ] { + let (list, at, wrote) = after(&two, index, outcome); + assert_eq!(list, owned(&items)); + assert_eq!(wrote, written, "{items:?}"); + if focus.is_some() { + assert_eq!(at, focus, "{items:?}"); + } + } + let (list, focus, _) = after(&[("seul", false)], 0, super::Outcome::Removed); + assert!(list.is_empty() && focus.is_none()); +} + +/// What the row held goes before the first line, its tick with it; on an empty row, the lines alone. +#[test] +fn lines_pasted_follow_what_the_row_held() { + let lines = || super::RowKey::Paste(vec!["- [x] a".to_owned(), "2. b".to_owned()]); + let (list, focus, _) = after(&[("avant ", false), ("suite", false)], 0, super::Outcome::Key(lines())); + assert_eq!(list, owned(&[("avant a", false), ("b", false), ("suite", false)])); + assert_eq!(focus, Some((1, 1))); + + let (list, _, _) = after(&[(" ", false)], 0, super::Outcome::Key(lines())); + assert_eq!(list, owned(&[("a", true), ("b", false)])); +} + +/// The drag's keyboard twin, from the grip as from the row. +#[test] +fn the_grip_moves_its_task_with_alt_and_an_arrow() { + let (mut harness, _) = list(&[item("un", false), item("deux", false)]); + harness + .query_all_by(|node| node.author_id() == Some("checklist-grip")) + .next() + .unwrap() + .focus(); + settle(&mut harness); + press(&mut harness, Modifiers::ALT, Key::ArrowDown); + + assert_eq!(rows(&harness), ["deux", "un"]); } diff --git a/crates/ui/src/notes/overlays/editor/code.rs b/crates/ui/src/notes/overlays/editor/code.rs index dcac64a4a..43895408a 100644 --- a/crates/ui/src/notes/overlays/editor/code.rs +++ b/crates/ui/src/notes/overlays/editor/code.rs @@ -62,10 +62,7 @@ impl CodeView { fn fields(text: &str) -> Vec { api::notes::field_ranges(text) .into_iter() - .map(|range| Decoration { - range, - mark: Mark::Field, - }) + .map(|range| Decoration { range, mark: Mark::Field }) .collect() } @@ -83,8 +80,7 @@ pub(super) fn show( ) -> Shown { if code.language != language || (code.colouring.is_none() && text::highlight::is_ready()) { code.language = language; - code.colouring = - language::syntax(language).and_then(|syntax| Colouring::new(ui.ctx(), syntax)); + code.colouring = language::syntax(language).and_then(|syntax| Colouring::new(ui.ctx(), syntax)); } let mut changed = false; if let Some(replacing) = search_bar::shortcut(ui) { @@ -105,20 +101,12 @@ pub(super) fn show( let mut decorations = code.fields.clone(); if code.search.open { let selected = code.editor.buffer.selection().range(); - decorations.extend( - code.editor - .buffer - .find(&code.search.query, text::COUNT_CAP) - .into_iter() - .map(|range| Decoration { - mark: if range == selected { - Mark::CurrentMatch - } else { - Mark::Match - }, - range, - }), - ); + decorations.extend(code.editor.buffer.find(&code.search.query, text::COUNT_CAP).into_iter().map( + |range| Decoration { + mark: if range == selected { Mark::CurrentMatch } else { Mark::Match }, + range, + }, + )); } let p = palette(ui.ctx()); let colouring = code.colouring.as_mut(); @@ -130,12 +118,7 @@ pub(super) fn show( let colours = |line: usize, _: &str| -> Vec<(std::ops::Range, Color32)> { window .and_then(|colouring| colouring.line(line)) - .map(|tokens| { - tokens - .iter() - .map(|(range, token)| (range.clone(), tint(p, *token))) - .collect() - }) + .map(|tokens| tokens.iter().map(|(range, token)| (range.clone(), tint(p, *token))).collect()) .unwrap_or_default() }; let label = i18n::translate(locale, keys::editor::CONTENT_LABEL, &[]); @@ -155,10 +138,7 @@ pub(super) fn show( code.edited(line); changed = true; } - Shown { - changed, - left: output.response.lost_focus(), - } + Shown { changed, left: output.response.lost_focus() } } fn tint(p: &crate::theme::tokens::Palette, token: Token) -> Color32 { diff --git a/crates/ui/src/notes/overlays/editor/code/tests.rs b/crates/ui/src/notes/overlays/editor/code/tests.rs index 0051cc7db..f283e1e43 100644 --- a/crates/ui/src/notes/overlays/editor/code/tests.rs +++ b/crates/ui/src/notes/overlays/editor/code/tests.rs @@ -13,16 +13,10 @@ fn snippet(content: &str, language: Language) -> (Harness, String) { text::highlight::warm(); let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "deploy").id.clone(); - let patch = NotePatch { - content: Some(content.into()), - language: Some(language), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(content.into()), language: Some(language), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = expanded_area(backend, profile); click_id(&mut harness, "note-card-open"); (harness, id) @@ -30,12 +24,10 @@ fn snippet(content: &str, language: Language) -> (Harness, String) { fn stored(harness: &Harness, id: &str) -> String { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() - .content - .clone() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + .content + .clone() } fn press(harness: &mut Harness, modifiers: Modifiers, key: Key) { @@ -76,34 +68,20 @@ fn ctrl_f_finds_counts_and_moves_between_matches() { click_id(&mut harness, "editor-body"); press(&mut harness, Modifiers::COMMAND, Key::F); harness.get_by(|node| node.author_id() == Some("search-field")); - harness - .get_by(|node| node.author_id() == Some("search-field")) - .type_text("id"); + harness.get_by(|node| node.author_id() == Some("search-field")).type_text("id"); settle(&mut harness); assert_eq!(count(&harness), "1 / 4"); press(&mut harness, Modifiers::NONE, Key::Enter); assert_eq!(count(&harness), "2 / 4"); click_id(&mut harness, "search-word"); - assert_eq!( - count(&harness), - "3 matches", - "the one inside user_id no longer counts" - ); + assert_eq!(count(&harness), "3 matches", "the one inside user_id no longer counts"); press(&mut harness, Modifiers::SHIFT, Key::Enter); press(&mut harness, Modifiers::NONE, Key::Escape); - assert!( - harness - .query_by(|node| node.author_id() == Some("search-field")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("search-field")).is_none()); press(&mut harness, Modifiers::NONE, Key::End); press(&mut harness, Modifiers::NONE, Key::Enter); - assert_eq!( - code(&harness).lines().count(), - 4, - "the code has the keys back" - ); + assert_eq!(code(&harness).lines().count(), 4, "the code has the keys back"); } #[test] @@ -111,9 +89,7 @@ fn ctrl_h_replaces_one_then_all_and_one_undo_takes_all_back() { let (mut harness, id) = snippet("a b a b a", Language::Txt); click_id(&mut harness, "editor-body"); press(&mut harness, Modifiers::COMMAND, Key::H); - harness - .get_by(|node| node.author_id() == Some("search-field")) - .type_text("a"); + harness.get_by(|node| node.author_id() == Some("search-field")).type_text("a"); settle(&mut harness); click_id(&mut harness, "search-replace-field"); harness @@ -175,12 +151,7 @@ fn ctrl_alt_g_puts_the_caret_on_the_line_and_gives_the_keys_back() { let (mut harness, _) = snippet("un\ndeux\ntrois", Language::Txt); click_id(&mut harness, "editor-body"); go_to(&mut harness, "2"); - assert!( - harness - .query_by(|node| node.author_id() == Some("go-to-line-input")) - .is_none(), - "the bar went" - ); + assert!(harness.query_by(|node| node.author_id() == Some("go-to-line-input")).is_none(), "the bar went"); breaks_the_line(&mut harness); assert_eq!(code(&harness), "un\n\ndeux\ntrois"); } @@ -195,15 +166,6 @@ fn a_line_past_the_end_is_the_last_and_escape_leaves_the_bar() { press(&mut harness, Modifiers::COMMAND | Modifiers::ALT, Key::G); press(&mut harness, Modifiers::NONE, Key::Escape); - assert!( - harness - .query_by(|node| node.author_id() == Some("go-to-line-input")) - .is_none() - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-title")) - .is_some(), - "the editor stays" - ); + assert!(harness.query_by(|node| node.author_id() == Some("go-to-line-input")).is_none()); + assert!(harness.query_by(|node| node.author_id() == Some("editor-title")).is_some(), "the editor stays"); } diff --git a/crates/ui/src/notes/overlays/editor/drawing.rs b/crates/ui/src/notes/overlays/editor/drawing.rs index 9a3d13b65..716f10bb7 100644 --- a/crates/ui/src/notes/overlays/editor/drawing.rs +++ b/crates/ui/src/notes/overlays/editor/drawing.rs @@ -11,8 +11,8 @@ use crate::theme::tokens::{font, gap}; use drawing::{Attaching, Editor, Fill, Format, Frame, Grip, Hue, Mark, Point, Tool}; use egui::epaint::{PathShape, PathStroke, TextShape}; use egui::{ - Align, Color32, CornerRadius, CursorIcon, Key, Layout, Modifiers, Pos2, Rect, Response, Sense, - Shape, Stroke, StrokeKind, Ui, Vec2, + Align, Color32, CornerRadius, CursorIcon, Key, Layout, Modifiers, Pos2, Rect, Response, Sense, Shape, + Stroke, StrokeKind, Ui, Vec2, }; use i18n::{Language, keys}; @@ -33,49 +33,13 @@ const HUE_TINT: u8 = 36; const ASCENT: f32 = 0.97; const TOOLS: [(Tool, Icon, i18n::Key, &str, Key); 8] = [ - ( - Tool::Select, - Icon::MousePointer, - keys::drawing::SELECT, - "select", - Key::V, - ), - ( - Tool::Rectangle, - Icon::Square, - keys::drawing::RECTANGLE, - "rectangle", - Key::R, - ), - ( - Tool::Ellipse, - Icon::Circle, - keys::drawing::ELLIPSE, - "ellipse", - Key::O, - ), - ( - Tool::Diamond, - Icon::Diamond, - keys::drawing::DIAMOND, - "diamond", - Key::D, - ), - ( - Tool::Arrow, - Icon::ArrowRight, - keys::drawing::ARROW, - "arrow", - Key::A, - ), + (Tool::Select, Icon::MousePointer, keys::drawing::SELECT, "select", Key::V), + (Tool::Rectangle, Icon::Square, keys::drawing::RECTANGLE, "rectangle", Key::R), + (Tool::Ellipse, Icon::Circle, keys::drawing::ELLIPSE, "ellipse", Key::O), + (Tool::Diamond, Icon::Diamond, keys::drawing::DIAMOND, "diamond", Key::D), + (Tool::Arrow, Icon::ArrowRight, keys::drawing::ARROW, "arrow", Key::A), (Tool::Pen, Icon::Pencil, keys::drawing::PEN, "pen", Key::P), - ( - Tool::Eraser, - Icon::Eraser, - keys::drawing::ERASER, - "eraser", - Key::E, - ), + (Tool::Eraser, Icon::Eraser, keys::drawing::ERASER, "eraser", Key::E), (Tool::Text, Icon::Type, keys::drawing::TEXT, "text", Key::T), ]; @@ -172,13 +136,7 @@ fn file_name(title: &str, language: Language) -> String { let printable: String = title .chars() .filter(|character| *character >= ' ') - .map(|character| { - if r#"\/:*?"<>|"#.contains(character) { - '-' - } else { - character - } - }) + .map(|character| if r#"\/:*?"<>|"#.contains(character) { '-' } else { character }) .collect(); let name = printable.trim(); if name.is_empty() { @@ -249,10 +207,7 @@ pub(super) fn show( return on_stage(&mut stage_ui, view, (title, language)); } let export = toolbar(ui, view, language, !expanded); - Shown { - export, - ..on_stage(ui, view, (title, language)) - } + Shown { export, ..on_stage(ui, view, (title, language)) } } fn on_stage(ui: &mut Ui, view: &mut DrawingView, (title, language): (&str, Language)) -> Shown { @@ -271,11 +226,7 @@ fn on_stage(ui: &mut Ui, view: &mut DrawingView, (title, language): (&str, Langu let holds = has_keys(ui, &stage) || view.typing.is_some(); let left = view.held_keys && !holds; view.held_keys = holds; - Shown { - save: pause_over(ui, view) || left, - left, - export: None, - } + Shown { save: pause_over(ui, view) || left, left, export: None } } fn pause_over(ui: &Ui, view: &mut DrawingView) -> bool { @@ -289,8 +240,7 @@ fn pause_over(ui: &Ui, view: &mut DrawingView) -> bool { return false; }; if now < due { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(due - now)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(due - now)); return false; } view.save_at = None; @@ -298,12 +248,7 @@ fn pause_over(ui: &Ui, view: &mut DrawingView) -> bool { } /// The tools in a row; `exports`, the two buttons at its end. -fn toolbar( - ui: &mut Ui, - view: &mut DrawingView, - language: Language, - exports: bool, -) -> Option { +fn toolbar(ui: &mut Ui, view: &mut DrawingView, language: Language, exports: bool) -> Option { let p = palette(ui.ctx()); let mut export = None; let row = ui.horizontal_wrapped(|ui| { @@ -317,9 +262,7 @@ fn toolbar( widgets::wrap_before(ui, room); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { let drawn = view.editor.shapes() > 0; - export = ui - .add_enabled_ui(drawn, |ui| self::exports(ui, language)) - .inner; + export = ui.add_enabled_ui(drawn, |ui| self::exports(ui, language)).inner; }); }); ui.painter().hline( @@ -336,16 +279,12 @@ fn palette_column(ui: &mut Ui, view: &mut DrawingView, language: Language) -> Re let p = palette(ui.ctx()); let whole = ui.max_rect(); let column = Rect::from_min_size(whole.min, Vec2::new(PALETTE_WIDTH, whole.height())); - let mut column_ui = ui.new_child( - egui::UiBuilder::new() - .max_rect(column) - .layout(Layout::top_down(Align::Center)), - ); + let mut column_ui = + ui.new_child(egui::UiBuilder::new().max_rect(column).layout(Layout::top_down(Align::Center))); column_ui.spacing_mut().item_spacing.y = gap::TIGHT; tools(&mut column_ui, view, language, 10.0); let edge = whole.left() + PALETTE_WIDTH + 8.0; - ui.painter() - .vline(edge, whole.y_range(), Stroke::new(1.0, p.line_soft)); + ui.painter().vline(edge, whole.y_range(), Stroke::new(1.0, p.line_soft)); ui.advance_cursor_after_rect(whole); Rect::from_min_max(egui::pos2(edge + 8.0, whole.top()), whole.max) } @@ -420,9 +359,7 @@ fn swatch(ui: &mut Ui, view: &mut DrawingView, hue: Hue, language: Language) { crate::widgets::pointer(ui, &response); let on = view.editor.hue() == hue; let name = i18n::translate(language, colour_key(hue), &[]); - response.widget_info(|| { - egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, name.clone()) - }); + response.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, name.clone())); widgets::address(ui, &response, &format!("drawing-hue-{}", hue.name())); let painter = ui.painter(); painter.circle_filled(rect.center(), 8.0, stroke(p, hue)); @@ -495,12 +432,8 @@ fn keys_of(ui: &Ui, view: &mut DrawingView, stage: &Response) { if view.typing.is_some() || !(has_keys(ui, stage) || view.held_keys) { return; } - let pressed = |modifiers, key| { - ui.ctx() - .input_mut(|input| input.consume_key(modifiers, key)) - }; - if pressed(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z) || pressed(Modifiers::COMMAND, Key::Y) - { + let pressed = |modifiers, key| ui.ctx().input_mut(|input| input.consume_key(modifiers, key)); + if pressed(Modifiers::COMMAND | Modifiers::SHIFT, Key::Z) || pressed(Modifiers::COMMAND, Key::Y) { view.editor.redo(); } else if pressed(Modifiers::COMMAND, Key::Z) { view.editor.undo(); @@ -543,14 +476,8 @@ fn paint(ui: &Ui, view: &mut DrawingView, stage: Rect, language: Language) { let painter = ui.painter_at(stage); if view.editor.shapes() == 0 && view.editor.pen_line().is_none() { let words = i18n::translate(language, keys::drawing::EMPTY, &[]); - let galley = widgets::text( - ui, - &words, - font::READING, - 400.0, - egui::FontFamily::Proportional, - p.text_2, - ); + let galley = + widgets::text(ui, &words, font::READING, 400.0, egui::FontFamily::Proportional, p.text_2); let at = stage.center() - galley.size() / 2.0; painter.galley(at, galley, p.text_2); } @@ -561,10 +488,7 @@ fn paint(ui: &Ui, view: &mut DrawingView, stage: Rect, language: Language) { let at = |at: &Point| view.camera.screen_at(stage, *at); let line: Vec = points.iter().map(at).collect(); let width = view.camera.length(drawing::edit::PEN_WIDTH); - painter.add(Shape::line( - line, - Stroke::new(width, stroke(p, view.editor.hue())), - )); + painter.add(Shape::line(line, Stroke::new(width, stroke(p, view.editor.hue())))); } if view.editor.tool() == Tool::Eraser && let Some(at) = ui.input(|input| input.pointer.hover_pos()) @@ -573,10 +497,7 @@ fn paint(ui: &Ui, view: &mut DrawingView, stage: Rect, language: Language) { { // What a press would take away. let corners = frame.corners().map(|at| view.camera.screen_at(stage, at)); - painter.add(Shape::closed_line( - corners.to_vec(), - Stroke::new(2.0, p.red), - )); + painter.add(Shape::closed_line(corners.to_vec(), Stroke::new(2.0, p.red))); } if let Some(at) = ui.input(|input| input.pointer.latest_pos()) && stage.contains(at) @@ -587,12 +508,7 @@ fn paint(ui: &Ui, view: &mut DrawingView, stage: Rect, language: Language) { if let Some(ends) = view.editor.arrow_ends() { for (_, at) in ends { let centre = view.camera.screen_at(stage, at); - painter.circle( - centre, - GRIP_SIZE / 2.0, - p.amber_edge, - Stroke::new(1.0, p.bg_1), - ); + painter.circle(centre, GRIP_SIZE / 2.0, p.amber_edge, Stroke::new(1.0, p.bg_1)); } } if let Some(frame) = view.editor.frame() { @@ -609,21 +525,9 @@ fn paint(ui: &Ui, view: &mut DrawingView, stage: Rect, language: Language) { } } -fn paint_mark( - ui: &Ui, - painter: &egui::Painter, - p: &Palette, - (stage, camera): (Rect, Camera), - mark: &Mark, -) { +fn paint_mark(ui: &Ui, painter: &egui::Painter, p: &Palette, (stage, camera): (Rect, Camera), mark: &Mark) { match mark { - Mark::Line { - points, - closed, - fill, - hue, - width, - } => { + Mark::Line { points, closed, fill, hue, width } => { let colour = stroke(p, *hue); let at = |at: &Point| camera.screen_at(stage, *at); let line: Vec = points.iter().map(at).collect(); @@ -639,25 +543,12 @@ fn paint_mark( PathShape::line(line, edge) }); } - Mark::Words { - text, - at, - angle, - size, - hue, - } => { + Mark::Words { text, at, angle, size, hue } => { let colour = stroke(p, *hue); #[expect(clippy::cast_possible_truncation, reason = "an angle on the screen")] let turned = angle.to_radians() as f32; let size = camera.length(*size); - let galley = widgets::text( - ui, - text, - size, - 400.0, - egui::FontFamily::Proportional, - colour, - ); + let galley = widgets::text(ui, text, size, 400.0, egui::FontFamily::Proportional, colour); let above = egui::emath::Rot2::from_angle(turned) * Vec2::new(0.0, -ASCENT * size); let shape = TextShape::new(camera.screen_at(stage, *at) + above, galley, colour); painter.add(shape.with_angle(turned)); @@ -666,12 +557,7 @@ fn paint_mark( } /// What the end of the arrow would hold on to, and the points it can be held by. -fn paint_attaching( - painter: &egui::Painter, - p: &Palette, - (stage, camera): (Rect, Camera), - held: &Attaching, -) { +fn paint_attaching(painter: &egui::Painter, p: &Palette, (stage, camera): (Rect, Camera), held: &Attaching) { let edge = Stroke::new(2.0, p.amber_edge); let corners = held.frame.corners().map(|at| camera.screen_at(stage, at)); painter.add(Shape::closed_line(corners.to_vec(), edge)); @@ -687,24 +573,12 @@ fn paint_attaching( } } -fn paint_frame( - painter: &egui::Painter, - p: &Palette, - (stage, camera): (Rect, Camera), - frame: &Frame, -) { +fn paint_frame(painter: &egui::Painter, p: &Palette, (stage, camera): (Rect, Camera), frame: &Frame) { let edge = Stroke::new(1.0, p.amber_edge); - let corners: Vec = frame - .corners() - .iter() - .map(|at| camera.screen_at(stage, *at)) - .collect(); + let corners: Vec = frame.corners().iter().map(|at| camera.screen_at(stage, *at)).collect(); painter.add(Shape::closed_line(corners, edge)); painter.line_segment( - [ - camera.screen_at(stage, frame.grip(Grip::Top)), - camera.screen_at(stage, frame.grip(Grip::Rotate)), - ], + [camera.screen_at(stage, frame.grip(Grip::Top)), camera.screen_at(stage, frame.grip(Grip::Rotate))], edge, ); for grip in Grip::ALL { @@ -729,10 +603,10 @@ fn typing(ui: &mut Ui, view: &mut DrawingView, stage: Rect) { let place = view.camera.rect(stage, &object.bounds()); let font_size = view.camera.length(object.font_size()); let colour = stroke(p, object.hue()); - let mut field = view.typing.take().unwrap_or_else(|| Typing { - words: object.text().unwrap_or_default().to_owned(), - settling: true, - }); + let mut field = view + .typing + .take() + .unwrap_or_else(|| Typing { words: object.text().unwrap_or_default().to_owned(), settling: true }); let mut on_stage = ui.new_child(egui::UiBuilder::new().max_rect(place)); on_stage.set_clip_rect(stage.intersect(ui.clip_rect())); let response = on_stage.put( diff --git a/crates/ui/src/notes/overlays/editor/drawing/camera.rs b/crates/ui/src/notes/overlays/editor/drawing/camera.rs index a79cda2a2..0c98ef7f1 100644 --- a/crates/ui/src/notes/overlays/editor/drawing/camera.rs +++ b/crates/ui/src/notes/overlays/editor/drawing/camera.rs @@ -22,20 +22,14 @@ pub(super) struct Camera { impl Default for Camera { fn default() -> Self { - Self { - zoom: 1.0, - pan: Vec2::ZERO, - } + Self { zoom: 1.0, pan: Vec2::ZERO } } } impl Camera { pub(super) fn scene_at(&self, stage: Rect, at: Pos2) -> Point { let from = (at - stage.min - self.pan) / self.zoom; - Point { - x: f64::from(from.x), - y: f64::from(from.y), - } + Point { x: f64::from(from.x), y: f64::from(from.y) } } pub(super) fn screen_at(&self, stage: Rect, at: Point) -> Pos2 { @@ -52,10 +46,7 @@ impl Camera { } pub(super) fn rect(&self, stage: Rect, of: &Box) -> Rect { - let min = Point { - x: of.left, - y: of.top, - }; + let min = Point { x: of.left, y: of.top }; let size = Vec2::new(self.length(of.width), self.length(of.height)); Rect::from_min_size(self.screen_at(stage, min), size) } @@ -84,10 +75,7 @@ impl Camera { }; let room = (stage - Vec2::splat(2.0 * MARGIN)).max(Vec2::splat(1.0)); let zoom = (room / size).min_elem().clamp(LEAST, 1.0); - Self { - zoom, - pan: stage / 2.0 - centre * zoom, - } + Self { zoom, pan: stage / 2.0 - centre * zoom } } /// As a drawing opens: as it was drawn where the stage holds it, fitted where it does not. @@ -108,22 +96,14 @@ impl Camera { mod tests { use super::*; - const STAGE: Rect = Rect { - min: Pos2::new(100.0, 50.0), - max: Pos2::new(700.0, 450.0), - }; + const STAGE: Rect = Rect { min: Pos2::new(100.0, 50.0), max: Pos2::new(700.0, 450.0) }; fn near(a: Pos2, b: Pos2) -> bool { (a - b).length() < 0.01 } fn drawn(left: f64, top: f64, width: f64, height: f64) -> Box { - Box { - left, - top, - width, - height, - } + Box { left, top, width, height } } #[test] @@ -171,10 +151,7 @@ mod tests { assert_eq!(Camera::opening(size, None), Camera::default()); let small = drawn(20.0, 20.0, 200.0, 100.0); assert_eq!(Camera::opening(size, Some(&small)), Camera::default()); - for beyond in [ - drawn(20.0, 20.0, 900.0, 100.0), - drawn(-50.0, 0.0, 60.0, 60.0), - ] { + for beyond in [drawn(20.0, 20.0, 900.0, 100.0), drawn(-50.0, 0.0, 60.0, 60.0)] { let camera = Camera::opening(size, Some(&beyond)); assert!(STAGE.contains_rect(camera.rect(STAGE, &beyond))); } diff --git a/crates/ui/src/notes/overlays/editor/drawing/look.rs b/crates/ui/src/notes/overlays/editor/drawing/look.rs index 14e2a70fd..8fbdf44a9 100644 --- a/crates/ui/src/notes/overlays/editor/drawing/look.rs +++ b/crates/ui/src/notes/overlays/editor/drawing/look.rs @@ -154,30 +154,19 @@ pub(super) fn controls(ui: &mut Ui, view: &mut DrawingView, stage: Rect, languag ); row.spacing_mut().item_spacing.x = gap::LINE; let out = tr(keys::drawing::ZOOM_OUT); - if IconButton::new(Icon::Minus, &out, "drawing-zoom-out") - .show(&mut row) - .clicked() - { + if IconButton::new(Icon::Minus, &out, "drawing-zoom-out").show(&mut row).clicked() { zoom(view, stage, 1.0 / STEP); } - let reset = Button::new(&shown, "drawing-zoom") - .kind(Kind::Quiet) - .show(&mut row); + let reset = Button::new(&shown, "drawing-zoom").kind(Kind::Quiet).show(&mut row); if widgets::tooltip(reset, &tr(keys::drawing::ZOOM_RESET)).clicked() { whole_size(view, stage); } let closer = tr(keys::drawing::ZOOM_IN); - if IconButton::new(Icon::Plus, &closer, "drawing-zoom-in") - .show(&mut row) - .clicked() - { + if IconButton::new(Icon::Plus, &closer, "drawing-zoom-in").show(&mut row).clicked() { zoom(view, stage, STEP); } let whole = tr(keys::drawing::FIT); - if IconButton::new(Icon::Maximize, &whole, "drawing-fit") - .show(&mut row) - .clicked() - { + if IconButton::new(Icon::Maximize, &whole, "drawing-fit").show(&mut row).clicked() { fit(view, stage); } } diff --git a/crates/ui/src/notes/overlays/editor/drawing/tests.rs b/crates/ui/src/notes/overlays/editor/drawing/tests.rs index 616a37ffe..567114c89 100644 --- a/crates/ui/src/notes/overlays/editor/drawing/tests.rs +++ b/crates/ui/src/notes/overlays/editor/drawing/tests.rs @@ -19,10 +19,8 @@ fn opened(content: &str) -> (Harness, String) { ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = expanded_area(backend, profile); harness.state_mut().state.editor.open(id.clone()); settle(&mut harness); @@ -31,10 +29,8 @@ fn opened(content: &str) -> (Harness, String) { fn stored(harness: &Harness, id: &str) -> DisplayNote { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() } fn thumbnail(harness: &Harness, id: &str) -> Option { @@ -108,11 +104,7 @@ fn a_tool_draws_on_the_stage_and_the_close_writes_it_with_its_pictures() { close(&mut harness); let note = stored(&harness, &id); - assert!( - note.content.contains(r#""type":"Rect""#), - "{}", - note.content - ); + assert!(note.content.contains(r#""type":"Rect""#), "{}", note.content); assert!(note.content.contains(r#""hue":"ink""#)); assert!(thumbnail(&harness, &id).is_some()); } @@ -167,7 +159,8 @@ fn opened_and_closed_nothing_moves() { #[test] fn a_drawing_with_no_picture_takes_them_on_being_left_and_no_date_moves() { - let scene = r#"{"version":1,"scene":{"objects":[{"type":"Rect","left":60,"top":45,"width":100,"height":50}]}}"#; + let scene = + r#"{"version":1,"scene":{"objects":[{"type":"Rect","left":60,"top":45,"width":100,"height":50}]}}"#; let (mut harness, id) = opened(scene); let before = stored(&harness, &id).updated_at; @@ -203,17 +196,12 @@ fn the_tools_answer_to_their_letters_and_escape_drops_tool_then_selection_then_s } fn pressed(harness: &Harness, id: &str) -> bool { - harness - .get_by(|node| node.author_id() == Some(id)) - .accesskit_node() - .toggled() + harness.get_by(|node| node.author_id() == Some(id)).accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) } fn is_open(harness: &Harness) -> bool { - harness - .query_by(|node| node.author_id() == Some("editor-title")) - .is_some() + harness.query_by(|node| node.author_id() == Some("editor-title")).is_some() } /// A window without the system's focus still answers the keys it is sent: a test's has none. @@ -268,9 +256,7 @@ fn a_text_is_typed_where_clicked_and_stored() { let at = point(&harness, 60.0, 60.0); drag(&mut harness, at, at); - harness - .get_by(|node| node.author_id() == Some("drawing-text")) - .type_text("API"); + harness.get_by(|node| node.author_id() == Some("drawing-text")).type_text("API"); harness.run_steps(3); close(&mut harness); @@ -293,14 +279,7 @@ fn a_new_drawing_left_empty_is_never_written() { } fn cards(harness: &Harness) -> usize { - harness - .state() - .state - .notes_query - .view() - .unwrap() - .cards() - .count() + harness.state().state.notes_query.view().unwrap().cards().count() } #[test] @@ -416,10 +395,7 @@ fn nothing_drawn_has_nothing_to_export() { fn a_file_is_named_after_the_title_with_what_no_system_refuses() { use i18n::Language; - assert_eq!( - file_name("Archi: v2/final?", Language::En), - "Archi- v2-final-" - ); + assert_eq!(file_name("Archi: v2/final?", Language::En), "Archi- v2-final-"); assert_eq!(file_name(" sketch\u{7} ", Language::En), "sketch"); assert_eq!(file_name(" ", Language::En), "Drawing"); assert_eq!(file_name("", Language::Fr), "Dessin"); @@ -614,11 +590,7 @@ fn an_arrow_selected_is_moved_by_its_ends() { // Back on the middle of that side: the point is the one it keeps. drag(&mut harness, away, start); assert!(bound(&mut harness)); - assert!( - stored(&harness, &id) - .content - .contains(r#""fromAnchor":"right""#) - ); + assert!(stored(&harness, &id).content.contains(r#""fromAnchor":"right""#)); } /// The toolbar of a panel: nothing over anything else. @@ -630,12 +602,7 @@ fn in_a_narrow_panel_the_exports_take_a_line_of_their_own() { settle(&mut harness); let rect = |id: &str| harness.get_by(|node| node.author_id() == Some(id)).rect(); - let tools = [ - "drawing-tool-select", - "drawing-hue-purple", - "drawing-undo", - "drawing-delete", - ]; + let tools = ["drawing-tool-select", "drawing-hue-purple", "drawing-undo", "drawing-delete"]; for export in ["drawing-export-png", "drawing-export-svg"] { for tool in tools { assert!(!rect(export).intersects(rect(tool)), "{export} over {tool}"); diff --git a/crates/ui/src/notes/overlays/editor/expanded.rs b/crates/ui/src/notes/overlays/editor/expanded.rs index 94f110922..9322ab2b6 100644 --- a/crates/ui/src/notes/overlays/editor/expanded.rs +++ b/crates/ui/src/notes/overlays/editor/expanded.rs @@ -9,8 +9,8 @@ use engine::notes::model::DisplayNote; use i18n::keys; use super::{ - EditorView, ExplorerLayout, band, body, close_button, copy, drawing, editor, expand_button, - fields, format, header, json_view, language_menu, more_menu, pin, revisions, save, title, + EditorView, ExplorerLayout, band, body, close_button, copy, drawing, editor, expand_button, fields, + format, header, json_view, language_menu, more_menu, pin, revisions, save, title, }; use crate::action::Actions; use crate::notes::Editing; @@ -50,11 +50,7 @@ pub(super) fn show( let top = ui.cursor().top(); let foot = whole.bottom() - STATUS_HEIGHT; let details = shows_details(state, whole.width()); - let split = if details { - whole.right() - DETAILS_WIDTH - } else { - whole.right() - }; + let split = if details { whole.right() - DETAILS_WIDTH } else { whole.right() }; if details { let column = Rect::from_min_max(pos2(split, top), pos2(whole.right(), foot)); let line = Stroke::new(1.0, palette(ui.ctx()).line_soft); @@ -65,21 +61,9 @@ pub(super) fn show( let main = Rect::from_min_max(pos2(whole.left(), top), pos2(split, foot)); let mut main_ui = child(ui, main, "editor-main"); let history_below = !details; - main_column( - &mut main_ui, - state, - (session, note), - (editing, layout), - history_below, - actions, - ); + main_column(&mut main_ui, state, (session, note), (editing, layout), history_below, actions); let status = Rect::from_min_max(pos2(whole.left(), foot), whole.max); - super::footer( - &mut child(ui, status, "editor-status"), - state, - note, - editing, - ); + super::footer(&mut child(ui, status, "editor-status"), state, note, editing); ui.advance_cursor_after_rect(whole); closed } @@ -129,18 +113,11 @@ fn main_column( }); } let top = ui.cursor().top(); - let history = if history_below { - revisions::height(state, whole.bottom() - top - super::BODY_FLOOR) - } else { - 0.0 - }; + let history = + if history_below { revisions::height(state, whole.bottom() - top - super::BODY_FLOOR) } else { 0.0 }; let bottom = whole.bottom() - history; let filled = !note.placeholders.is_empty() && editing.exploring.is_none(); - let code_bottom = if filled { - (bottom - (bottom - top) * FILLED_SHARE).round() - } else { - bottom - }; + let code_bottom = if filled { (bottom - (bottom - top) * FILLED_SHARE).round() } else { bottom }; let body_rect = Rect::from_min_max(pos2(whole.left(), top), pos2(whole.right(), code_bottom)); let mut inner = body_rect.shrink2(Vec2::new(20.0, 14.0)); if note.kind == NoteKind::Checklist && inner.width() > TASKS_WIDTH { @@ -149,14 +126,7 @@ fn main_column( let mut body_ui = ui.new_child(UiBuilder::new().max_rect(inner)); body_ui.set_clip_rect(body_ui.clip_rect().intersect(body_rect)); let typed = editing.body.clone(); - let left = body( - &mut body_ui, - state, - (session, note), - (editing, layout), - false, - actions, - ); + let left = body(&mut body_ui, state, (session, note), (editing, layout), false, actions); if left { save(session, note, editing, actions); } @@ -170,11 +140,7 @@ fn main_column( } if history > 0.0 { let rect = Rect::from_min_max(pos2(whole.left(), bottom), whole.max); - revisions::show( - &mut ui.new_child(UiBuilder::new().max_rect(rect)), - state, - actions, - ); + revisions::show(&mut ui.new_child(UiBuilder::new().max_rect(rect)), state, actions); } } @@ -207,8 +173,7 @@ fn filled_below( editing.fields.asked = true; fields::preview(session, note, editing, actions); } - ui.painter() - .hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); let mut area = ui.new_child( UiBuilder::new() .max_rect(rect.shrink2(Vec2::new(20.0, 10.0))) @@ -284,12 +249,10 @@ fn primary( .enabled(view.shapes() > 0) .show(ui); let mut chosen = None; - egui::Popup::menu(&trigger) - .frame(widgets::menu_frame(ui.ctx())) - .show(|ui| { - ui.spacing_mut().item_spacing.y = gap::TIGHT; - chosen = drawing::exports(ui, state.language); - }); + egui::Popup::menu(&trigger).frame(widgets::menu_frame(ui.ctx())).show(|ui| { + ui.spacing_mut().item_spacing.y = gap::TIGHT; + chosen = drawing::exports(ui, state.language); + }); if let Some(format) = chosen { super::export(ui, note, view, format, state, actions); } @@ -299,18 +262,10 @@ fn primary( /// there is no room for it. fn details_button(ui: &mut Ui, state: &AppState, room: bool, actions: &mut Actions) { let open = state.settings.editor_details_open; - let key = if open { - keys::editor::details::HIDE - } else { - keys::editor::details::SHOW - }; + let key = if open { keys::editor::details::HIDE } else { keys::editor::details::SHOW }; let words = i18n::translate(state.language, keys::editor::details::SHOW, &[]); let hint = i18n::translate(state.language, key, &[]); - let icon = if open { - Icon::ChevronRight - } else { - Icon::ChevronLeft - }; + let icon = if open { Icon::ChevronRight } else { Icon::ChevronLeft }; let clicked = Button::new(&words, "editor-details") .kind(Kind::Outline) .icon(icon) @@ -360,15 +315,8 @@ fn place_of(state: &AppState, note: &DisplayNote) -> String { .iter() .find(|space| space.id == note.space_id) .map(|space| space.name.clone()); - let folders = note - .folder - .iter() - .flat_map(|folder| folder.path.iter().cloned()); - space - .into_iter() - .chain(folders) - .collect::>() - .join(" › ") + let folders = note.folder.iter().flat_map(|folder| folder.path.iter().cloned()); + space.into_iter().chain(folders).collect::>().join(" › ") } /// ‹ n / total ›: where the note open sits among the cards shown, and the way to its neighbours. @@ -378,12 +326,7 @@ fn steps(ui: &mut Ui, state: &AppState, actions: &mut Actions) { }; let tr = |key| i18n::translate(state.language, key, &[]); let next = ui.add_enabled_ui(at + 1 < order.len(), |ui| { - IconButton::new( - Icon::ChevronRight, - &tr(keys::editor::NEXT_NOTE), - "editor-next", - ) - .show(ui) + IconButton::new(Icon::ChevronRight, &tr(keys::editor::NEXT_NOTE), "editor-next").show(ui) }); if next.inner.clicked() { actions.push(editor(Editing::Step(1))); @@ -393,10 +336,7 @@ fn steps(ui: &mut Ui, state: &AppState, actions: &mut Actions) { keys::editor::POSITION, &[ ("at", u32::try_from(at + 1).unwrap_or(u32::MAX).into()), - ( - "total", - u32::try_from(order.len()).unwrap_or(u32::MAX).into(), - ), + ("total", u32::try_from(order.len()).unwrap_or(u32::MAX).into()), ], ); let shown = ui.label( diff --git a/crates/ui/src/notes/overlays/editor/fields.rs b/crates/ui/src/notes/overlays/editor/fields.rs index ed206792d..5178a13ae 100644 --- a/crates/ui/src/notes/overlays/editor/fields.rs +++ b/crates/ui/src/notes/overlays/editor/fields.rs @@ -44,12 +44,7 @@ impl FieldsView { .iter() .map(|field| (field.name.clone(), field.value.clone())) .collect(); - Self { - typed: stored.clone(), - kept: stored, - previewing: false, - asked: false, - } + Self { typed: stored.clone(), kept: stored, previewing: false, asked: false } } /// Every field by name, raw: `notes::placeholder::fill` decides what an empty one is worth. @@ -91,9 +86,7 @@ pub(super) fn show( // A field the text just gained: the values stored under its name, if it had some. for field in ¬e.placeholders { let typed = &mut editing.fields.typed; - typed - .entry(field.name.clone()) - .or_insert_with(|| field.value.clone()); + typed.entry(field.name.clone()).or_insert_with(|| field.value.clone()); } let open = state.settings.editor_fields_open; let values = editing.fields.values(note); @@ -124,12 +117,7 @@ pub(super) fn show( } } -pub(super) fn preview( - session: u64, - note: &DisplayNote, - editing: &EditorView, - actions: &mut Actions, -) { +pub(super) fn preview(session: u64, note: &DisplayNote, editing: &EditorView, actions: &mut Actions) { actions.push(editor(Editing::Fields(Fields::Preview { session, content: editing.body.clone(), @@ -138,13 +126,7 @@ pub(super) fn preview( } /// The strip is the button: a row that lights up reads as a control, a bare label as a heading. -fn toggle( - ui: &mut Ui, - language: Language, - open: bool, - values: &Values, - note: &DisplayNote, -) -> bool { +fn toggle(ui: &mut Ui, language: Language, open: bool, values: &Values, note: &DisplayNote) -> bool { let p = palette(ui.ctx()); let size = Vec2::new(ui.available_width(), HEAD_HEIGHT); let (rect, response) = ui.allocate_exact_size(size, Sense::click()); @@ -152,29 +134,14 @@ fn toggle( if response.hovered() { ui.painter().rect_filled(rect, 7.0, p.bg_2); } - let ink = if response.hovered() { - p.text_0 - } else { - p.text_1 - }; - let caret = if open { - Icon::ChevronDown - } else { - Icon::ChevronRight - }; + let ink = if response.hovered() { p.text_0 } else { p.text_1 }; + let caret = if open { Icon::ChevronDown } else { Icon::ChevronRight }; let at = rect.left() + 8.0; let middle = rect.center().y; let square = Rect::from_center_size(egui::pos2(at + 6.0, middle), Vec2::splat(12.0)); icons::paint(ui, square, caret, ink); let title = i18n::translate(language, keys::placeholders::PANEL_TITLE, &[]); - let words = widgets::text( - ui, - &title, - font::LABEL, - 600.0, - FontFamily::Proportional, - ink, - ); + let words = widgets::text(ui, &title, font::LABEL, 600.0, FontFamily::Proportional, ink); let title_at = egui::pos2(at + 20.0, middle - words.size().y / 2.0); let after_title = title_at.x + words.size().x + 8.0; ui.painter().galley(title_at, words, ink); @@ -183,23 +150,9 @@ fn toggle( let after_count = count(ui, (done, total), egui::pos2(after_title, middle)); let verb = (!open).then(|| { let verb = i18n::translate(language, keys::placeholders::SHOW, &[]); - let colour = if response.hovered() { - p.amber_text - } else { - p.text_2 - }; - let words = widgets::text( - ui, - &verb, - font::META, - 400.0, - FontFamily::Proportional, - colour, - ); - let at = egui::pos2( - rect.right() - 8.0 - words.size().x, - middle - words.size().y / 2.0, - ); + let colour = if response.hovered() { p.amber_text } else { p.text_2 }; + let words = widgets::text(ui, &verb, font::META, 400.0, FontFamily::Proportional, colour); + let at = egui::pos2(rect.right() - 8.0 - words.size().x, middle - words.size().y / 2.0); let left = at.x; ui.painter().galley(at, words, colour); left @@ -207,26 +160,14 @@ fn toggle( let line = summary(values, note, language); if let Some(right) = verb { let room = Rect::from_x_y_ranges(after_count + 8.0..=right - 8.0, rect.y_range()); - let words = widgets::text( - ui, - &line, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let words = widgets::text(ui, &line, font::META, 400.0, FontFamily::Monospace, p.text_2); let at = egui::pos2(room.left(), middle - words.size().y / 2.0); - ui.painter() - .with_clip_rect(room) - .galley(at, words, p.text_2); + ui.painter().with_clip_rect(room).galley(at, words, p.text_2); } let said = i18n::translate( language, keys::placeholders::FILLED_COUNT, - &[ - ("filled", counted(done).into()), - ("total", counted(total).into()), - ], + &[("filled", counted(done).into()), ("total", counted(total).into())], ); ui.ctx().accesskit_node_builder(response.id, |node| { let held = if open { "" } else { line.as_str() }; @@ -252,18 +193,10 @@ fn count(ui: &Ui, (done, total): (usize, usize), left_middle: egui::Pos2) -> f32 let words = widgets::text(ui, &words, font::CAPTION, 400.0, FontFamily::Monospace, ink); let size = words.size() + Vec2::new(16.0, 2.0); let pill = Rect::from_min_size(left_middle - Vec2::new(0.0, size.y / 2.0), size); - let fill = if complete { - p.amber_fill.gamma_multiply(0.1) - } else { - p.bg_2 - }; + let fill = if complete { p.amber_fill.gamma_multiply(0.1) } else { p.bg_2 }; ui.painter().rect_filled(pill, size.y / 2.0, fill); - ui.painter().rect_stroke( - pill, - size.y / 2.0, - Stroke::new(1.0, line), - egui::StrokeKind::Inside, - ); + ui.painter() + .rect_stroke(pill, size.y / 2.0, Stroke::new(1.0, line), egui::StrokeKind::Inside); let at = pill.center() - words.size() / 2.0; ui.painter().galley(at, words, ink); pill.right() @@ -311,28 +244,20 @@ fn head_actions( editing.fields.keep(note, actions); changed = true; } - if Button::new( - &tr(keys::placeholders::COPY_RAW), - "placeholder-panel-copy-raw", - ) - .icon(Icon::Copy) - .show(ui) - .clicked() + if Button::new(&tr(keys::placeholders::COPY_RAW), "placeholder-panel-copy-raw") + .icon(Icon::Copy) + .show(ui) + .clicked() { - actions.push(editor(Editing::Fields(Fields::CopyRaw( - editing.body.clone(), - )))); + actions.push(editor(Editing::Fields(Fields::CopyRaw(editing.body.clone())))); } let previewing = editing.fields.previewing; if !state.settings.editor_fullscreen - && Button::new( - &tr(keys::placeholders::PREVIEW), - "placeholder-panel-preview", - ) - .icon(Icon::Eye) - .armed(previewing) - .show(ui) - .clicked() + && Button::new(&tr(keys::placeholders::PREVIEW), "placeholder-panel-preview") + .icon(Icon::Eye) + .armed(previewing) + .show(ui) + .clicked() { editing.fields.previewing = !previewing; if !previewing { @@ -357,12 +282,7 @@ fn body( let mut left = false; let frame = egui::Frame::new() .fill(p.bg_0) - .inner_margin(Margin { - left: 20, - right: 20, - top: 10, - bottom: 12, - }) + .inner_margin(Margin { left: 20, right: 20, top: 10, bottom: 12 }) .show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = gap::SNUG; @@ -378,12 +298,8 @@ fn body( } let hint = i18n::translate(language, keys::placeholders::PANEL_HINT, &[]); ui.add( - egui::Label::new( - egui::RichText::new(hint) - .size(font::CAPTION) - .color(p.text_2), - ) - .wrap(), + egui::Label::new(egui::RichText::new(hint).size(font::CAPTION).color(p.text_2)) + .wrap(), ); }); }); diff --git a/crates/ui/src/notes/overlays/editor/fields/tests.rs b/crates/ui/src/notes/overlays/editor/fields/tests.rs index f470f920d..5e5c9a6b9 100644 --- a/crates/ui/src/notes/overlays/editor/fields/tests.rs +++ b/crates/ui/src/notes/overlays/editor/fields/tests.rs @@ -12,15 +12,10 @@ const BODY: &str = "psql -h {{host}} -p {{port=5432}}"; fn opened(text: &str) -> (Harness, String) { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "psql").id.clone(); - let patch = NotePatch { - content: Some(text.to_owned()), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(text.to_owned()), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = area(backend, profile); harness.state_mut().state.editor.open(id.clone()); settle(&mut harness); @@ -30,10 +25,8 @@ fn opened(text: &str) -> (Harness, String) { fn stored(harness: &Harness, id: &str) -> DisplayNote { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() } fn value_of(note: &DisplayNote, name: &str) -> String { @@ -42,9 +35,7 @@ fn value_of(note: &DisplayNote, name: &str) -> String { } fn has(harness: &Harness, id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(id)).is_some() } fn counted(harness: &Harness) -> String { @@ -74,9 +65,7 @@ fn type_first(harness: &mut Harness, words: &str) { /// `author_id` clicked, then what reached the clipboard. fn copied_by(harness: &mut Harness, author_id: &str) -> Option { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); let mut copied = None; for _ in 0..60 { harness.step(); diff --git a/crates/ui/src/notes/overlays/editor/format.rs b/crates/ui/src/notes/overlays/editor/format.rs index 9fe94e477..ff88679a0 100644 --- a/crates/ui/src/notes/overlays/editor/format.rs +++ b/crates/ui/src/notes/overlays/editor/format.rs @@ -6,8 +6,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Align, CornerRadius, Key, Layout, Modifiers, Popup, PopupCloseBehavior, Rect, Stroke, - StrokeKind, Ui, UiBuilder, pos2, vec2, + Align, CornerRadius, Key, Layout, Modifiers, Popup, PopupCloseBehavior, Rect, Stroke, StrokeKind, Ui, + UiBuilder, pos2, vec2, }; use engine::notes::language::Language; use engine::notes::model::DisplayNote; @@ -77,10 +77,7 @@ fn ready(state: &AppState, (session, note): (u64, &DisplayNote), editing: &Edito language::formatter(note.language).is_some() && !state.formatting.busy(session) && !editing.fields.previewing - && editing - .exploring - .as_ref() - .is_none_or(super::json_view::Exploring::shows_code) + && editing.exploring.as_ref().is_none_or(super::json_view::Exploring::shows_code) } /// The button and, joined to it, the chevron that opens the settings. @@ -104,19 +101,13 @@ pub(super) fn button( ) }; let enabled = ready(state, (session, note), editing); - let (label, keys) = ( - tr(keys::editor::format::LABEL), - tr(keys::editor::format::KEYS), - ); + let (label, keys) = (tr(keys::editor::format::LABEL), tr(keys::editor::format::KEYS)); let settings = tr(keys::editor::format::SETTINGS); - let mut split = SplitButton::new( - (&label, "editor-format"), - (&settings, "editor-format-settings"), - SplitKind::Tint, - ) - .icon(Icon::Format) - .keys(&keys) - .enabled(enabled); + let mut split = + SplitButton::new((&label, "editor-format"), (&settings, "editor-format-settings"), SplitKind::Tint) + .icon(Icon::Format) + .keys(&keys) + .enabled(enabled); if !labelled { split = split.icon_only(); } @@ -139,8 +130,7 @@ pub(super) fn shortcut( editing: &mut EditorView, actions: &mut Actions, ) { - let pressed = - ui.input_mut(|input| input.consume_key(Modifiers::SHIFT | Modifiers::ALT, Key::F)); + let pressed = ui.input_mut(|input| input.consume_key(Modifiers::SHIFT | Modifiers::ALT, Key::F)); if pressed && ready(state, (session, note), editing) { ask(state, (session, note), editing, actions); } @@ -182,9 +172,7 @@ pub(super) fn adopt(ui: &Ui, state: &AppState, session: u64, editing: &mut Edito let text = code.text(); if answered.quiet { // Formatted on save, and written so: the field follows unless it was typed into since. - if let Answer::Formatted { - text: formatted, .. - } = &answered.answer + if let Answer::Formatted { text: formatted, .. } = &answered.answer && *formatted != text && editing.body == text { @@ -198,11 +186,7 @@ pub(super) fn adopt(ui: &Ui, state: &AppState, session: u64, editing: &mut Edito return; } let notice = match &answered.answer { - Answer::Formatted { - text: formatted, - cursor, - changed_lines, - } => { + Answer::Formatted { text: formatted, cursor, changed_lines } => { code.editor.replace_all(formatted); code.edited(0); code.editor.select(*cursor..*cursor); @@ -214,10 +198,7 @@ pub(super) fn adopt(ui: &Ui, state: &AppState, session: u64, editing: &mut Edito Answer::Syntax { line, column } => { let at = offset_of(&code.editor.buffer, *line, *column); code.editor.select(at..at); - Notice::Syntax { - line: *line, - column: *column, - } + Notice::Syntax { line: *line, column: *column } } Answer::Fields => Notice::Fields, Answer::Failed => Notice::Failed, @@ -245,8 +226,7 @@ pub(super) fn notice(ui: &mut Ui, state: &AppState, body: Rect, editing: &mut Ed editing.format.notice = None; return; } - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(until - now)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(until - now)); let p = palette(ui.ctx()); let language = state.language; let words = match notice { @@ -268,38 +248,16 @@ pub(super) fn notice(ui: &mut Ui, state: &AppState, body: Rect, editing: &mut Ed Notice::Fields => i18n::translate(language, keys::editor::format::FIELDS, &[]), Notice::Failed => i18n::translate(language, keys::editor::format::FAILED, &[]), }; - let failed = matches!( - notice, - Notice::Syntax { .. } | Notice::Fields | Notice::Failed - ); + let failed = matches!(notice, Notice::Syntax { .. } | Notice::Fields | Notice::Failed); let undo = i18n::translate(language, keys::editor::format::UNDO, &[]); - let galley = widgets::text( - ui, - &words, - font::BODY, - 400.0, - egui::FontFamily::Proportional, - p.text_0, - ); - let undo_room = if matches!(notice, Notice::Formatted(_)) { - Button::width(ui, &undo) + 12.0 - } else { - 0.0 - }; + let galley = widgets::text(ui, &words, font::BODY, 400.0, egui::FontFamily::Proportional, p.text_0); + let undo_room = + if matches!(notice, Notice::Formatted(_)) { Button::width(ui, &undo) + 12.0 } else { 0.0 }; let size = vec2(galley.size().x + undo_room + 28.0, 40.0); - let rect = Rect::from_center_size( - pos2(body.center().x, body.bottom() - 16.0 - size.y / 2.0), - size, - ); - let edge = if failed { - p.red.gamma_multiply(0.5) - } else { - p.line - }; - ui.painter().add( - p.shadow_overlay - .as_shape(rect, CornerRadius::same(radius::CARD)), - ); + let rect = Rect::from_center_size(pos2(body.center().x, body.bottom() - 16.0 - size.y / 2.0), size); + let edge = if failed { p.red.gamma_multiply(0.5) } else { p.line }; + ui.painter() + .add(p.shadow_overlay.as_shape(rect, CornerRadius::same(radius::CARD))); ui.painter().rect( rect, CornerRadius::same(radius::CARD), @@ -317,9 +275,7 @@ pub(super) fn notice(ui: &mut Ui, state: &AppState, body: Rect, editing: &mut Ed let said = inner.label(galley); widgets::address(&inner, &said, "editor-format-notice"); let kind = notice.kind(); - inner - .ctx() - .accesskit_node_builder(said.id, |node| node.set_description(kind)); + inner.ctx().accesskit_node_builder(said.id, |node| node.set_description(kind)); if matches!(notice, Notice::Formatted(_)) && Button::new(&undo, "editor-format-undo") .kind(widgets::Kind::Quiet) @@ -358,13 +314,9 @@ fn panel(ui: &mut Ui, state: &AppState, width: &mut Option, actions: &mu setting(ui, &tr(keys::editor::format::PRINT_WIDTH), |ui| { ui.set_max_width(WIDTH_FIELD); let typed = width.get_or_insert_with(|| now.print_width.to_string()); - let field = TextField::new( - typed, - &tr(keys::editor::format::PRINT_WIDTH), - "prettier-width", - ) - .compact() - .show(ui); + let field = TextField::new(typed, &tr(keys::editor::format::PRINT_WIDTH), "prettier-width") + .compact() + .show(ui); if field.lost_focus() { if let Some(clamped) = typed.trim().parse::().ok().and_then(clamp_width) { next.print_width = clamped; @@ -376,10 +328,8 @@ fn panel(ui: &mut Ui, state: &AppState, width: &mut Option, actions: &mu .into_iter() .map(|each| (each, tr(indentation_key(each)))) .collect(); - let options: Vec<(Indentation, &str)> = indentations - .iter() - .map(|(each, name)| (*each, name.as_str())) - .collect(); + let options: Vec<(Indentation, &str)> = + indentations.iter().map(|(each, name)| (*each, name.as_str())).collect(); setting(ui, &tr(keys::editor::format::INDENTATION), |ui| { Segmented::new(&options, "prettier-indentation").show(ui, &mut next.indentation); }); @@ -390,21 +340,9 @@ fn panel(ui: &mut Ui, state: &AppState, width: &mut Option, actions: &mu Segmented::new("es, "prettier-quotes").show(ui, &mut next.single_quote); }); for (key, author_id, value) in [ - ( - keys::editor::format::SEMICOLONS, - "prettier-semicolons", - &mut next.semicolons, - ), - ( - keys::editor::format::TRAILING_COMMAS, - "prettier-trailingCommas", - &mut next.trailing_commas, - ), - ( - keys::editor::format::FORMAT_ON_SAVE, - "prettier-formatOnSave", - &mut next.format_on_save, - ), + (keys::editor::format::SEMICOLONS, "prettier-semicolons", &mut next.semicolons), + (keys::editor::format::TRAILING_COMMAS, "prettier-trailingCommas", &mut next.trailing_commas), + (keys::editor::format::FORMAT_ON_SAVE, "prettier-formatOnSave", &mut next.format_on_save), ] { let label = tr(key); setting(ui, &label, |ui| { @@ -422,11 +360,7 @@ fn panel(ui: &mut Ui, state: &AppState, width: &mut Option, actions: &mu &[("list", formatted.join(", ").into())], ); note(ui, &tr(keys::editor::format::FORMATTED_TITLE), &list); - note( - ui, - &tr(keys::editor::format::NOT_FORMATTED_TITLE), - &tr(keys::editor::format::NOT_FORMATTED_LIST), - ); + note(ui, &tr(keys::editor::format::NOT_FORMATTED_TITLE), &tr(keys::editor::format::NOT_FORMATTED_LIST)); if next != now { actions.push(editor(Editing::Prettier(next))); } @@ -455,11 +389,7 @@ fn note(ui: &mut Ui, title: &str, words: &str) { let p = palette(ui.ctx()); let mut job = egui::text::LayoutJob::default(); let font = egui::FontId::proportional(font::CONTROL); - job.append( - &format!("{title} "), - 0.0, - egui::TextFormat::simple(font.clone(), p.text_1), - ); + job.append(&format!("{title} "), 0.0, egui::TextFormat::simple(font.clone(), p.text_1)); job.append(words, 0.0, egui::TextFormat::simple(font, p.text_2)); ui.add(egui::Label::new(job).wrap()); } diff --git a/crates/ui/src/notes/overlays/editor/format/tests.rs b/crates/ui/src/notes/overlays/editor/format/tests.rs index 8eed1ff8d..37fb9f7cf 100644 --- a/crates/ui/src/notes/overlays/editor/format/tests.rs +++ b/crates/ui/src/notes/overlays/editor/format/tests.rs @@ -15,16 +15,10 @@ const TIDY: &str = "import { inject } from '@angular/core';\nconst host = {{db_h fn snippet(content: &str, language: Language) -> (Harness<'static>, String) { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "invoices").id.clone(); - let patch = NotePatch { - content: Some(content.into()), - language: Some(language), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(content.into()), language: Some(language), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = area(backend, profile); click_id(&mut harness, "note-card-open"); (harness, id) @@ -37,12 +31,10 @@ fn code(harness: &Harness<'_>) -> String { fn stored(harness: &Harness<'_>, id: &str) -> String { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() - .content - .clone() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + .content + .clone() } fn notice(harness: &Harness<'_>) -> Option { @@ -52,9 +44,7 @@ fn notice(harness: &Harness<'_>) -> Option { } fn formatted(harness: &mut Harness<'_>, expected: &str) { - until(harness, "the formatted text in the field", |harness| { - code(harness) == expected - }); + until(harness, "the formatted text in the field", |harness| code(harness) == expected); } #[test] @@ -64,10 +54,7 @@ fn the_button_formats_marks_the_lines_and_its_notice_undoes() { formatted(&mut harness, TIDY); assert_eq!(notice(&harness).as_deref(), Some("formatted")); let view = harness.state().state.notes_view.editor.as_ref().unwrap(); - assert!( - !view.code.as_ref().unwrap().marked.is_empty(), - "lines marked" - ); + assert!(!view.code.as_ref().unwrap().marked.is_empty(), "lines marked"); click_id(&mut harness, "editor-format-undo"); assert_eq!(code(&harness), MESSY); @@ -75,41 +62,26 @@ fn the_button_formats_marks_the_lines_and_its_notice_undoes() { } fn rect(harness: &Harness<'_>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } /// Where the frame painted `words`. fn painted_at(harness: &Harness<'_>, words: &str) -> Option { - harness - .output() - .shapes - .iter() - .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text() == words => { - Some(egui::Rect::from_min_size(text.pos, text.galley.size())) - } - _ => None, - }) + harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == words => { + Some(egui::Rect::from_min_size(text.pos, text.galley.size())) + } + _ => None, + }) } #[test] fn the_button_is_one_piece_with_its_chevron_and_says_its_keys_where_they_fit() { let (mut harness, _) = snippet(MESSY, Language::Ts); - let (main, chevron) = ( - rect(&harness, "editor-format"), - rect(&harness, "editor-format-settings"), - ); - assert!( - (main.right() - chevron.left()).abs() < 0.1, - "{main:?} {chevron:?}" - ); + let (main, chevron) = (rect(&harness, "editor-format"), rect(&harness, "editor-format-settings")); + assert!((main.right() - chevron.left()).abs() < 0.1, "{main:?} {chevron:?}"); assert!((main.height() - chevron.height()).abs() < 0.1); - assert!( - painted_at(&harness, "Shift Alt F").is_none(), - "beside the cards" - ); + assert!(painted_at(&harness, "Shift Alt F").is_none(), "beside the cards"); harness.set_size(egui::vec2(1_700.0, 900.0)); settle(&mut harness); @@ -131,10 +103,7 @@ fn each_switch_of_the_settings_has_its_label_on_its_row() { let switch = rect(&harness, author_id); let label = painted_at(&harness, words).unwrap_or_else(|| panic!("{words} is not painted")); assert!(label.right() < switch.left(), "{words}"); - assert!( - (label.center().y - switch.center().y).abs() < 3.0, - "{words}" - ); + assert!((label.center().y - switch.center().y).abs() < 3.0, "{words}"); } click_id(&mut harness, "prettier-semicolons"); assert!(!harness.state().state.prettier.semicolons); @@ -167,9 +136,7 @@ fn a_syntax_error_is_said_and_nothing_changes() { let broken = "const a = {\n b: 1,,\n}"; let (mut harness, _) = snippet(broken, Language::Ts); click_id(&mut harness, "editor-format"); - until(&mut harness, "the error said", |harness| { - notice(harness).as_deref() == Some("syntax") - }); + until(&mut harness, "the error said", |harness| notice(harness).as_deref() == Some("syntax")); assert_eq!(code(&harness), broken); } @@ -192,14 +159,10 @@ fn the_library_settings_apply_at_once_and_are_kept() { harness.key_press(Key::Escape); settle(&mut harness); click_id(&mut harness, "editor-format"); - until( - &mut harness, - "formatted in the library's style", - |harness| { - code(harness).starts_with("import { inject } from \"@angular/core\";\n") - && code(harness).contains("\n private readonly") - }, - ); + until(&mut harness, "formatted in the library's style", |harness| { + code(harness).starts_with("import { inject } from \"@angular/core\";\n") + && code(harness).contains("\n private readonly") + }); } #[test] @@ -217,7 +180,86 @@ fn a_body_left_is_formatted_on_save_when_the_library_asks() { .type_text("const b=1"); settle(&mut harness); click_id(&mut harness, "editor-close"); - until(&mut harness, "written formatted", |harness| { - stored(harness, &id) == "const b = 1;" - }); + until(&mut harness, "written formatted", |harness| stored(harness, &id) == "const b = 1;"); +} + +#[test] +fn what_is_formatted_already_says_so() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| notice(harness).as_deref() == Some("unchanged")); + assert_eq!(code(&harness), TIDY); +} + +#[test] +fn the_notice_goes_once_typed_over() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| notice(harness).is_some()); + click_id(&mut harness, "editor-body"); + harness.get_by(|node| node.author_id() == Some("editor-body")).type_text("x"); + settle(&mut harness); + + assert_eq!(notice(&harness), None); +} + +#[test] +fn the_notice_goes_by_itself() { + let (mut harness, _) = snippet(TIDY, Language::Ts); + click_id(&mut harness, "editor-format"); + until(&mut harness, "it is said", |harness| notice(harness).is_some()); + for _ in 0..60 { + harness.step(); + } + + assert_eq!(notice(&harness), None); +} + +/// Written so by the core; the field follows rather than writing the older text back. +#[test] +fn the_field_follows_what_was_formatted_on_save() { + let (mut harness, _) = snippet("a", Language::Ts); + click_id(&mut harness, "editor-format-settings"); + click_id(&mut harness, "prettier-formatOnSave"); + harness.key_press(Key::Escape); + settle(&mut harness); + click_id(&mut harness, "editor-body"); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text("const b=1"); + settle(&mut harness); + click_id(&mut harness, "editor-title"); + + formatted(&mut harness, "const b = 1;"); +} + +/// Within what Prettier takes, and what is not a number is not taken. +#[test] +fn a_width_is_taken_once_its_field_is_left() { + for (typed, width) in [("80", 80), ("9999", 200), ("3", 40), ("wide", 100)] { + let (mut harness, _) = snippet("a", Language::Ts); + click_id(&mut harness, "editor-format-settings"); + let before = harness.state().state.prettier.print_width; + click_id(&mut harness, "prettier-width"); + harness.key_press_modifiers(Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("prettier-width")) + .type_text(typed); + settle(&mut harness); + assert_eq!(harness.state().state.prettier.print_width, before, "not yet"); + harness.key_press(Key::Enter); + settle(&mut harness); + assert_eq!(harness.state().state.prettier.print_width, width, "{typed}"); + } +} + +#[test] +fn prettier_s_line_and_column_are_a_place_in_the_text() { + let buffer = text::Buffer::new("ab\ncdé\n"); + for ((line, column), at) in + [((1, 1), 0), ((1, 3), 2), ((2, 2), 4), ((2, 99), 6), ((0, 0), 0), ((99, 1), 7)] + { + assert_eq!(super::offset_of(&buffer, line, column), at, "{line}:{column}"); + } } diff --git a/crates/ui/src/notes/overlays/editor/go_to_line.rs b/crates/ui/src/notes/overlays/editor/go_to_line.rs index fa6bd0214..8d9264e9d 100644 --- a/crates/ui/src/notes/overlays/editor/go_to_line.rs +++ b/crates/ui/src/notes/overlays/editor/go_to_line.rs @@ -59,17 +59,11 @@ pub(super) fn show(ui: &mut Ui, bar: &mut GoToLine, editor: &mut Editor, languag .show(ui, |ui| { ui.spacing_mut().item_spacing = Vec2::new(gap::SNUG, gap::SNUG); ui.horizontal(|ui| { - ui.label( - egui::RichText::new(&label) - .size(font::LABEL) - .color(p.text_1), - ); + ui.label(egui::RichText::new(&label).size(font::LABEL).color(p.text_1)); let field = ui .scope(|ui| { ui.set_width(FIELD_WIDTH); - TextField::new(&mut bar.typed, &label, "go-to-line-input") - .compact() - .show(ui) + TextField::new(&mut bar.typed, &label, "go-to-line-input").compact().show(ui) }) .inner; if std::mem::take(&mut bar.focus) { @@ -78,20 +72,15 @@ pub(super) fn show(ui: &mut Ui, bar: &mut GoToLine, editor: &mut Editor, languag // Taken, or the code that gets the keys back would type it. let entered = field.lost_focus() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Enter)); - let pressed = Button::new(&tr(keys::editor::code::GO), "go-to-line-submit") - .show(ui) - .clicked(); + let pressed = + Button::new(&tr(keys::editor::code::GO), "go-to-line-submit").show(ui).clicked(); if entered || pressed { bar.go(editor); } ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if IconButton::new( - Icon::X, - &tr(keys::editor::search::CLOSE), - "go-to-line-close", - ) - .show(ui) - .clicked() + if IconButton::new(Icon::X, &tr(keys::editor::search::CLOSE), "go-to-line-close") + .show(ui) + .clicked() { bar.close(editor); } @@ -99,8 +88,7 @@ pub(super) fn show(ui: &mut Ui, bar: &mut GoToLine, editor: &mut Editor, languag }); }); let rect = ui.min_rect(); - ui.painter() - .hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); if ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) { bar.close(editor); } diff --git a/crates/ui/src/notes/overlays/editor/header.rs b/crates/ui/src/notes/overlays/editor/header.rs index 7c002acaa..55f84968d 100644 --- a/crates/ui/src/notes/overlays/editor/header.rs +++ b/crates/ui/src/notes/overlays/editor/header.rs @@ -62,14 +62,7 @@ fn context( ) { let p = palette(ui.ctx()); context_field(ui, state, (session, note), editing, 160.0, actions); - ui.label(widgets::text( - ui, - "·", - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - )); + ui.label(widgets::text(ui, "·", font::CONTROL, 400.0, FontFamily::Proportional, p.text_2)); } fn context_field( @@ -117,30 +110,13 @@ fn tags( let width = widgets::Chip::width(ui, &label).min(widest) + cross; widgets::kept_together(ui, width, |ui| { ui.spacing_mut().item_spacing.x = gap::LINE; - widgets::Chip::new(&label, "editor-tag", true) - .widest(widest) - .show(ui); - let remove = i18n::translate( - language, - keys::editor::REMOVE_TAG, - &[("tag", tag.clone().into())], - ); - if IconButton::new(Icon::X, &remove, "editor-tag-remove") - .show(ui) - .clicked() - { - let kept = note - .tags - .iter() - .filter(|kept| *kept != tag) - .cloned() - .collect(); + widgets::Chip::new(&label, "editor-tag", true).widest(widest).show(ui); + let remove = i18n::translate(language, keys::editor::REMOVE_TAG, &[("tag", tag.clone().into())]); + if IconButton::new(Icon::X, &remove, "editor-tag-remove").show(ui).clicked() { + let kept = note.tags.iter().filter(|kept| *kept != tag).cloned().collect(); actions.push(editor(Editing::Save { session, - edit: Edit { - tags: Some(kept), - ..Edit::default() - }, + edit: Edit { tags: Some(kept), ..Edit::default() }, })); } }); @@ -149,6 +125,8 @@ fn tags( let hint = i18n::translate(language, keys::editor::ADD_TAG_PLACEHOLDER, &[]); let response = ui.add( egui::TextEdit::singleline(&mut editing.tag) + // Not its place, which the tag just added moves. + .id_salt("editor-tag-add") .hint_text(hint) .text_color(p.text_1) .font(egui::FontId::new(font::CONTROL, FontFamily::Proportional)) @@ -169,9 +147,7 @@ fn tags( fn lifecycle_words(state: &AppState, note: &DisplayNote) -> String { match note.lifecycle { - NoteLifecycle::Permanent => { - i18n::translate(state.language, keys::lifecycle::NEVER_EXPIRES, &[]) - } + NoteLifecycle::Permanent => i18n::translate(state.language, keys::lifecycle::NEVER_EXPIRES, &[]), NoteLifecycle::Expires { at } => { i18n::time::expiry(at, state.clock.now(), &Local).text(state.language) } @@ -222,21 +198,13 @@ fn lifecycle_badge(ui: &mut Ui, state: &AppState, note: &DisplayNote) { Vec2::splat(11.0), ); crate::theme::icons::paint(ui, glyph, icon, hue); - let at = egui::pos2( - rect.left() + 10.0 + 16.0, - rect.center().y - galley.size().y / 2.0, - ); + let at = egui::pos2(rect.left() + 10.0 + 16.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, hue); widgets::address(ui, &response, "editor-lifecycle"); } /// Emptied, the note is permanent again; a day, and it is due at the end of it, local time. -fn deadline( - ui: &mut Ui, - state: &AppState, - (session, note): (u64, &DisplayNote), - actions: &mut Actions, -) { +fn deadline(ui: &mut Ui, state: &AppState, (session, note): (u64, &DisplayNote), actions: &mut Actions) { let day = match note.lifecycle { NoteLifecycle::Expires { at } => Some(at.with_timezone(&Local).date_naive()), NoteLifecycle::Permanent => None, @@ -247,19 +215,14 @@ fn deadline( .language(state.language) .show(ui); let lifecycle = match picked { - Some(date::Picked::Day(day)) => { - end_of_local_day(day).map(|at| NoteLifecycle::Expires { at }) - } + Some(date::Picked::Day(day)) => end_of_local_day(day).map(|at| NoteLifecycle::Expires { at }), Some(date::Picked::Cleared) => Some(NoteLifecycle::Permanent), None => None, }; if let Some(lifecycle) = lifecycle { actions.push(editor(Editing::Save { session, - edit: Edit { - lifecycle: Some(lifecycle), - ..Edit::default() - }, + edit: Edit { lifecycle: Some(lifecycle), ..Edit::default() }, })); } } @@ -288,14 +251,7 @@ fn placement( ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = Vec2::new(gap::SNUG, gap::SNUG); let label = |ui: &mut Ui, words: &str| { - ui.label(widgets::text( - ui, - words, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - )); + ui.label(widgets::text(ui, words, font::META, 400.0, FontFamily::Proportional, p.text_2)); }; label(ui, &tr(keys::editor::kind::LABEL)); kind_menu(ui, state, (session, note), editing, actions); @@ -319,14 +275,8 @@ fn kind_menu( let tr = |key| i18n::translate(state.language, key, &[]); let current = tr(kind_name(note.kind)); if note.kind == NoteKind::Drawing { - let response = ui.label(widgets::text( - ui, - ¤t, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - )); + let response = + ui.label(widgets::text(ui, ¤t, font::LABEL, 400.0, FontFamily::Proportional, p.text_1)); widgets::address(ui, &response, "editor-kind"); return; } @@ -335,10 +285,7 @@ fn kind_menu( .filter(|kind| *kind != note.kind) .map(|kind| (kind, tr(convert_name(kind)))) .collect(); - let options: Vec<(NoteKind, &str)> = names - .iter() - .map(|(kind, name)| (*kind, name.as_str())) - .collect(); + let options: Vec<(NoteKind, &str)> = names.iter().map(|(kind, name)| (*kind, name.as_str())).collect(); let mut chosen = note.kind; if ChoiceMenu::new(¤t, "editor-kind", &options) .naming(Naming::Label) @@ -346,11 +293,7 @@ fn kind_menu( .changed() && chosen != note.kind { - actions.push(editor(Editing::Convert { - session, - into: chosen, - edit: editing.edit(note), - })); + actions.push(editor(Editing::Convert { session, into: chosen, edit: editing.edit(note) })); } } @@ -365,10 +308,7 @@ pub(super) fn details( ) { let whole = ui.max_rect(); let history = super::revisions::height(state, whole.height() / 2.0); - let sections = Rect::from_min_max( - whole.min, - egui::pos2(whole.right(), whole.bottom() - history), - ); + let sections = Rect::from_min_max(whole.min, egui::pos2(whole.right(), whole.bottom() - history)); let mut sections_ui = ui.new_child(egui::UiBuilder::new().max_rect(sections)); egui::ScrollArea::vertical() .id_salt("editor-details") @@ -436,25 +376,15 @@ fn detail_sections( fn section(ui: &mut Ui, state: &AppState, name: i18n::Key, content: impl FnOnce(&mut Ui)) { let p = palette(ui.ctx()); let words = i18n::translate(state.language, name, &[]).to_uppercase(); - ui.label(widgets::text( - ui, - &words, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - )); + ui.label(widgets::text(ui, &words, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2)); ui.horizontal_wrapped(content); ui.add_space(gap::GROUPS); } fn space_menu(ui: &mut Ui, state: &AppState, note: &DisplayNote, actions: &mut Actions) { let spaces = state.spaces.spaces(); - let options: Vec<(usize, &str)> = spaces - .iter() - .enumerate() - .map(|(at, space)| (at, space.name.as_str())) - .collect(); + let options: Vec<(usize, &str)> = + spaces.iter().enumerate().map(|(at, space)| (at, space.name.as_str())).collect(); let Some(mut chosen) = spaces.iter().position(|space| space.id == note.space_id) else { return; }; @@ -529,26 +459,17 @@ pub(super) fn summary(ui: &mut Ui, state: &AppState, note: &DisplayNote, actions let attached = usize::try_from(note.attachment_count).unwrap_or(usize::MAX); parts.push(count(language, keys::editor::header::ATTACHMENTS, attached)); } - let words = format!( - "{} {}", - tr(keys::editor::header::TITLE), - parts.join(" · ") - ); + let words = format!("{} {}", tr(keys::editor::header::TITLE), parts.join(" · ")); ui.horizontal(|ui| { let (caret, _) = ui.allocate_exact_size(Vec2::splat(12.0), egui::Sense::hover()); crate::theme::icons::paint(ui, caret, Icon::ChevronRight, p.text_2); let unfold = tr(keys::editor::header::UNFOLD); let expires = matches!(note.lifecycle, NoteLifecycle::Expires { .. }); - let badge = if expires { - lifecycle_width(ui, state, note) + ui.spacing().item_spacing.x - } else { - 0.0 - }; + let badge = + if expires { lifecycle_width(ui, state, note) + ui.spacing().item_spacing.x } else { 0.0 }; let room = ui.available_width() - badge - 2.0 * ui.spacing().button_padding.x; let line = widgets::one_line(ui, &words, (font::CONTROL, 400.0), p.text_2, room); - let response = ui - .add(egui::Button::new(line).frame(false)) - .on_hover_text(&unfold); + let response = ui.add(egui::Button::new(line).frame(false)).on_hover_text(&unfold); widgets::address(ui, &response, "editor-header-summary"); if response.clicked() { actions.push(editor(Editing::FoldHeader(false))); diff --git a/crates/ui/src/notes/overlays/editor/json_view.rs b/crates/ui/src/notes/overlays/editor/json_view.rs index a0c224ef2..298666d2c 100644 --- a/crates/ui/src/notes/overlays/editor/json_view.rs +++ b/crates/ui/src/notes/overlays/editor/json_view.rs @@ -43,11 +43,7 @@ pub(crate) struct Layout { impl Default for Layout { fn default() -> Self { - Self { - side_by_side: false, - code_hidden: false, - share: CODE_SHARE, - } + Self { side_by_side: false, code_hidden: false, share: CODE_SHARE } } } @@ -131,22 +127,14 @@ pub(super) fn band( (Tab::Tree, keys::json::tabs::TREE, "editor-view-tree"), ] { let on = exploring.tab == tab; - let response = Button::new(&tr(key), author_id) - .kind(Kind::Quiet) - .armed(on) - .show(ui); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_selected(on)); + let response = Button::new(&tr(key), author_id).kind(Kind::Quiet).armed(on).show(ui); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_selected(on)); if response.clicked() { exploring.tab = tab; } } ui.add_space(gap::GROUPS); - let hint = if fits { - keys::json::side_by_side::HINT - } else { - keys::json::side_by_side::NARROW - }; + let hint = if fits { keys::json::side_by_side::HINT } else { keys::json::side_by_side::NARROW }; let toggle = Button::new(&tr(keys::json::side_by_side::TOGGLE), "editor-side-by-side") .kind(Kind::Quiet) .armed(layout.side_by_side) @@ -159,11 +147,10 @@ pub(super) fn band( } } if layout.side_by_side && fits && exploring.tab != Tab::Code { - let hide = - Button::new(&tr(keys::json::side_by_side::HIDE_CODE), "editor-hide-code") - .kind(Kind::Quiet) - .armed(layout.code_hidden) - .show(ui); + let hide = Button::new(&tr(keys::json::side_by_side::HIDE_CODE), "editor-hide-code") + .kind(Kind::Quiet) + .armed(layout.code_hidden) + .show(ui); if hide.clicked() { layout.code_hidden = !layout.code_hidden; } @@ -191,11 +178,9 @@ fn validity(ui: &mut Ui, view: &JsonView, format: StructureFormat, language: Lan let p = palette(ui.ctx()); let name = json_explorer::format_name(format); let (mark, words, colour) = match &view.error { - None => ( - Icon::Check, - i18n::translate(language, keys::json::VALID, &[("format", name.into())]), - p.green, - ), + None => { + (Icon::Check, i18n::translate(language, keys::json::VALID, &[("format", name.into())]), p.green) + } Some(error) => ( Icon::X, i18n::translate( @@ -234,78 +219,41 @@ pub(super) fn body( let mode = exploring.mode(); let beside = mode.is_some() && layout.side_by_side && fits && !layout.code_hidden; let explored = state.explored.of(session); - let mut shown = Shown { - changed: false, - left: false, - }; + let mut shown = Shown { changed: false, left: false }; match mode { None => { - let drawn = - super::code::show(ui, code, note.language, (state.language, &state.settings)); + let drawn = super::code::show(ui, code, note.language, (state.language, &state.settings)); (shown.changed, shown.left) = (drawn.changed, drawn.left); } Some(mode) if beside => { let split = rect.left() + (rect.width() * layout.share).max(CODE_FLOOR); let split = split.min(rect.right() - EXPLORER_FLOOR); let code_rect = Rect::from_min_max(rect.min, pos2(split - 4.0, rect.bottom())); - let mut code_ui = ui.new_child( - UiBuilder::new() - .id_salt("side-by-side-code") - .max_rect(code_rect), - ); - let pane = widgets::region( - &mut code_ui, - code_rect, - "side-by-side-code", - egui::Sense::hover(), - ); + let mut code_ui = ui.new_child(UiBuilder::new().id_salt("side-by-side-code").max_rect(code_rect)); + let pane = widgets::region(&mut code_ui, code_rect, "side-by-side-code", egui::Sense::hover()); widgets::address(&code_ui, &pane, "side-by-side-code"); let before = code.editor.buffer.selection().head; code.lit = lit_lines(code, explored, &exploring.explorer); - let drawn = super::code::show( - &mut code_ui, - code, - note.language, - (state.language, &state.settings), - ); + let drawn = + super::code::show(&mut code_ui, code, note.language, (state.language, &state.settings)); (shown.changed, shown.left) = (drawn.changed, drawn.left); if code.editor.buffer.selection().head != before && !drawn.changed { caret_moved(exploring, code, explored); } - let handle_rect = Rect::from_min_max( - pos2(split - 4.0, rect.top()), - pos2(split + 4.0, rect.bottom()), - ); - let mut handle_ui = ui.new_child( - UiBuilder::new() - .id_salt("side-by-side-handle") - .max_rect(handle_rect), - ); + let handle_rect = + Rect::from_min_max(pos2(split - 4.0, rect.top()), pos2(split + 4.0, rect.bottom())); + let mut handle_ui = + ui.new_child(UiBuilder::new().id_salt("side-by-side-handle").max_rect(handle_rect)); let moved = widgets::split_handle(&mut handle_ui, "side-by-side-handle"); if moved != 0.0 { layout.share = ((split + moved - rect.left()) / rect.width()).clamp(0.1, 0.9); } let explorer_rect = Rect::from_min_max(pos2(split + 4.0, rect.top()), rect.max); - let mut explorer_ui = ui.new_child( - UiBuilder::new() - .id_salt("side-by-side") - .max_rect(explorer_rect), - ); - let pane = widgets::region( - &mut explorer_ui, - explorer_rect, - "side-by-side", - egui::Sense::hover(), - ); + let mut explorer_ui = + ui.new_child(UiBuilder::new().id_salt("side-by-side").max_rect(explorer_rect)); + let pane = widgets::region(&mut explorer_ui, explorer_rect, "side-by-side", egui::Sense::hover()); widgets::address(&explorer_ui, &pane, "side-by-side"); - explore( - &mut explorer_ui, - state, - exploring, - code, - explored, - (mode, true), - ); + explore(&mut explorer_ui, state, exploring, code, explored, (mode, true)); } Some(mode) => { code.lit = 0..0; @@ -328,13 +276,10 @@ fn ask(ui: &Ui, session: u64, exploring: &mut Exploring, code: &CodeView, action exploring.due = None; exploring.text = code.text(); } else { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(due - now)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(due - now)); } } - let query = exploring - .explorer - .query(exploring.text.clone(), exploring.format); + let query = exploring.explorer.query(exploring.text.clone(), exploring.format); if exploring.asked.as_ref() != Some(&query) { exploring.asked = Some(query.clone()); actions.push(super::editor(Editing::Explore { session, query })); @@ -387,11 +332,7 @@ fn chars(code: &CodeView, span: Span) -> Range { } /// The lines of the explorer's selection, lit in the code beside it. -fn lit_lines( - code: &CodeView, - answer: Option<(&JsonView, &str)>, - explorer: &Explorer, -) -> Range { +fn lit_lines(code: &CodeView, answer: Option<(&JsonView, &str)>, explorer: &Explorer) -> Range { let Some((view, _)) = answer else { return 0..0; }; diff --git a/crates/ui/src/notes/overlays/editor/json_view/tests.rs b/crates/ui/src/notes/overlays/editor/json_view/tests.rs index d670ce0b3..8c07c2b04 100644 --- a/crates/ui/src/notes/overlays/editor/json_view/tests.rs +++ b/crates/ui/src/notes/overlays/editor/json_view/tests.rs @@ -24,20 +24,12 @@ const EVENT: &str = r#"{ fn snippet(content: &str, language: Language) -> Harness<'static> { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "webhook").id.clone(); - let patch = NotePatch { - content: Some(content.into()), - language: Some(language), - ..NotePatch::default() - }; - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &id, &patch) - }) - .unwrap(); + let patch = NotePatch { content: Some(content.into()), language: Some(language), ..NotePatch::default() }; + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &id, &patch)) + .unwrap(); let mut harness = expanded_area(backend, profile); click_id(&mut harness, "note-card-open"); - until(&mut harness, "the draft explored", |harness| { - has(harness, "editor-json-validity") - }); + until(&mut harness, "the draft explored", |harness| has(harness, "editor-json-validity")); harness } @@ -46,17 +38,13 @@ fn has(harness: &Harness<'_>, author_id: &str) -> bool { } fn count(harness: &Harness<'_>, author_id: &str) -> usize { - harness - .query_all_by(|node| node.author_id() == Some(author_id)) - .count() + harness.query_all_by(|node| node.author_id() == Some(author_id)).count() } /// The entry of the graph or the tree written at `path`. fn click_at(harness: &mut Harness<'_>, author_id: &str, path: &str) { harness - .get_by(|node| { - node.author_id() == Some(author_id) && node.description().as_deref() == Some(path) - }) + .get_by(|node| node.author_id() == Some(author_id) && node.description().as_deref() == Some(path)) .click(); settle(harness); } @@ -84,9 +72,7 @@ fn press(harness: &mut Harness<'_>, modifiers: Modifiers, key: Key) { fn graph(harness: &mut Harness<'_>) { click_id(harness, "editor-view-graph"); - until(harness, "the nodes drawn", |harness| { - has(harness, "json-node-head") - }); + until(harness, "the nodes drawn", |harness| has(harness, "json-node-head")); } #[test] @@ -113,13 +99,9 @@ fn a_row_closes_and_opens_its_container_one_level() { let mut harness = snippet(EVENT, Language::Json); graph(&mut harness); click_at(&mut harness, "json-row", "$.data.object.lines"); - until(&mut harness, "the lines closed", |harness| { - count(harness, "json-node-head") == 3 - }); + until(&mut harness, "the lines closed", |harness| count(harness, "json-node-head") == 3); click_at(&mut harness, "json-row", "$.data.object.lines"); - until(&mut harness, "the lines open again", |harness| { - count(harness, "json-node-head") == 4 - }); + until(&mut harness, "the lines open again", |harness| count(harness, "json-node-head") == 4); } #[test] @@ -129,26 +111,18 @@ fn folded_to_the_root_the_selection_falls_back_then_comes_back() { click_id(&mut harness, "json-fit"); click_at(&mut harness, "json-node-head", "$.data.object"); click_id(&mut harness, "json-collapse-all"); - until(&mut harness, "the root alone", |harness| { - count(harness, "json-node-head") == 1 - }); + until(&mut harness, "the root alone", |harness| count(harness, "json-node-head") == 1); assert_eq!(selected(&harness), "$.data"); click_id(&mut harness, "json-open-all"); - until(&mut harness, "every node again", |harness| { - count(harness, "json-node-head") == 5 - }); + until(&mut harness, "every node again", |harness| count(harness, "json-node-head") == 5); assert_eq!(selected(&harness), "$.data.object"); click_at(&mut harness, "json-node-head", "$"); press(&mut harness, Modifiers::SHIFT, Key::ArrowLeft); - until(&mut harness, "the root alone, from the keys", |harness| { - count(harness, "json-node-head") == 1 - }); + until(&mut harness, "the root alone, from the keys", |harness| count(harness, "json-node-head") == 1); press(&mut harness, Modifiers::SHIFT, Key::ArrowRight); - until(&mut harness, "every node, from the keys", |harness| { - count(harness, "json-node-head") == 5 - }); + until(&mut harness, "every node, from the keys", |harness| count(harness, "json-node-head") == 5); } #[test] @@ -158,8 +132,7 @@ fn a_node_moved_with_alt_and_an_arrow_is_put_back_by_the_reset() { let top = |harness: &Harness<'_>| { harness .get_by(|node| { - node.author_id() == Some("json-node-head") - && node.description().as_deref() == Some("$.data") + node.author_id() == Some("json-node-head") && node.description().as_deref() == Some("$.data") }) .rect() .top() @@ -177,9 +150,7 @@ fn a_node_moved_with_alt_and_an_arrow_is_put_back_by_the_reset() { fn a_match_found_is_stepped_to_and_shown_in_the_code() { let mut harness = snippet(EVENT, Language::Json); graph(&mut harness); - harness - .get_by(|node| node.author_id() == Some("json-search")) - .focus(); + harness.get_by(|node| node.author_id() == Some("json-search")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("json-search")) @@ -201,14 +172,10 @@ fn a_match_found_is_stepped_to_and_shown_in_the_code() { fn the_tree_folds_a_container_clicked() { let mut harness = snippet(EVENT, Language::Json); click_id(&mut harness, "editor-view-tree"); - until(&mut harness, "the lines drawn", |harness| { - has(harness, "json-line") - }); + until(&mut harness, "the lines drawn", |harness| has(harness, "json-line")); let lines = count(&harness, "json-line"); click_at(&mut harness, "json-line", "$.data"); - until(&mut harness, "the tree folded", |harness| { - count(harness, "json-line") < lines - }); + until(&mut harness, "the tree folded", |harness| count(harness, "json-line") < lines); } #[test] @@ -249,9 +216,7 @@ fn a_broken_draft_says_where_it_breaks() { .is_some() }); click_id(&mut harness, "editor-view-graph"); - until(&mut harness, "the place said", |harness| { - has(harness, "json-invalid") - }); + until(&mut harness, "the place said", |harness| has(harness, "json-invalid")); click_id(&mut harness, "json-error-show"); assert!(has(&harness, "editor-body")); } @@ -271,3 +236,90 @@ fn a_yaml_snippet_is_explored_and_plain_text_is_not() { }; assert!(!has(&harness, "editor-view-graph")); } + +#[test] +fn another_language_is_another_reader_or_none() { + let mut harness = snippet(EVENT, Language::Json); + graph(&mut harness); + let pick = |harness: &mut Harness<'_>, language: Language| { + let edit = crate::state::editor::Edit { language: Some(language), ..Default::default() }; + let session = harness.state().state.editor.opened().unwrap().session; + let bench = harness.state_mut(); + let save = crate::notes::Action::Editor(crate::notes::Editing::Save { session, edit }); + bench + .state + .apply(crate::action::Action::Notes(save), &egui::Context::default(), &bench.backend); + settle(harness); + }; + pick(&mut harness, Language::Yml); + assert!(has(&harness, "editor-view-graph")); + assert!(!has(&harness, "json-node-head"), "back to the code"); + pick(&mut harness, Language::Sh); + assert!(!has(&harness, "editor-view-graph")); +} + +/// The code keeps its floor; what is left is said to be too little. +#[test] +fn too_narrow_for_both_it_says_so_and_shows_one_at_a_time() { + let mut harness = snippet(EVENT, Language::Json); + click_id(&mut harness, "editor-side-by-side"); + until(&mut harness, "side by side", |harness| has(harness, "side-by-side")); + harness.set_size(egui::vec2(760.0, 800.0)); + settle(&mut harness); + + assert!(has(&harness, "editor-side-by-side-narrow")); + assert!(!has(&harness, "side-by-side")); + let toggle = harness.get_by(|node| node.author_id() == Some("editor-side-by-side")); + assert!(toggle.accesskit_node().is_disabled()); +} + +#[test] +fn the_line_between_the_code_and_the_explorer_moves() { + let mut harness = snippet(EVENT, Language::Json); + click_id(&mut harness, "editor-side-by-side"); + until(&mut harness, "side by side", |harness| has(harness, "side-by-side")); + let left = |harness: &Harness<'_>| { + harness + .get_by(|node| node.author_id() == Some("side-by-side-handle")) + .rect() + .left() + }; + let before = left(&harness); + harness.get_by(|node| node.author_id() == Some("side-by-side-handle")).focus(); + settle(&mut harness); + press(&mut harness, Modifiers::NONE, Key::ArrowRight); + press(&mut harness, Modifiers::NONE, Key::ArrowRight); + + assert!((left(&harness) - before - 32.0).abs() < 1.0, "{before} {}", left(&harness)); +} + +#[test] +fn the_tree_it_proposes_is_the_one_it_shows() { + let objects = vec![r#"{"a":1}"#; 200].join(","); + let arrays: Vec = (0..11).map(|n| format!(r#""k{n}":[{objects}]"#)).collect(); + let mut harness = snippet(&format!("{{{}}}", arrays.join(",")), Language::Json); + graph(&mut harness); + click_id(&mut harness, "json-open-all"); + until(&mut harness, "it is folded", |harness| has(harness, "json-show-tree")); + click_id(&mut harness, "json-show-tree"); + + assert!(has(&harness, "json-tree")); +} + +/// Explored a moment after the typing, not at each key. +#[test] +fn what_is_typed_is_explored_once_the_keys_rest() { + let mut harness = snippet(r#"{"a":1}"#, Language::Json); + click_id(&mut harness, "editor-body"); + press(&mut harness, Modifiers::COMMAND, Key::A); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text(r#"{"a":1,"#); + until(&mut harness, "the draft refused", |harness| { + said(harness, "editor-json-validity").contains("line") + }); + harness + .get_by(|node| node.author_id() == Some("editor-body")) + .type_text(r#""b":2}"#); + until(&mut harness, "the draft read", |harness| !said(harness, "editor-json-validity").contains("line")); +} diff --git a/crates/ui/src/notes/overlays/editor/mod.rs b/crates/ui/src/notes/overlays/editor/mod.rs index 645c56a1f..fb9e3b435 100644 --- a/crates/ui/src/notes/overlays/editor/mod.rs +++ b/crates/ui/src/notes/overlays/editor/mod.rs @@ -81,13 +81,11 @@ impl EditorView { source: note.source.clone(), body: body::text_of(note), checklist: checklist::ChecklistView::of(¬e.items), - code: (note.kind == NoteKind::Snippet) - .then(|| code::CodeView::of(¬e.content, note.language)), + code: (note.kind == NoteKind::Snippet).then(|| code::CodeView::of(¬e.content, note.language)), exploring: json_view::Exploring::of(note), rich: (note.kind == NoteKind::Note).then(|| rich::RichEditor::of(¬e.content)), sheet: (note.kind == NoteKind::Calc).then(|| calc::CalcView::of(¬e.content)), - drawing: (note.kind == NoteKind::Drawing) - .then(|| drawing::DrawingView::open(¬e.content)), + drawing: (note.kind == NoteKind::Drawing).then(|| drawing::DrawingView::open(¬e.content)), fields: fields::FieldsView::of(note), format: format::FormatView::default(), removing: None, @@ -171,14 +169,7 @@ pub(crate) fn show( .layout(Layout::top_down(Align::Min)), ); panel_ui.set_clip_rect(room.intersect(ui.clip_rect())); - let closed = panel( - &mut panel_ui, - state, - (open.session, note), - editing, - layout, - actions, - ); + let closed = panel(&mut panel_ui, state, (open.session, note), editing, layout, actions); // After the panel: what in it answers Escape (a search bar, a drawing's tool) took it. let escaped = !overlaid && !typing @@ -202,8 +193,7 @@ pub(crate) fn show( fn empty_panel(ui: &Ui, room: Rect) { let p = palette(ui.ctx()); ui.painter().rect_filled(room, CornerRadius::ZERO, p.bg_1); - ui.painter() - .vline(room.left(), room.y_range(), Stroke::new(1.0, p.line)); + ui.painter().vline(room.left(), room.y_range(), Stroke::new(1.0, p.line)); } /// The editor's column: toolbar, header, body, footer. `true` once the close button is clicked. @@ -242,19 +232,11 @@ fn panel( egui::pos2(whole.left(), ui.cursor().top()), egui::pos2(whole.right(), whole.bottom() - footer_height - history), ); - let mut body_ui = - ui.new_child(UiBuilder::new().max_rect(body_rect.shrink2(Vec2::new(20.0, 14.0)))); + let mut body_ui = ui.new_child(UiBuilder::new().max_rect(body_rect.shrink2(Vec2::new(20.0, 14.0)))); // In a small window the bands leave it little: what does not fit stops at its edge. body_ui.set_clip_rect(body_ui.clip_rect().intersect(body_rect)); let previewing = editing.fields.previewing; - let left = body( - &mut body_ui, - state, - (session, note), - (editing, layout), - previewing, - actions, - ); + let left = body(&mut body_ui, state, (session, note), (editing, layout), previewing, actions); if left { save(session, note, editing, actions); } @@ -329,9 +311,7 @@ fn body( } else if note.kind == NoteKind::Checklist { egui::ScrollArea::vertical() .auto_shrink(false) - .show(ui, |ui| { - checklist::show(ui, &mut editing.checklist, state.language, expanded) - }) + .show(ui, |ui| checklist::show(ui, &mut editing.checklist, state.language, expanded)) .inner } else { body::show(ui, state, note, &mut editing.body) @@ -369,8 +349,7 @@ fn under_body( let mut history_ui = ui.new_child(UiBuilder::new().max_rect(history_rect)); revisions::show(&mut history_ui, state, actions); } - let footer_rect = - Rect::from_min_max(egui::pos2(whole.left(), history_rect.bottom()), whole.max); + let footer_rect = Rect::from_min_max(egui::pos2(whole.left(), history_rect.bottom()), whole.max); let mut footer_ui = ui.new_child(UiBuilder::new().max_rect(footer_rect)); footer(&mut footer_ui, state, note, editing); } @@ -392,10 +371,7 @@ fn rich_body( actions.push(editor(Editing::Convert { session, into: NoteKind::Snippet, - edit: Edit { - body: Some(Body::Content(code)), - ..Edit::default() - }, + edit: Edit { body: Some(Body::Content(code)), ..Edit::default() }, })); } // Written only on a frame that changed it: the whole Note, a few ms past a few thousand lines. @@ -411,12 +387,7 @@ fn rich_body( } /// A strip of the editor, a soft line under it. -pub(super) fn band( - ui: &mut Ui, - margin: Margin, - ruled: bool, - content: impl FnOnce(&mut Ui) -> R, -) -> R { +pub(super) fn band(ui: &mut Ui, margin: Margin, ruled: bool, content: impl FnOnce(&mut Ui) -> R) -> R { let p = palette(ui.ctx()); let shown = egui::Frame::new().inner_margin(margin).show(ui, |ui| { ui.set_width(ui.available_width()); @@ -424,8 +395,7 @@ pub(super) fn band( }); if ruled { let rect = shown.response.rect; - ui.painter() - .hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); } shown.inner } @@ -514,10 +484,7 @@ fn compact_toolbar( fn close_button(ui: &mut Ui, state: &AppState) -> bool { let close = i18n::translate(state.language, keys::editor::CLOSE, &[]); let keys = i18n::translate(state.language, keys::editor::CLOSE_KEYS, &[]); - IconButton::new(Icon::X, &close, "editor-close") - .keys(&keys) - .show(ui) - .clicked() + IconButton::new(Icon::X, &close, "editor-close").keys(&keys).show(ui).clicked() } fn expand_button(ui: &mut Ui, state: &AppState, actions: &mut Actions) { @@ -560,9 +527,7 @@ fn fold_button( .show(ui) .clicked() } else { - IconButton::new(icon, &words, "editor-fold-header") - .show(ui) - .clicked() + IconButton::new(icon, &words, "editor-fold-header").show(ui).clicked() }; if clicked { if !folded { @@ -616,10 +581,7 @@ fn title( .margin(Margin::ZERO) .hint_text(untitled) .text_color(p.text_0) - .font(egui::FontId::new( - font::HEADING, - egui::FontFamily::Proportional, - )) + .font(egui::FontId::new(font::HEADING, egui::FontFamily::Proportional)) .desired_width(ui.available_width().max(120.0)), ); ui.ctx() @@ -634,13 +596,7 @@ fn title( } /// The Note full screen, a section a slide: what is on screen, not what is stored. -fn present( - ui: &mut Ui, - state: &AppState, - editing: &EditorView, - labelled: bool, - actions: &mut Actions, -) { +fn present(ui: &mut Ui, state: &AppState, editing: &EditorView, labelled: bool, actions: &mut Actions) { let words = i18n::translate(state.language, keys::editor::PRESENT, &[]); let hint = i18n::translate(state.language, keys::editor::PRESENT_LABEL, &[]); let clicked = if labelled { @@ -651,37 +607,19 @@ fn present( } else { IconButton::new(Icon::Play, &words, "editor-present").show(ui) }; - let clicked = if labelled { - widgets::tooltip(clicked, &hint) - } else { - clicked - }; + let clicked = if labelled { widgets::tooltip(clicked, &hint) } else { clicked }; if clicked.clicked() { - actions.push(editor(Editing::Present { - title: editing.title.clone(), - markdown: editing.body.clone(), - })); + actions + .push(editor(Editing::Present { title: editing.title.clone(), markdown: editing.body.clone() })); } } fn pin(ui: &mut Ui, state: &AppState, note: &DisplayNote, labelled: bool, actions: &mut Actions) { - let key = if note.pinned { - keys::editor::PINNED - } else { - keys::editor::PIN - }; + let key = if note.pinned { keys::editor::PINNED } else { keys::editor::PIN }; let words = i18n::translate(state.language, key, &[]); let clicked = if labelled { - let kind = if note.pinned { - Kind::Filled - } else { - Kind::Outline - }; - Button::new(&words, "editor-pin") - .kind(kind) - .icon(Icon::Pin) - .show(ui) - .clicked() + let kind = if note.pinned { Kind::Filled } else { Kind::Outline }; + Button::new(&words, "editor-pin").kind(kind).icon(Icon::Pin).show(ui).clicked() } else { IconButton::new(Icon::Pin, &words, "editor-pin") .pressed(note.pinned) @@ -708,10 +646,7 @@ fn priority(ui: &mut Ui, state: &AppState, note: &DisplayNote, actions: &mut Act (level, name) }) .collect(); - let options: Vec<(Priority, &str)> = names - .iter() - .map(|(level, name)| (*level, name.as_str())) - .collect(); + let options: Vec<(Priority, &str)> = names.iter().map(|(level, name)| (*level, name.as_str())).collect(); let mut chosen = note.priority; let label = tr(keys::notes::PRIORITY_LABEL); if ChoiceMenu::new(&label, "editor-priority", &options) @@ -728,10 +663,7 @@ fn language_menu(ui: &mut Ui, state: &AppState, note: &DisplayNote, actions: &mu .into_iter() .map(|language| (language, crate::notes::language::label(language))) .collect(); - let hints: Vec<&str> = Language::ALL - .into_iter() - .map(crate::notes::language::hint) - .collect(); + let hints: Vec<&str> = Language::ALL.into_iter().map(crate::notes::language::hint).collect(); let mut chosen = note.language; let label = i18n::translate(state.language, keys::editor::LANGUAGE_LABEL, &[]); if ChoiceMenu::new(&label, "editor-language", &options) @@ -742,10 +674,7 @@ fn language_menu(ui: &mut Ui, state: &AppState, note: &DisplayNote, actions: &mu { actions.push(editor(Editing::Save { session: state.editor.opened().map_or(0, |open| open.session), - edit: Edit { - language: Some(chosen), - ..Edit::default() - }, + edit: Edit { language: Some(chosen), ..Edit::default() }, })); } } @@ -784,19 +713,9 @@ fn copy( } } -fn delete( - ui: &mut Ui, - state: &AppState, - editing: &mut EditorView, - labelled: bool, - actions: &mut Actions, -) { +fn delete(ui: &mut Ui, state: &AppState, editing: &mut EditorView, labelled: bool, actions: &mut Actions) { let confirming = editing.confirming_delete; - let key = if confirming { - keys::editor::DELETE_CONFIRM - } else { - keys::editor::DELETE - }; + let key = if confirming { keys::editor::DELETE_CONFIRM } else { keys::editor::DELETE }; let words = i18n::translate(state.language, key, &[]); let clicked = if labelled || confirming { Button::new(&words, "editor-delete") @@ -824,50 +743,23 @@ fn delete( fn footer(ui: &mut Ui, state: &AppState, note: &DisplayNote, editing: &EditorView) { let p = palette(ui.ctx()); let rect = ui.max_rect(); - ui.painter() - .hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); let language = state.language; - let shapes = editing - .drawing - .as_ref() - .map_or(0, drawing::DrawingView::shapes); - let counted = body::stats( - note, - &editing.body, - &editing.checklist.items, - shapes, - language, - ); + let shapes = editing.drawing.as_ref().map_or(0, drawing::DrawingView::shapes); + let counted = body::stats(note, &editing.body, &editing.checklist.items, shapes, language); let modified = (!note.id.is_empty()).then(|| { let (said, _) = crate::services::time::relative(note.updated_at, state.clock.as_ref()); - format!( - "{} {}", - i18n::translate(language, keys::editor::MODIFIED_PREFIX, &[]), - said.text(language) - ) + format!("{} {}", i18n::translate(language, keys::editor::MODIFIED_PREFIX, &[]), said.text(language)) }); let mut inner = ui.new_child(UiBuilder::new().max_rect(rect.shrink2(Vec2::new(20.0, 0.0)))); inner.horizontal_centered(|ui| { - let galley = widgets::text( - ui, - &counted, - font::META, - 400.0, - egui::FontFamily::Monospace, - p.text_2, - ); + let galley = widgets::text(ui, &counted, font::META, 400.0, egui::FontFamily::Monospace, p.text_2); let response = ui.label(galley); widgets::address(ui, &response, "editor-stats"); if let Some(modified) = modified { ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let galley = widgets::text( - ui, - &modified, - font::META, - 400.0, - egui::FontFamily::Monospace, - p.text_2, - ); + let galley = + widgets::text(ui, &modified, font::META, 400.0, egui::FontFamily::Monospace, p.text_2); ui.label(galley); }); } @@ -876,10 +768,7 @@ fn footer(ui: &mut Ui, state: &AppState, note: &DisplayNote, editing: &EditorVie /// The fields as they are, written: on blur, before a copy, a fold or a conversion. pub(super) fn save(session: u64, note: &DisplayNote, editing: &EditorView, actions: &mut Actions) { - actions.push(editor(Editing::Save { - session, - edit: editing.edit(note), - })); + actions.push(editor(Editing::Save { session, edit: editing.edit(note) })); } /// ⚠️ The one closing path, and it writes the drafts first: Escape, the backdrop and the close @@ -895,12 +784,7 @@ fn close(session: u64, note: &DisplayNote, editing: &mut EditorView, actions: &m fn arrivals(ui: &Ui, actions: &mut Actions) { use crate::state::attachments::Asked; let (dropped, pasted) = ui.input(|input| { - let dropped: Vec<_> = input - .raw - .dropped_files - .iter() - .map(|file| file.path().to_path_buf()) - .collect(); + let dropped: Vec<_> = input.raw.dropped_files.iter().map(|file| file.path().to_path_buf()).collect(); let pasted: Vec<_> = input .events .iter() @@ -934,13 +818,7 @@ fn pictures(ui: &Ui, session: u64, editing: &mut EditorView, actions: &mut Actio /// A drawing that came by import has its scene and no picture: it takes them on being left, /// and no date moves. -fn missing_pictures( - ui: &Ui, - session: u64, - note: &DisplayNote, - editing: &EditorView, - actions: &mut Actions, -) { +fn missing_pictures(ui: &Ui, session: u64, note: &DisplayNote, editing: &EditorView, actions: &mut Actions) { let drawn = editing.drawing.as_ref(); let content = drawn.and_then(drawing::DrawingView::content_if_drawn); if let Some(content) = content.filter(|_| !note.id.is_empty()) { diff --git a/crates/ui/src/notes/overlays/editor/revisions.rs b/crates/ui/src/notes/overlays/editor/revisions.rs index da43ff7b7..52e1e113d 100644 --- a/crates/ui/src/notes/overlays/editor/revisions.rs +++ b/crates/ui/src/notes/overlays/editor/revisions.rs @@ -48,8 +48,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { } let p = palette(ui.ctx()); let rect = ui.max_rect(); - ui.painter() - .hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); egui::Frame::new() .inner_margin(gap::margin(gap::PANEL, gap::SNUG)) .show(ui, |ui| { @@ -70,20 +69,9 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { fn toggle(ui: &mut Ui, state: &AppState, count: usize, actions: &mut Actions) { let p = palette(ui.ctx()); let count = u32::try_from(count).unwrap_or(u32::MAX); - let words = i18n::translate( - state.language, - keys::revisions::TITLE, - &[("count", count.into())], - ); + let words = i18n::translate(state.language, keys::revisions::TITLE, &[("count", count.into())]); let open = state.revisions.is_open(); - let galley = widgets::text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, &words, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); let response = widgets::interact( ui, Vec2::new(galley.size().x + 22.0, 22.0), @@ -96,17 +84,10 @@ fn toggle(ui: &mut Ui, state: &AppState, count: usize, actions: &mut Actions) { egui::pos2(response.rect.left() + 7.0, response.rect.center().y), Vec2::splat(11.0), ); - let icon = if open { - Icon::ArrowDown - } else { - Icon::ChevronRight - }; + let icon = if open { Icon::ArrowDown } else { Icon::ChevronRight }; icons::paint(ui, chevron, icon, p.text_2); ui.painter().galley( - egui::pos2( - response.rect.left() + 18.0, - response.rect.center().y - galley.size().y / 2.0, - ), + egui::pos2(response.rect.left() + 18.0, response.rect.center().y - galley.size().y / 2.0), galley, p.text_1, ); @@ -121,27 +102,15 @@ fn list(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let language = state.language; for kept in state.revisions.kept() { let (when, _) = crate::services::time::relative(kept.taken_at, state.clock.as_ref()); - let size = i18n::translate( - language, - keys::revisions::CHARACTERS, - &[("count", kept.characters.into())], - ); + let size = + i18n::translate(language, keys::revisions::CHARACTERS, &[("count", kept.characters.into())]); let look = i18n::translate(language, keys::revisions::LOOK, &[]); let words = format!("{} · {size}", when.text(language)); ui.horizontal(|ui| { - let row = widgets::text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let row = widgets::text(ui, &words, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); ui.label(row); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let response = Button::new(&look, "revision-open") - .kind(Kind::Quiet) - .show(ui); + let response = Button::new(&look, "revision-open").kind(Kind::Quiet).show(ui); if response.clicked() { actions.push(editor(Editing::Revisions(Revisions::Look(kept.id.clone())))); } @@ -161,19 +130,8 @@ fn preview_of(ui: &mut Ui, state: &AppState, preview: &Preview, actions: &mut Ac let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let (when, _) = crate::services::time::relative(preview.kept.taken_at, state.clock.as_ref()); - let head = format!( - "{} {}", - tr(keys::revisions::PREVIEW_OF), - when.text(language) - ); - ui.label(widgets::text( - ui, - &head, - font::LABEL, - 600.0, - FontFamily::Proportional, - p.text_0, - )); + let head = format!("{} {}", tr(keys::revisions::PREVIEW_OF), when.text(language)); + ui.label(widgets::text(ui, &head, font::LABEL, 600.0, FontFamily::Proportional, p.text_0)); if preview.lines.is_empty() { let same = ui.label(widgets::text( ui, @@ -188,19 +146,9 @@ fn preview_of(ui: &mut Ui, state: &AppState, preview: &Preview, actions: &mut Ac diff(ui, &preview.lines, language); } let newer = u32::try_from(preview.newer).unwrap_or(u32::MAX); - let warning = i18n::translate( - language, - keys::revisions::CONSEQUENCE, - &[("count", newer.into())], - ); - let note = ui.label(widgets::text( - ui, - &warning, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.amber_text, - )); + let warning = i18n::translate(language, keys::revisions::CONSEQUENCE, &[("count", newer.into())]); + let note = + ui.label(widgets::text(ui, &warning, font::CONTROL, 400.0, FontFamily::Proportional, p.amber_text)); address(ui, ¬e, "revision-consequence"); ui.horizontal(|ui| { if Button::new(&tr(keys::revisions::BACK), "revision-back") @@ -236,24 +184,14 @@ fn diff(ui: &mut Ui, lines: &[DiffLine], language: Language) { DiffLine::Dropped { text } => ("−", text.clone(), p.red, "diff-dropped"), DiffLine::Skipped { count } => ( " ", - i18n::translate( - language, - keys::revisions::SKIPPED, - &[("count", (*count).into())], - ), + i18n::translate(language, keys::revisions::SKIPPED, &[("count", (*count).into())]), p.text_2, "diff-skipped", ), }; let words = format!("{sign} {text}"); - let shown = ui.label(widgets::text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Monospace, - ink, - )); + let shown = + ui.label(widgets::text(ui, &words, font::LABEL, 400.0, FontFamily::Monospace, ink)); address(ui, &shown, author_id); } }) diff --git a/crates/ui/src/notes/overlays/editor/revisions/tests.rs b/crates/ui/src/notes/overlays/editor/revisions/tests.rs index 641807047..7de67d9a9 100644 --- a/crates/ui/src/notes/overlays/editor/revisions/tests.rs +++ b/crates/ui/src/notes/overlays/editor/revisions/tests.rs @@ -8,25 +8,18 @@ type Harness = egui_kittest::Harness<'static, Bench>; fn stored(harness: &Harness, id: &str) -> DisplayNote { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() } /// A snippet whose body was edited once, so one body is kept: « SELECT 1; ». fn edited() -> (Harness, String) { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "psql").id.clone(); - let patch = NotePatch { - content: Some("SELECT 2;\nSELECT 3;".into()), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some("SELECT 2;\nSELECT 3;".into()), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = expanded_area(backend, profile); click_id(&mut harness, "note-card-open"); (harness, id) @@ -42,22 +35,12 @@ fn body(harness: &Harness) -> String { #[test] fn the_history_lists_the_body_kept_and_previews_what_would_change() { let (mut harness, _) = edited(); - assert!( - harness - .query_by(|node| node.author_id() == Some("revision-open")) - .is_none(), - "folded at first" - ); + assert!(harness.query_by(|node| node.author_id() == Some("revision-open")).is_none(), "folded at first"); click_id(&mut harness, "revisions-toggle"); click_id(&mut harness, "revision-open"); harness.get_by(|node| node.author_id() == Some("diff-restored")); - assert_eq!( - harness - .query_all_by(|node| node.author_id() == Some("diff-dropped")) - .count(), - 2 - ); + assert_eq!(harness.query_all_by(|node| node.author_id() == Some("diff-dropped")).count(), 2); harness.get_by(|node| node.author_id() == Some("revision-consequence")); click_id(&mut harness, "revision-back"); harness.get_by(|node| node.author_id() == Some("revision-open")); @@ -73,17 +56,9 @@ fn going_back_puts_the_body_back_in_the_editor_and_leaves_the_date() { assert_eq!(stored(&harness, &id).content, "SELECT 1;"); assert_eq!(stored(&harness, &id).updated_at, before); - assert_eq!( - body(&harness), - "SELECT 1;", - "the editor shows the body put back" - ); + assert_eq!(body(&harness), "SELECT 1;", "the editor shows the body put back"); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id).content, - "SELECT 1;", - "the close writes nothing older" - ); + assert_eq!(stored(&harness, &id).content, "SELECT 1;", "the close writes nothing older"); } #[test] @@ -93,9 +68,83 @@ fn a_new_note_and_a_todo_list_offer_no_history() { let mut harness = expanded_area(backend, profile); click_id(&mut harness, "new-note"); settle(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("revisions-toggle")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("revisions-toggle")).is_none()); +} + +/// A snippet whose body was each of `bodies` in turn, its history open. +fn rewritten(bodies: &[String]) -> Harness { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let bodies = bodies.to_vec(); + engine::db::run_here(backend.engine(), move |engine| { + for body in bodies { + let patch = NotePatch { content: Some(body), ..NotePatch::default() }; + engine::notes::update_note(engine, &id, &patch)?; + } + Ok::<_, engine::error::AppError>(()) + }) + .unwrap(); + let mut harness = expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + click_id(&mut harness, "revisions-toggle"); + harness +} + +fn look(harness: &mut Harness, rank: usize) { + harness + .query_all_by(|node| node.author_id() == Some("revision-open")) + .nth(rank) + .unwrap() + .click(); + settle(harness); +} + +fn shown(harness: &Harness, author_id: &str) -> Vec { + use egui_kittest::kittest::NodeT; + + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .map(|node| { + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() + }) + .collect() +} + +/// The newest kept first; the one before the last edit was the same text. +#[test] +fn a_body_that_is_the_one_on_screen_says_so() { + let mut harness = rewritten(&["B".to_owned(), "A".to_owned(), "B".to_owned()]); + look(&mut harness, 1); + + assert_eq!(shown(&harness, "revision-identical").len(), 1); + assert!(shown(&harness, "diff-kept").is_empty()); +} + +#[test] +fn the_lines_far_from_a_change_are_counted_rather_than_shown() { + let lines: Vec = (0..40).map(|at| format!("line {at}")).collect(); + let mut changed = lines.clone(); + changed[20] = "line twenty".to_owned(); + let mut harness = rewritten(&[lines.join("\n"), changed.join("\n")]); + look(&mut harness, 0); + + assert_eq!(shown(&harness, "diff-restored"), ["+ line 20"]); + assert_eq!(shown(&harness, "diff-dropped"), ["− line twenty"]); + let kept = shown(&harness, "diff-kept"); + assert!(!kept.is_empty() && kept.len() < 10, "{kept:?}"); + assert_eq!(shown(&harness, "diff-skipped").len(), 2, "above and below"); +} + +/// What is put back erases what came after it. +#[test] +fn the_consequence_counts_the_newer_bodies() { + let bodies: Vec = ["B", "C", "D"].map(str::to_owned).to_vec(); + let warned = |rank| { + let mut harness = rewritten(&bodies); + look(&mut harness, rank); + shown(&harness, "revision-consequence").join("") + }; + + assert_ne!(warned(0), warned(2)); } diff --git a/crates/ui/src/notes/overlays/editor/rich.rs b/crates/ui/src/notes/overlays/editor/rich.rs index 58db0f0be..aca4c773d 100644 --- a/crates/ui/src/notes/overlays/editor/rich.rs +++ b/crates/ui/src/notes/overlays/editor/rich.rs @@ -11,6 +11,7 @@ use richtext::edit::{self, ordered}; use richtext::inlines::{self, Mark}; use richtext::picture::{self, Beside}; use richtext::{Document, History, ListKind, Marks, Position, Selection, tree}; +use text::{Direction, Unit}; use crate::state::AppState; use crate::theme::palette; @@ -67,16 +68,10 @@ impl RichEditor { if document.blocks.is_empty() { document.blocks.push(richtext::Block::Paragraph(Vec::new())); } - let first = tree::leaves(&document) - .into_iter() - .next() - .unwrap_or_default(); + let first = tree::leaves(&document).into_iter().next().unwrap_or_default(); Self { document, - selection: Selection::caret(Position { - path: first, - offset: 0, - }), + selection: Selection::caret(Position { path: first, offset: 0 }), history: History::default(), last: None, edited: false, @@ -124,12 +119,9 @@ impl RichEditor { /// Text typed, then the input rule it closes, undone on its own. fn type_text(&mut self, text: &str) { let marks = self.stored.take().unwrap_or_else(|| self.marks_here()); - self.change(Step::Typing, |document, selection| { - edit::insert_text(document, selection, text, &marks) - }); + self.change(Step::Typing, |document, selection| edit::insert_text(document, selection, text, &marks)); let before = self.document.clone(); - let Some(applied) = richtext::rules::after_typing(&mut self.document, &self.selection) - else { + let Some(applied) = richtext::rules::after_typing(&mut self.document, &self.selection) else { return; }; let typed = std::mem::replace(&mut self.document, before); @@ -172,11 +164,7 @@ impl RichEditor { fn undo(&mut self, redo: bool) { let now = (&self.document, &self.selection); - let back = if redo { - self.history.redo(now) - } else { - self.history.undo(now) - }; + let back = if redo { self.history.redo(now) } else { self.history.undo(now) }; if let Some((document, selection)) = back { self.document = document; self.selection = selection; @@ -195,32 +183,37 @@ impl RichEditor { }; let end = tree::leaf(&self.document, last).map_or(0, |leaf| leaf.len()); self.selection = Selection { - anchor: Position { - path: first.clone(), - offset: 0, - }, - head: Position { - path: last.clone(), - offset: end, - }, + anchor: Position { path: first.clone(), offset: 0 }, + head: Position { path: last.clone(), offset: end }, }; } - /// The caret one `char` along, across leaves; `extend` keeps the anchor. - fn step(&mut self, forward: bool, extend: bool) { + /// The text of the leaf at `path`, as its offsets count it. + fn leaf_text(&self, path: &[usize]) -> Option { + match tree::leaf(&self.document, path)? { + tree::Leaf::Inlines(content) => Some(inlines::plain(content)), + tree::Leaf::Code(text) => Some(text.clone()), + } + } + + /// The offset one `unit` along in the caret's leaf; `None` at its edge. + fn along(&self, forward: bool, unit: Unit) -> Option { + let head = &self.selection.head; + let direction = if forward { Direction::Forward } else { Direction::Backward }; + let buffer = text::Buffer::new(&self.leaf_text(&head.path)?); + let offset = buffer.step(head.offset, direction, unit); + (offset != head.offset).then_some(offset) + } + + /// The caret one `unit` along, across leaves; `extend` keeps the anchor. + fn step(&mut self, forward: bool, extend: bool, unit: Unit) { let head = self.selection.head.clone(); - if !extend && !self.selection.is_empty() { + if !extend && unit == Unit::Grapheme && !self.selection.is_empty() { let (start, end) = ordered(&self.selection); self.selection = Selection::caret(if forward { end } else { start }); return; } - let length = tree::leaf(&self.document, &head.path).map_or(0, |leaf| leaf.len()); - let inside = if forward { - (head.offset < length).then_some(head.offset + 1) - } else { - head.offset.checked_sub(1) - }; - if let Some(offset) = inside { + if let Some(offset) = self.along(forward, unit) { self.move_head(Position { offset, ..head }, extend); } else { self.step_past(head.path, forward, extend); @@ -228,6 +221,20 @@ impl RichEditor { self.goal_x = None; } + /// The selection, or one `unit` from the caret; at a leaf's edge, what the document makes of it. + fn delete(&mut self, forward: bool, unit: Unit) { + let within = self.selection.is_empty().then(|| self.along(forward, unit)); + let Some(offset) = within.flatten() else { + let delete = if forward { edit::delete_forward } else { edit::delete_backward }; + self.change(Step::Other, delete); + return; + }; + let anchor = self.selection.head.clone(); + let head = Position { offset, ..anchor.clone() }; + let taken = Selection { anchor, head }; + self.change(Step::Other, |document, _| edit::delete_selection(document, &taken)); + } + /// Off a leaf or an image: onto the image beside it, which a selection goes over. fn step_past(&mut self, mut path: Vec, forward: bool, extend: bool) { loop { @@ -243,26 +250,14 @@ impl RichEditor { /// The word holding the `char` at `at`, as the code editor reads a word; `extend`, the /// selection stretched to it. fn select_word(&mut self, at: Position, extend: bool) { - let text = match tree::leaf(&self.document, &at.path) { - Some(tree::Leaf::Inlines(content)) => inlines::plain(content), - Some(tree::Leaf::Code(text)) => text.clone(), - None => return, + let Some(text) = self.leaf_text(&at.path) else { + return; }; let word = text::word_around(&text, at.offset); - let start = Position { - path: at.path.clone(), - offset: word.start, - }; - let end = Position { - path: at.path, - offset: word.end, - }; + let start = Position { path: at.path.clone(), offset: word.start }; + let end = Position { path: at.path, offset: word.end }; if extend { - let head = if start >= self.selection.anchor { - end - } else { - start - }; + let head = if start >= self.selection.anchor { end } else { start }; self.move_head(head, true); } else { self.move_head(start, false); @@ -276,13 +271,7 @@ impl RichEditor { let Some(len) = tree::leaf(&self.document, &path).map(|leaf| leaf.len()) else { return; }; - self.move_head( - Position { - path: path.clone(), - offset: 0, - }, - false, - ); + self.move_head(Position { path: path.clone(), offset: 0 }, false); self.move_head(Position { path, offset: len }, true); self.goal_x = None; } @@ -321,10 +310,7 @@ impl RichEditor { fn position_at(&self, point: Pos2) -> Option { let laid = self.laid_at(point)?; let offset = laid.galley.cursor_from_pos(point - laid.origin).index.0; - Some(Position { - path: laid.path.clone(), - offset, - }) + Some(Position { path: laid.path.clone(), offset }) } /// The `char` under a point: before the nearest boundary when the point is left of it. @@ -333,10 +319,7 @@ impl RichEditor { let local = point - laid.origin; let cursor = laid.galley.cursor_from_pos(local); let before = local.x < laid.galley.pos_from_cursor(cursor).center().x; - Some(Position { - path: laid.path.clone(), - offset: cursor.index.0.saturating_sub(usize::from(before)), - }) + Some(Position { path: laid.path.clone(), offset: cursor.index.0.saturating_sub(usize::from(before)) }) } /// ↓ with nothing under a code block: a paragraph is opened there. @@ -355,15 +338,8 @@ impl RichEditor { return; }; let x = *self.goal_x.get_or_insert(caret.left()); - let y = if down { - caret.bottom() + 2.0 - } else { - caret.top() - 2.0 - }; - let inside = self - .laid - .iter() - .find(|laid| laid_rect(laid).y_range().contains(y)); + let y = if down { caret.bottom() + 2.0 } else { caret.top() - 2.0 }; + let inside = self.laid.iter().find(|laid| laid_rect(laid).y_range().contains(y)); let target = inside.or_else(|| { if down { self.laid @@ -385,15 +361,8 @@ impl RichEditor { }; let rect = laid_rect(target); let y = y.clamp(rect.top() + 1.0, rect.bottom() - 1.0); - let offset = target - .galley - .cursor_from_pos(pos2(x, y) - target.origin) - .index - .0; - let head = Position { - path: target.path.clone(), - offset, - }; + let offset = target.galley.cursor_from_pos(pos2(x, y) - target.origin).index.0; + let head = Position { path: target.path.clone(), offset }; let goal = self.goal_x; self.move_head(head, extend); self.goal_x = goal; @@ -453,8 +422,7 @@ pub(super) fn show(ui: &mut Ui, view: &mut RichEditor, state: &AppState) -> Show top = bar_ui.min_rect().bottom(); } let p = palette(ui.ctx()); - ui.painter() - .hline(whole.x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(whole.x_range(), top, Stroke::new(1.0, p.line_soft)); let body = Rect::from_min_max(pos2(whole.left(), top + 1.0), whole.max); let mut body_ui = ui.new_child(UiBuilder::new().id_salt("rich-body").max_rect(body)); let surface = widgets::region(&mut body_ui, body, "editor-rich", Sense::click_and_drag()); @@ -543,12 +511,8 @@ pub(in crate::notes) fn embedded(state: &AppState, id: &str) -> Option /// Tab and the arrows are the text's while it has the keys; Escape is not, it closes. fn lock_keys(ui: &Ui, id: egui::Id) { - let filter = egui::EventFilter { - tab: true, - horizontal_arrows: true, - vertical_arrows: true, - escape: false, - }; + let filter = + egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape: false }; ui.memory_mut(|memory| memory.set_focus_lock_filter(id, filter)); } @@ -557,11 +521,7 @@ fn describe(ui: &Ui, surface: &egui::Response, view: &RichEditor, language: Lang let label = i18n::translate(language, keys::editor::CONTENT_LABEL, &[]); let value: String = tree::leaves(&view.document) .iter() - .filter_map(|path| match tree::leaf(&view.document, path) { - Some(tree::Leaf::Inlines(content)) => Some(inlines::plain(content)), - Some(tree::Leaf::Code(text)) => Some(text.clone()), - None => None, - }) + .filter_map(|path| view.leaf_text(path)) .collect::>() .join("\n"); surface.widget_info(|| egui::WidgetInfo::labeled(egui::Role::MultilineTextInput, true, &label)); @@ -579,6 +539,8 @@ fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) { return; }; let shift = ui.input(|input| input.modifiers.shift); + // A drag is known as one once the pointer left where it was pressed. + let pressed = ui.input(|input| input.pointer.press_origin()).unwrap_or(at); // egui reports the click of a double click too, and both of a triple: the longest first. if surface.triple_clicked() && let Some(position) = view.position_at(at) @@ -591,7 +553,7 @@ fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) { view.select_word(position, shift); surface.request_focus(); } else if (surface.drag_started() || surface.clicked()) - && let Some(position) = view.position_at(at) + && let Some(position) = view.position_at(pressed) { view.move_head(position, shift); view.goal_x = None; @@ -604,11 +566,7 @@ fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) { } /// The frame's keys and clipboard events; code pasted into the empty Note is answered. -fn keys( - ui: &Ui, - view: &mut RichEditor, - clipboard: &dyn platform::clipboard::Clipboard, -) -> Option { +fn keys(ui: &Ui, view: &mut RichEditor, clipboard: &dyn platform::clipboard::Clipboard) -> Option { let events = ui.input(|input| input.events.clone()); let mut code_paste = None; // A shortcut the text ran is taken from the frame, or the area's keys would run it too: @@ -623,13 +581,7 @@ fn keys( copy(ui, view); view.change(Step::Other, edit::delete_selection); } - Event::Key { - key, - physical_key, - pressed: true, - modifiers, - .. - } => { + Event::Key { key, physical_key, pressed: true, modifiers, .. } => { let shortcut = key_pressed(ui, view, key, physical_key, modifiers); if shortcut { ran.push((modifiers, key)); @@ -654,9 +606,7 @@ fn paste( ) -> Option { if let Some(html) = clipboard.html().filter(|html| richtext::formatted(html)) { let pasted = richtext::from_html(&html); - view.change(Step::Other, |document, selection| { - edit::insert_document(document, selection, pasted) - }); + view.change(Step::Other, |document, selection| edit::insert_document(document, selection, pasted)); return None; } let text = text.replace("\r\n", "\n"); @@ -675,15 +625,13 @@ fn paste( /// The selection as text, its lists' markers kept. fn copy(ui: &Ui, view: &RichEditor) { if !view.selection.is_empty() { - ui.ctx() - .copy_text(edit::copied(&view.document, &view.selection)); + ui.ctx().copy_text(edit::copied(&view.document, &view.selection)); } } fn copy_markdown(ui: &Ui, view: &RichEditor) { if !view.selection.is_empty() { - ui.ctx() - .copy_text(edit::copied_markdown(&view.document, &view.selection)); + ui.ctx().copy_text(edit::copied_markdown(&view.document, &view.selection)); } } @@ -704,8 +652,7 @@ fn menu(view: &mut RichEditor, surface: &egui::Response, language: Language) { ]; for (key, author_id) in entries { let label = i18n::translate(language, key, &[]); - if !crate::widgets::menu_entry(ui, &label, author_id, false, false, false).clicked() - { + if !crate::widgets::menu_entry(ui, &label, author_id, false, false, false).clicked() { continue; } match author_id { @@ -715,9 +662,7 @@ fn menu(view: &mut RichEditor, surface: &egui::Response, language: Language) { } "rich-menu-copy" => copy(ui, view), "rich-menu-copy-markdown" => copy_markdown(ui, view), - "rich-menu-paste" => ui - .ctx() - .send_viewport_cmd(egui::ViewportCommand::RequestPaste), + "rich-menu-paste" => ui.ctx().send_viewport_cmd(egui::ViewportCommand::RequestPaste), "rich-menu-select-all" => view.select_all(), _ => {} } @@ -743,12 +688,13 @@ fn key_pressed( if let Some(shortcut) = images::key_pressed(view, key, modifiers) { return shortcut; } + let unit = if modifiers.command { Unit::Word } else { Unit::Grapheme }; match key { Key::Enter => view.change(Step::Other, edit::split), - Key::Backspace => view.change(Step::Other, edit::delete_backward), - Key::Delete => view.change(Step::Other, edit::delete_forward), - Key::ArrowLeft => view.step(false, modifiers.shift), - Key::ArrowRight => view.step(true, modifiers.shift), + Key::Backspace => view.delete(false, unit), + Key::Delete => view.delete(true, unit), + Key::ArrowLeft => view.step(false, modifiers.shift, unit), + Key::ArrowRight => view.step(true, modifiers.shift, unit), Key::ArrowUp => view.vertical(false, modifiers.shift), Key::ArrowDown => view.vertical(true, modifiers.shift), Key::Home | Key::End => line_edge(view, key == Key::End, modifiers), @@ -789,22 +735,13 @@ fn run_command(ui: &Ui, view: &mut RichEditor, command: shortcuts::Command) { /// Home and End: the line's edges; with Ctrl, the document's. fn line_edge(view: &mut RichEditor, end: bool, modifiers: Modifiers) { + view.goal_x = None; if modifiers.command { let leaves = tree::leaves(&view.document); let target = if end { leaves.last() } else { leaves.first() }; if let Some(path) = target { - let offset = if end { - tree::leaf(&view.document, path).map_or(0, |leaf| leaf.len()) - } else { - 0 - }; - view.move_head( - Position { - path: path.clone(), - offset, - }, - modifiers.shift, - ); + let offset = if end { tree::leaf(&view.document, path).map_or(0, |leaf| leaf.len()) } else { 0 }; + view.move_head(Position { path: path.clone(), offset }, modifiers.shift); } return; } @@ -813,16 +750,8 @@ fn line_edge(view: &mut RichEditor, end: bool, modifiers: Modifiers) { return; }; let caret = laid.galley.pos_from_cursor(CCursor::new(head.offset)); - let x = if end { - f32::INFINITY - } else { - f32::NEG_INFINITY - }; - let offset = laid - .galley - .cursor_from_pos(egui::vec2(x, caret.center().y)) - .index - .0; + let x = if end { f32::INFINITY } else { f32::NEG_INFINITY }; + let offset = laid.galley.cursor_from_pos(egui::vec2(x, caret.center().y)).index.0; view.move_head(Position { offset, ..head }, modifiers.shift); } @@ -838,24 +767,18 @@ fn tab(view: &mut RichEditor, back: bool) { if let Some(tree::Leaf::Code(_)) = tree::leaf(&view.document, &path) { let unit = code_indent(view); if back { - view.change(Step::Other, |document, selection| { - edit::outdent_code(document, selection, &unit) - }); + view.change(Step::Other, |document, selection| edit::outdent_code(document, selection, &unit)); } else { view.type_text(&unit); } return; } - let item = tree::innermost_item(&view.document, &path); - match (item, back) { - (Some(_), false) => view.change(Step::Other, edit::sink_item), - (Some((list, item, _)), true) => { - view.change(Step::Other, |document, _| { - edit::lift_item(document, &list, item) - }); - } - (None, false) => view.type_text("\t"), - (None, true) => untab(view), + let in_item = tree::innermost_item(&view.document, &path).is_some(); + match (in_item, back) { + (true, false) => view.change(Step::Other, edit::sink_item), + (true, true) => view.change(Step::Other, edit::lift_item), + (false, false) => view.type_text("\t"), + (false, true) => untab(view), } } @@ -865,9 +788,7 @@ fn code_indent(view: &RichEditor) -> String { Some(richtext::Block::CodeBlock { language, .. }) => language.parse().ok(), _ => None, }; - language - .map_or(" ", crate::notes::language::indent_unit) - .to_owned() + language.map_or(" ", crate::notes::language::indent_unit).to_owned() } /// Shift+Tab outside a list: the tab a line starts with goes. @@ -880,17 +801,10 @@ fn untab(view: &mut RichEditor) { if !starts { return; } - let tab = Selection { - anchor: Position { - path: path.clone(), - offset: 0, - }, - head: Position { path, offset: 1 }, - }; + let tab = + Selection { anchor: Position { path: path.clone(), offset: 0 }, head: Position { path, offset: 1 } }; let offset = view.selection.head.offset.saturating_sub(1); - view.change(Step::Other, |document, _| { - edit::delete_selection(document, &tab) - }); + view.change(Step::Other, |document, _| edit::delete_selection(document, &tab)); view.selection.head.offset = offset; view.selection.anchor = view.selection.head.clone(); } @@ -903,15 +817,10 @@ fn paint_caret(ui: &Ui, view: &RichEditor, body: Rect) { return; } let p = palette(ui.ctx()); - ui.painter().with_clip_rect(body).vline( - caret.left(), - caret.y_range(), - Stroke::new(1.5, p.text_0), - ); - let to_global = ui - .ctx() - .layer_transform_to_global(ui.layer_id()) - .unwrap_or_default(); + ui.painter() + .with_clip_rect(body) + .vline(caret.left(), caret.y_range(), Stroke::new(1.5, p.text_0)); + let to_global = ui.ctx().layer_transform_to_global(ui.layer_id()).unwrap_or_default(); ui.ctx().output_mut(|output| { output.ime = Some(egui::output::IMEOutput { purpose: egui::IMEPurpose::Normal, diff --git a/crates/ui/src/notes/overlays/editor/rich/images.rs b/crates/ui/src/notes/overlays/editor/rich/images.rs index 0ba54dcda..32d40cd5e 100644 --- a/crates/ui/src/notes/overlays/editor/rich/images.rs +++ b/crates/ui/src/notes/overlays/editor/rich/images.rs @@ -22,10 +22,7 @@ impl RichEditor { _ => None, }; let place = past(true).or_else(|| past(false)).unwrap_or_else(|| { - let start = Position { - path: image.clone(), - offset: 0, - }; + let start = Position { path: image.clone(), offset: 0 }; tree::clamp(&self.document, &start) }); self.selection = Selection::caret(place); @@ -76,16 +73,8 @@ pub(super) fn key_pressed(view: &mut RichEditor, key: Key, modifiers: Modifiers) } /// Over the image picked: its outline, and on a drawing the corners to drag and the sizes. -pub(super) fn controls( - ui: &mut Ui, - view: &mut RichEditor, - images: &[LaidImage], - language: Language, -) { - let Some(laid) = images - .iter() - .find(|laid| Some(&laid.path) == view.picked.as_ref()) - else { +pub(super) fn controls(ui: &mut Ui, view: &mut RichEditor, images: &[LaidImage], language: Language) { + let Some(laid) = images.iter().find(|laid| Some(&laid.path) == view.picked.as_ref()) else { return; }; let p = palette(ui.ctx()); @@ -99,16 +88,8 @@ pub(super) fn controls( sizes(ui, view, laid, language); let label = i18n::translate(language, keys::drawing::EMBED_RESIZE, &[]); let corners = [ - ( - "rich-embed-resize", - laid.rect.right_bottom(), - CursorIcon::ResizeNwSe, - ), - ( - "rich-embed-resize-top", - laid.rect.right_top(), - CursorIcon::ResizeNeSw, - ), + ("rich-embed-resize", laid.rect.right_bottom(), CursorIcon::ResizeNwSe), + ("rich-embed-resize-top", laid.rect.right_top(), CursorIcon::ResizeNeSw), ]; for (author_id, at, cursor) in corners { let room = Rect::from_center_size(at, Vec2::splat(widgets::MIN_TARGET)); diff --git a/crates/ui/src/notes/overlays/editor/rich/search.rs b/crates/ui/src/notes/overlays/editor/rich/search.rs index 4f9d60d9c..4decdcf71 100644 --- a/crates/ui/src/notes/overlays/editor/rich/search.rs +++ b/crates/ui/src/notes/overlays/editor/rich/search.rs @@ -32,41 +32,26 @@ pub(super) fn matches(view: &RichEditor, query: &Query) -> Vec { /// What the bar draws over, when it is open: every match, for the view to light. pub(super) fn lit(view: &RichEditor, bar: &SearchBar) -> Vec { - if bar.open { - matches(view, &bar.query) - } else { - Vec::new() - } + if bar.open { matches(view, &bar.query) } else { Vec::new() } } fn start(found: &Found) -> Position { - Position { - path: found.0.clone(), - offset: found.1.start, - } + Position { path: found.0.clone(), offset: found.1.start } } fn end(found: &Found) -> Position { - Position { - path: found.0.clone(), - offset: found.1.end, - } + Position { path: found.0.clone(), offset: found.1.end } } fn select(found: &Found) -> Selection { - Selection { - anchor: start(found), - head: end(found), - } + Selection { anchor: start(found), head: end(found) } } impl RichEditor { /// The match the selection is on. fn selected_match(&self, found: &[Found]) -> Option { let (from, to) = ordered(&self.selection); - found - .iter() - .position(|each| start(each) == from && end(each) == to) + found.iter().position(|each| start(each) == from && end(each) == to) } } @@ -92,12 +77,8 @@ impl Searchable for RichEditor { let (first, last) = ordered(&self.selection); let next = match (from, direction) { (SeekFrom::Start, _) => found.iter().position(|each| start(each) >= first), - (SeekFrom::Past, Direction::Forward) => { - found.iter().position(|each| start(each) >= last) - } - (SeekFrom::Past, Direction::Backward) => { - found.iter().rposition(|each| end(each) <= first) - } + (SeekFrom::Past, Direction::Forward) => found.iter().position(|each| start(each) >= last), + (SeekFrom::Past, Direction::Backward) => found.iter().rposition(|each| end(each) <= first), }; let at = next.unwrap_or(match direction { Direction::Forward => 0, @@ -130,10 +111,8 @@ impl Searchable for RichEditor { self.record(Step::Other); // From the last: the offsets before it stay true. for each in found.iter().rev() { - let replacement = query.replacement(&richtext::edit::selected_text( - &self.document, - &select(each), - )); + let replacement = + query.replacement(&richtext::edit::selected_text(&self.document, &select(each))); let marks = self.marks_at_match(each); richtext::edit::insert_text(&mut self.document, &select(each), &replacement, &marks); } diff --git a/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs b/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs index e386742ac..aa16e6741 100644 --- a/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs +++ b/crates/ui/src/notes/overlays/editor/rich/shortcuts.rs @@ -67,17 +67,12 @@ fn matches(notation: &str, key: Key, physical: Option, modifiers: Modifiers return false; }; let wants = |modifier| held.contains(&modifier); - if modifiers.command != wants("Mod") - || modifiers.shift != wants("Shift") - || modifiers.alt != wants("Alt") + if modifiers.command != wants("Mod") || modifiers.shift != wants("Shift") || modifiers.alt != wants("Alt") { return false; } - let pressed = if name.chars().all(|glyph| glyph.is_ascii_digit()) { - physical.unwrap_or(key) - } else { - key - }; + let pressed = + if name.chars().all(|glyph| glyph.is_ascii_digit()) { physical.unwrap_or(key) } else { key }; Key::from_name(&name.to_uppercase()).or_else(|| Key::from_name(name)) == Some(pressed) } @@ -88,15 +83,9 @@ mod tests { #[test] fn a_digit_is_read_where_the_key_sits_and_a_letter_as_it_reads() { let ctrl_shift = Modifiers::COMMAND | Modifiers::SHIFT; - assert_eq!( - find(Key::Num8, Some(Key::Num8), ctrl_shift), - Some(Command::Bullet) - ); + assert_eq!(find(Key::Num8, Some(Key::Num8), ctrl_shift), Some(Command::Bullet)); // AZERTY: the key that prints 8 unshifted on QWERTY reads `_` with no digit. - assert_eq!( - find(Key::Minus, Some(Key::Num8), ctrl_shift), - Some(Command::Bullet) - ); + assert_eq!(find(Key::Minus, Some(Key::Num8), ctrl_shift), Some(Command::Bullet)); assert_eq!(find(Key::B, None, Modifiers::COMMAND), Some(Command::Bold)); assert_eq!(find(Key::B, None, ctrl_shift), Some(Command::Quote)); assert_eq!(find(Key::B, None, Modifiers::NONE), None); diff --git a/crates/ui/src/notes/overlays/editor/rich/tests.rs b/crates/ui/src/notes/overlays/editor/rich/tests.rs index 4e50f2de1..76b17182f 100644 --- a/crates/ui/src/notes/overlays/editor/rich/tests.rs +++ b/crates/ui/src/notes/overlays/editor/rich/tests.rs @@ -26,9 +26,7 @@ fn note(content: &str) -> (Harness<'static>, String) { .id .clone(); let mut harness = expanded_area(backend, profile); - harness - .get_by(|node| node.author_id() == Some("search-input")) - .focus(); + harness.get_by(|node| node.author_id() == Some("search-input")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("search-input")) @@ -42,12 +40,10 @@ fn note(content: &str) -> (Harness<'static>, String) { fn stored(harness: &Harness<'_>, id: &str) -> String { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() - .content - .clone() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + .content + .clone() } fn surface_text(harness: &Harness<'_>) -> String { @@ -71,9 +67,7 @@ fn press(harness: &mut Harness<'_>, modifiers: Modifiers, key: Key) { } fn type_in(harness: &mut Harness<'_>, text: &str) { - harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .type_text(text); + harness.get_by(|node| node.author_id() == Some("editor-rich")).type_text(text); settle(harness); } @@ -189,11 +183,7 @@ fn the_arrows_select_across_blocks_and_cut_then_paste_moves_the_text() { harness.event(egui::Event::Paste("b\ncd".to_owned())); settle(&mut harness); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - "ab\n\ncdef", - "joined by Delete, then pasted" - ); + assert_eq!(stored(&harness, &id), "ab\n\ncdef", "joined by Delete, then pasted"); } #[test] @@ -202,16 +192,12 @@ fn a_link_is_written_from_its_form_and_undo_and_redo_step_through_it() { at_end(&mut harness); type_in(&mut harness, " "); click_id(&mut harness, "rich-link"); - harness - .get_by(|node| node.author_id() == Some("rich-link-text")) - .focus(); + harness.get_by(|node| node.author_id() == Some("rich-link-text")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("rich-link-text")) .type_text("le site"); - harness - .get_by(|node| node.author_id() == Some("rich-link-address")) - .focus(); + harness.get_by(|node| node.author_id() == Some("rich-link-address")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("rich-link-address")) @@ -239,10 +225,7 @@ fn markdown_typed_becomes_formatting_and_the_shortcuts_format() { type_in(&mut harness, "fin"); press(&mut harness, Modifiers::COMMAND | Modifiers::ALT, Key::Num3); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - "## Plan\n\n- du **gras** ici\n\n### fin" - ); + assert_eq!(stored(&harness, &id), "## Plan\n\n- du **gras** ici\n\n### fin"); } #[test] @@ -318,21 +301,14 @@ fn a_page_pasted_keeps_its_bold_and_its_link() { Some(""), ); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - "Voir **zqcopie** et [là](https://devnotes.fr)" - ); + assert_eq!(stored(&harness, &id), "Voir **zqcopie** et [là](https://devnotes.fr)"); } #[test] fn code_pasted_into_an_empty_note_makes_it_a_snippet_and_text_pastes_as_text() { let (mut harness, id) = note(""); click_id(&mut harness, "editor-rich"); - paste( - &mut harness, - "{\n \"id\": 42\n}", - Some("
{}
"), - ); + paste(&mut harness, "{\n \"id\": 42\n}", Some("
{}
")); crate::notes::bench::until(&mut harness, "a JSON snippet", |harness| { let id = id.clone(); let note = engine::db::run_here(harness.state().backend.engine(), move |engine| { @@ -346,11 +322,7 @@ fn code_pasted_into_an_empty_note_makes_it_a_snippet_and_text_pastes_as_text() { at_end(&mut harness); paste(&mut harness, " {\"a\": 1}", None); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - "Voir {\"a\": 1}", - "a Note with words stays a Note" - ); + assert_eq!(stored(&harness, &id), "Voir {\"a\": 1}", "a Note with words stays a Note"); } fn search_count(harness: &Harness<'_>) -> String { @@ -399,10 +371,7 @@ fn png_uri(side: u32) -> String { let pixels = vec![200u8; usize::try_from(side * side * 4).unwrap()]; writer.write_image_data(&pixels).unwrap(); writer.finish().unwrap(); - format!( - "data:image/png;base64,{}", - base64::engine::general_purpose::STANDARD.encode(bytes) - ) + format!("data:image/png;base64,{}", base64::engine::general_purpose::STANDARD.encode(bytes)) } /// A Note of `content`, `{}` its drawing's id, open once the drawing's picture is read. @@ -417,10 +386,8 @@ fn embedding(content: &str) -> (Harness<'static>, String) { ..testing::snippet(space, "Archi".to_owned()) }; let id = engine::notes::create_note(engine, draft)?.id.clone(); - let pictures = engine::notes::drawing::DrawingPictures { - thumbnail: png_uri(4), - picture: png_uri(40), - }; + let pictures = + engine::notes::drawing::DrawingPictures { thumbnail: png_uri(4), picture: png_uri(40) }; let patch = engine::notes::model::NotePatch { pictures: Some(pictures), ..engine::notes::model::NotePatch::default() @@ -444,9 +411,7 @@ fn embedding(content: &str) -> (Harness<'static>, String) { .id .clone(); let mut harness = expanded_area(backend, profile); - harness - .get_by(|node| node.author_id() == Some("search-input")) - .focus(); + harness.get_by(|node| node.author_id() == Some("search-input")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("search-input")) @@ -456,9 +421,7 @@ fn embedding(content: &str) -> (Harness<'static>, String) { }); click_id(&mut harness, "note-card-open"); crate::notes::bench::until(&mut harness, "the drawing's picture", |harness| { - said(harness) - .first() - .is_some_and(|said| said == "le schéma") + said(harness).first().is_some_and(|said| said == "le schéma") }); settle(&mut harness); (harness, id) @@ -474,8 +437,7 @@ fn said(harness: &Harness<'_>) -> Vec { #[test] fn an_embedded_drawing_shows_its_picture_and_a_lost_one_says_so() { - let (mut harness, _) = - embedding("![le schéma](devnotes:drawing/{})\n\n![perdu](devnotes:drawing/nope)"); + let (mut harness, _) = embedding("![le schéma](devnotes:drawing/{})\n\n![perdu](devnotes:drawing/nope)"); crate::notes::bench::until(&mut harness, "both read", |harness| { said(harness) == ["le schéma", "Drawing not found"] }); @@ -492,9 +454,7 @@ fn drawn(harness: &Harness<'_>) -> egui::Rect { } fn present(harness: &Harness<'_>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } /// The Note saved, its drawing's reference. @@ -546,10 +506,7 @@ fn a_corner_dragged_keeps_the_ratio_and_stops_on_a_quarter() { assert!((drawn(&harness).width() - 0.5 * whole.width()).abs() < 1.0); press(&mut harness, Modifiers::COMMAND, Key::Z); - assert!( - (drawn(&harness).width() - whole.width()).abs() < 1.0, - "the drag is one step" - ); + assert!((drawn(&harness).width() - whole.width()).abs() < 1.0, "the drag is one step"); press(&mut harness, Modifiers::COMMAND, Key::Y); assert!(reference(&mut harness, &id).ends_with("?w=50")); } @@ -557,16 +514,11 @@ fn a_corner_dragged_keeps_the_ratio_and_stops_on_a_quarter() { #[test] fn the_arrows_reach_the_drawing_resize_it_with_alt_and_delete_takes_it_away() { let (mut harness, id) = embedding(EMBEDDING); - harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .focus(); + harness.get_by(|node| node.author_id() == Some("editor-rich")).focus(); press(&mut harness, Modifiers::COMMAND, Key::Home); press(&mut harness, Modifiers::NONE, Key::End); press(&mut harness, Modifiers::NONE, Key::ArrowRight); - assert!( - present(&harness, "rich-embed-resize"), - "the drawing is picked" - ); + assert!(present(&harness, "rich-embed-resize"), "the drawing is picked"); press(&mut harness, Modifiers::NONE, Key::ArrowRight); assert!(!present(&harness, "rich-embed-resize")); press(&mut harness, Modifiers::NONE, Key::ArrowLeft); @@ -610,14 +562,9 @@ fn a_fence_in_a_language_the_editor_does_not_know_stays_code_and_keeps_its_word( /// the toolbar and the header. #[test] fn a_long_code_block_scrolled_down_paints_nothing_above_the_body() { - let code = (0..80) - .map(|n| format!("let line_{n} = {n};")) - .collect::>() - .join("\n"); + let code = (0..80).map(|n| format!("let line_{n} = {n};")).collect::>().join("\n"); let (mut harness, _) = note(&format!("# Notes\n\nIntro.\n\n```rust\n{code}\n```\n")); - let body = harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .rect(); + let body = harness.get_by(|node| node.author_id() == Some("editor-rich")).rect(); harness.event(egui::Event::PointerMoved(body.center())); for _ in 0..6 { harness.event(egui::Event::MouseWheel { @@ -650,9 +597,7 @@ fn a_long_code_block_scrolled_down_paints_nothing_above_the_body() { #[test] fn the_down_arrow_on_the_last_line_of_a_final_code_block_opens_a_paragraph() { let (mut harness, id) = note("```rust\nlet x = 1;\nlet y = 2;\n```"); - let surface = harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .rect(); + let surface = harness.get_by(|node| node.author_id() == Some("editor-rich")).rect(); harness.drag_at(surface.left_top() + egui::vec2(60.0, 20.0)); harness.drop_at(surface.left_top() + egui::vec2(60.0, 20.0)); settle(&mut harness); @@ -667,10 +612,7 @@ fn the_down_arrow_on_the_last_line_of_a_final_code_block_opens_a_paragraph() { settle(&mut harness); click_id(&mut harness, "editor-close"); - assert_eq!( - stored(&harness, &id), - "```rust\nlet x = 1;\nlet y = 2;\n```\n\nAprès" - ); + assert_eq!(stored(&harness, &id), "```rust\nlet x = 1;\nlet y = 2;\n```\n\nAprès"); } /// Where the painted `words` show their char at `offset`, in the window. @@ -678,9 +620,7 @@ fn point_in(harness: &Harness<'_>, words: &str, offset: usize) -> egui::Pos2 { let shapes = &harness.output().shapes; let found = shapes.iter().find_map(|clipped| match &clipped.shape { egui::Shape::Text(text) if text.galley.text() == words => { - let at = text - .galley - .pos_from_cursor(egui::text::CCursor::new(offset)); + let at = text.galley.pos_from_cursor(egui::text::CCursor::new(offset)); Some(text.pos + at.center().to_vec2()) } _ => None, @@ -764,17 +704,12 @@ fn a_copied_list_keeps_its_markers_and_drops_the_inline_marks() { click_id(&mut harness, "editor-rich"); press(&mut harness, Modifiers::COMMAND, Key::A); harness.event(egui::Event::Copy); - assert_eq!( - clipboard(&mut harness).as_deref(), - Some("- one bold\n- two\n1. first\n2. second") - ); + assert_eq!(clipboard(&mut harness).as_deref(), Some("- one bold\n- two\n1. first\n2. second")); } /// Clicked, the frame left to `clipboard`: its copy is read there. fn menu_entry(harness: &Harness<'_>, author_id: &str) { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); } #[test] @@ -792,30 +727,17 @@ fn ctrl_shift_c_and_the_menu_copy_the_selection_as_markdown() { repeat: false, modifiers: held, }); - assert_eq!( - clipboard(&mut harness).as_deref(), - Some("- one **bold**\n- two") - ); + assert_eq!(clipboard(&mut harness).as_deref(), Some("- one **bold**\n- two")); harness.event(egui::Event::ModifiersChanged(Modifiers::NONE)); - harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .click_secondary(); + harness.get_by(|node| node.author_id() == Some("editor-rich")).click_secondary(); settle(&mut harness); menu_entry(&harness, "rich-menu-copy-markdown"); - assert_eq!( - clipboard(&mut harness).as_deref(), - Some("- one **bold**\n- two") - ); - harness - .get_by(|node| node.author_id() == Some("editor-rich")) - .click_secondary(); + assert_eq!(clipboard(&mut harness).as_deref(), Some("- one **bold**\n- two")); + harness.get_by(|node| node.author_id() == Some("editor-rich")).click_secondary(); settle(&mut harness); menu_entry(&harness, "rich-menu-copy"); - assert_eq!( - clipboard(&mut harness).as_deref(), - Some("- one bold\n- two") - ); + assert_eq!(clipboard(&mut harness).as_deref(), Some("- one bold\n- two")); } #[test] @@ -829,20 +751,15 @@ fn select_all_lights_every_row_of_a_wrapped_item() { let item = shapes .iter() .find_map(|clipped| match &clipped.shape { - egui::Shape::Text(text) if text.galley.text().starts_with("a sentence") => Some( - text.galley - .rows - .iter() - .map(|row| row.rect().translate(text.pos.to_vec2())), - ), + egui::Shape::Text(text) if text.galley.text().starts_with("a sentence") => { + Some(text.galley.rows.iter().map(|row| row.rect().translate(text.pos.to_vec2()))) + } _ => None, }) .expect("the item is painted") .collect::>(); assert!(item.len() >= 3, "wrapped on {} rows", item.len()); - let lit = crate::theme::palette(&harness.ctx) - .amber_fill - .gamma_multiply(0.3); + let lit = crate::theme::palette(&harness.ctx).amber_fill.gamma_multiply(0.3); for row in &item { let covered = shapes.iter().any(|clipped| { matches!(&clipped.shape, egui::Shape::Rect(shape) @@ -853,3 +770,274 @@ fn select_all_lights_every_row_of_a_wrapped_item() { assert!(covered, "row {row:?} is lit"); } } + +/// The caret where it was in the line, for what is typed next. +#[test] +fn shift_tab_takes_a_nested_item_back_from_the_middle_of_its_line() { + let (mut harness, id) = note("- one\n - two"); + at_end(&mut harness); + press(&mut harness, Modifiers::NONE, Key::ArrowLeft); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + type_in(&mut harness, "-"); + click_id(&mut harness, "editor-close"); + assert_eq!(stored(&harness, &id), "- one\n- tw-o"); +} + +/// A drag is known as one once the pointer left where it pressed: fast, some words further. +#[test] +fn a_drag_selects_from_where_it_was_pressed() { + let (mut harness, _) = note("hello world"); + let from = point_in(&harness, "hello world", 0); + let to = point_in(&harness, "hello world", 5); + let button = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + harness.event(egui::Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.step(); + for part in 1..=4_u8 { + harness.event(egui::Event::PointerMoved(from.lerp(to, f32::from(part) / 4.0))); + harness.step(); + } + harness.event(button(to, false)); + settle(&mut harness); + type_in(&mut harness, "bye"); + + assert_eq!(surface_text(&harness), "bye world"); +} + +/// The text with `|` where the keys leave the caret. +fn after(content: &str, keys: &[(Modifiers, Key)]) -> String { + let (mut harness, _) = note(content); + at_end(&mut harness); + for (modifiers, key) in keys { + press(&mut harness, *modifiers, *key); + } + type_in(&mut harness, "|"); + surface_text(&harness) +} + +#[test] +fn ctrl_moves_and_deletes_by_word() { + let word = Modifiers::COMMAND; + let select = Modifiers::COMMAND | Modifiers::SHIFT; + for (keys, text) in [ + ( + vec![(word, Key::ArrowLeft)], + "Un mot ici +|fin" + .to_owned(), + ), + ( + vec![(word, Key::ArrowLeft), (word, Key::ArrowLeft)], + "Un mot ici| +fin" + .to_owned(), + ), + ( + vec![(word, Key::Home), (word, Key::ArrowRight)], + "Un| mot ici +fin" + .to_owned(), + ), + ( + vec![(word, Key::Backspace)], + "Un mot ici +|" + .to_owned(), + ), + ( + vec![(word, Key::Home), (word, Key::Delete)], + "| mot ici +fin" + .to_owned(), + ), + ( + vec![(select, Key::ArrowLeft)], + "Un mot ici +|" + .to_owned(), + ), + ] { + assert_eq!( + after( + "Un mot ici + +fin", + &keys + ), + text, + "{keys:?}" + ); + } +} + +/// A family is one character to whoever reads it, three and their joiners to the text. +#[test] +fn a_character_of_several_is_walked_and_deleted_whole() { + let family = "\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}"; + let content = format!("a{family}b"); + let left = (Modifiers::NONE, Key::ArrowLeft); + + assert_eq!(after(&content, &[left, left]), format!("a|{family}b")); + assert_eq!(after(&content, &[left, (Modifiers::NONE, Key::Backspace)]), "a|b"); + assert_eq!(after(&content, &[left, left, (Modifiers::NONE, Key::Delete)]), "a|b"); +} + +/// From where End put it, not from where the caret once was. +#[test] +fn the_column_is_the_one_home_or_end_left() { + let down = (Modifiers::NONE, Key::ArrowDown); + let keys = [(Modifiers::COMMAND, Key::Home), down, (Modifiers::NONE, Key::End), down]; + + assert_eq!( + after( + "ab + +abcd + +abcdef", + &keys + ), + "ab +abcd +abcd|ef" + ); +} + +/// The whole of `content` selected, then the keys; what is stored. +fn formatted(content: &str, modifiers: Modifiers, key: Key) -> String { + let (mut harness, id) = note(content); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::A); + press(&mut harness, modifiers, key); + click_id(&mut harness, "editor-close"); + stored(&harness, &id) +} + +#[test] +fn each_shortcut_formats_what_is_selected() { + let (ctrl, shift, alt) = (Modifiers::COMMAND, Modifiers::SHIFT, Modifiers::ALT); + for (modifiers, key, markdown) in [ + (ctrl, Key::B, "**mot**"), + (ctrl, Key::I, "*mot*"), + (ctrl | shift, Key::S, "~~mot~~"), + (ctrl, Key::E, "`mot`"), + (ctrl | alt, Key::Num1, "# mot"), + (ctrl | alt, Key::Num6, "###### mot"), + (ctrl | shift, Key::Num7, "1. mot"), + (ctrl | shift, Key::Num8, "- mot"), + (ctrl | shift, Key::Num9, "- [ ] mot"), + (ctrl | shift, Key::B, "> mot"), + (ctrl | alt, Key::C, "```\nmot\n```"), + ] { + assert_eq!(formatted("mot", modifiers, key), markdown, "{modifiers:?} {key:?}"); + } + assert_eq!(formatted("## mot", ctrl | alt, Key::Num0), "mot"); +} + +/// Nothing selected, it is what is typed next that takes the mark. +#[test] +fn a_mark_asked_with_nothing_selected_is_the_next_word_s() { + for (key, shift, markdown) in + [(Key::I, false, "un *x*"), (Key::S, true, "un ~~x~~"), (Key::E, false, "un `x`")] + { + let (mut harness, id) = note("un "); + at_end(&mut harness); + let modifiers = if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }; + key_by_key(&mut harness, " "); + press(&mut harness, modifiers, key); + type_in(&mut harness, "x"); + click_id(&mut harness, "editor-close"); + assert_eq!(stored(&harness, &id), markdown, "{key:?}"); + } +} + +#[test] +fn a_line_broken_stays_in_its_paragraph() { + for modifiers in [Modifiers::SHIFT, Modifiers::COMMAND] { + let (mut harness, _) = note("un"); + at_end(&mut harness); + press(&mut harness, modifiers, Key::Enter); + type_in(&mut harness, "deux"); + assert_eq!(surface_text(&harness), "un\ndeux", "{modifiers:?}"); + click_id(&mut harness, "editor-close"); + } +} + +/// Its own undo, whatever runs after. +#[test] +fn redo_puts_back_what_undo_took() { + for (modifiers, key) in [(Modifiers::COMMAND, Key::Y), (Modifiers::COMMAND | Modifiers::SHIFT, Key::Z)] { + let (mut harness, _) = note("un"); + at_end(&mut harness); + type_in(&mut harness, " deux"); + press(&mut harness, Modifiers::COMMAND, Key::Z); + assert_eq!(surface_text(&harness), "un"); + press(&mut harness, modifiers, key); + assert_eq!(surface_text(&harness), "un deux", "{key:?}"); + } +} + +#[test] +fn a_tab_outside_a_list_is_text_and_shift_tab_takes_it_back() { + let (mut harness, _) = note("mot"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::Home); + press(&mut harness, Modifiers::NONE, Key::Tab); + assert_eq!(surface_text(&harness), "\tmot"); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + assert_eq!(surface_text(&harness), "mot"); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + assert_eq!(surface_text(&harness), "mot", "nothing more to take"); + type_in(&mut harness, "|"); + assert_eq!(surface_text(&harness), "|mot", "the caret stayed"); +} + +#[test] +fn shift_tab_takes_a_level_off_a_line_of_code() { + let (mut harness, _) = note("```rs\n let a = 1;\n```"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::End); + press(&mut harness, Modifiers::SHIFT, Key::Tab); + + assert_eq!(surface_text(&harness), "let a = 1;"); +} + +#[test] +fn the_menu_cuts_what_is_selected_and_asks_for_what_to_paste() { + let (mut harness, _) = note("hello world"); + click_id(&mut harness, "editor-rich"); + press(&mut harness, Modifiers::COMMAND, Key::Home); + press(&mut harness, Modifiers::SHIFT | Modifiers::COMMAND, Key::ArrowRight); + let menu = |harness: &mut Harness<'_>| { + harness.get_by(|node| node.author_id() == Some("editor-rich")).click_secondary(); + settle(harness); + }; + menu(&mut harness); + menu_entry(&harness, "rich-menu-cut"); + assert_eq!(clipboard(&mut harness).as_deref(), Some("hello")); + assert_eq!(surface_text(&harness), " world"); + + menu(&mut harness); + menu_entry(&harness, "rich-menu-paste"); + let mut asked = false; + for _ in 0..4 { + harness.step(); + asked |= harness + .output() + .viewport_output + .values() + .any(|viewport| viewport.commands.contains(&egui::ViewportCommand::RequestPaste)); + } + assert!(asked); + + menu(&mut harness); + menu_entry(&harness, "rich-menu-select-all"); + settle(&mut harness); + type_in(&mut harness, "x"); + assert_eq!(surface_text(&harness), "x"); +} diff --git a/crates/ui/src/notes/overlays/editor/rich/toolbar.rs b/crates/ui/src/notes/overlays/editor/rich/toolbar.rs index 70f414154..22b81f5bb 100644 --- a/crates/ui/src/notes/overlays/editor/rich/toolbar.rs +++ b/crates/ui/src/notes/overlays/editor/rich/toolbar.rs @@ -47,91 +47,31 @@ const GROUPS: [&[Entry]; 4] = { use keys::editor::rich as words; [ &[ - ( - Tool::Heading(1), - "rich-h1", - Face::Text("H1"), - words::HEADING1, - ), - ( - Tool::Heading(2), - "rich-h2", - Face::Text("H2"), - words::HEADING2, - ), - ( - Tool::Heading(3), - "rich-h3", - Face::Text("H3"), - words::HEADING3, - ), + (Tool::Heading(1), "rich-h1", Face::Text("H1"), words::HEADING1), + (Tool::Heading(2), "rich-h2", Face::Text("H2"), words::HEADING2), + (Tool::Heading(3), "rich-h3", Face::Text("H3"), words::HEADING3), ], &[ - ( - Tool::Mark(|| Mark::Bold), - "rich-bold", - Face::Icon(Icon::Bold), - words::BOLD, - ), - ( - Tool::Mark(|| Mark::Italic), - "rich-italic", - Face::Icon(Icon::Italic), - words::ITALIC, - ), - ( - Tool::Mark(|| Mark::Strike), - "rich-strike", - Face::Icon(Icon::Strike), - words::STRIKE, - ), - ( - Tool::Mark(|| Mark::Code), - "rich-code", - Face::Icon(Icon::Code), - words::CODE, - ), + (Tool::Mark(|| Mark::Bold), "rich-bold", Face::Icon(Icon::Bold), words::BOLD), + (Tool::Mark(|| Mark::Italic), "rich-italic", Face::Icon(Icon::Italic), words::ITALIC), + (Tool::Mark(|| Mark::Strike), "rich-strike", Face::Icon(Icon::Strike), words::STRIKE), + (Tool::Mark(|| Mark::Code), "rich-code", Face::Icon(Icon::Code), words::CODE), (Tool::Link, "rich-link", Face::Icon(Icon::Link), words::LINK), ], &[ - ( - Tool::List(ListKind::Bullet), - "rich-bullet", - Face::Icon(Icon::ListBullet), - words::BULLET_LIST, - ), + (Tool::List(ListKind::Bullet), "rich-bullet", Face::Icon(Icon::ListBullet), words::BULLET_LIST), ( Tool::List(ListKind::Ordered { start: 1 }), "rich-ordered", Face::Icon(Icon::ListOrdered), words::ORDERED_LIST, ), - ( - Tool::List(ListKind::Task), - "rich-tasks", - Face::Icon(Icon::ListTasks), - words::TASK_LIST, - ), - ( - Tool::Quote, - "rich-quote", - Face::Icon(Icon::Quote), - words::QUOTE, - ), + (Tool::List(ListKind::Task), "rich-tasks", Face::Icon(Icon::ListTasks), words::TASK_LIST), + (Tool::Quote, "rich-quote", Face::Icon(Icon::Quote), words::QUOTE), ], &[ - ( - Tool::CodeBlock, - "rich-codeBlock", - Face::Text("{ }"), - words::CODE_BLOCK, - ), - ( - Tool::Table, - "rich-table", - Face::Icon(Icon::Table), - words::TABLE, - ), + (Tool::CodeBlock, "rich-codeBlock", Face::Text("{ }"), words::CODE_BLOCK), + (Tool::Table, "rich-table", Face::Icon(Icon::Table), words::TABLE), ], ] }; @@ -143,21 +83,12 @@ const TABLE_TOOLS: [(Tool, &str, i18n::Key); 5] = { (Tool::RowAfter, "rich-rowAfter", words::ADD_ROW), (Tool::ColumnAfter, "rich-columnAfter", words::ADD_COLUMN), (Tool::DeleteRow, "rich-deleteRow", words::DELETE_ROW), - ( - Tool::DeleteColumn, - "rich-deleteColumn", - words::DELETE_COLUMN, - ), + (Tool::DeleteColumn, "rich-deleteColumn", words::DELETE_COLUMN), (Tool::DeleteTable, "rich-deleteTable", words::DELETE_TABLE), ] }; -pub(super) fn show( - ui: &mut Ui, - view: &mut RichEditor, - drawings: &[DrawingRef], - language: Language, -) { +pub(super) fn show(ui: &mut Ui, view: &mut RichEditor, drawings: &[DrawingRef], language: Language) { let tr = |key| i18n::translate(language, key, &[]); let mut inner = ui.new_child( UiBuilder::new() @@ -184,20 +115,12 @@ pub(super) fn show( drawing_menu(&mut inner, view, drawings, language); if let Some(fence) = code_language(view) { inner.add_space(gap::INSET); - language_menu( - &mut inner, - view, - &fence, - (&tr(keys::editor::rich::CODE_LANGUAGE), language), - ); + language_menu(&mut inner, view, &fence, (&tr(keys::editor::rich::CODE_LANGUAGE), language)); } if table::cell_of(&view.document, &view.selection.head.path).is_some() { inner.add_space(gap::INSET); for (tool, author_id, key) in TABLE_TOOLS { - let clicked = Button::new(&tr(key), author_id) - .kind(Kind::Quiet) - .show(&mut inner) - .clicked(); + let clicked = Button::new(&tr(key), author_id).kind(Kind::Quiet).show(&mut inner).clicked(); if clicked { run(view, tool); view.refocus = true; @@ -208,18 +131,11 @@ pub(super) fn show( fn button(ui: &mut Ui, face: Face, name: &str, author_id: &str, on: bool) -> bool { match face { - Face::Icon(icon) => IconButton::new(icon, name, author_id) - .pressed(on) - .show(ui) - .clicked(), + Face::Icon(icon) => IconButton::new(icon, name, author_id).pressed(on).show(ui).clicked(), Face::Text(text) => { - let response = Button::new(text, author_id) - .kind(Kind::Quiet) - .armed(on) - .show(ui); + let response = Button::new(text, author_id).kind(Kind::Quiet).armed(on).show(ui); let name = name.to_owned(); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(name)); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(name)); response.clicked() } } @@ -259,12 +175,8 @@ fn drawing_menu(ui: &mut Ui, view: &mut RichEditor, drawings: &[DrawingRef], lan src: format!("{DRAWING_SOURCE}{}", drawing.id), width: None, }; - let pasted = Document { - blocks: vec![image], - }; - view.change(Step::Other, |document, selection| { - edit::insert_document(document, selection, pasted) - }); + let pasted = Document { blocks: vec![image] }; + view.change(Step::Other, |document, selection| edit::insert_document(document, selection, pasted)); view.refocus = true; } @@ -275,10 +187,7 @@ fn language_menu(ui: &mut Ui, view: &mut RichEditor, fence: &str, words: (&str, .into_iter() .map(|code| (code, crate::notes::language::label(code))) .collect(); - let hints: Vec<&str> = Code::ALL - .into_iter() - .map(crate::notes::language::hint) - .collect(); + let hints: Vec<&str> = Code::ALL.into_iter().map(crate::notes::language::hint).collect(); let mut chosen = fence.parse::().unwrap_or(Code::Txt); if ChoiceMenu::new(label, "rich-code-language", &options) .hints(&hints) @@ -321,12 +230,9 @@ fn active(view: &RichEditor, tool: Tool) -> bool { matches!(block, Block::List { kind: at, .. } if std::mem::discriminant(&at) == std::mem::discriminant(&kind)) }), - Tool::Quote => matches!( - head.path - .first() - .and_then(|top| view.document.blocks.get(*top)), - Some(Block::Quote(_)) - ), + Tool::Quote => { + matches!(head.path.first().and_then(|top| view.document.blocks.get(*top)), Some(Block::Quote(_))) + } Tool::CodeBlock => code_language(view).is_some(), _ => false, } @@ -342,14 +248,11 @@ pub(super) fn run(view: &mut RichEditor, tool: Tool) { Tool::Mark(mark) => view.toggle(&mark()), Tool::Link => { let text = edit::selected_text(&view.document, &view.selection); - view.link = Some(LinkForm { - text, - address: view.marks_here().link.unwrap_or_default(), - }); + view.link = Some(LinkForm { text, address: view.marks_here().link.unwrap_or_default() }); + } + Tool::List(kind) => { + view.change(Step::Other, |document, selection| edit::toggle_list(document, selection, kind)); } - Tool::List(kind) => view.change(Step::Other, |document, selection| { - edit::toggle_list(document, selection, kind) - }), Tool::Quote => view.change(Step::Other, edit::toggle_quote), Tool::CodeBlock => view.change(Step::Other, edit::toggle_code_block), Tool::Table => view.change(Step::Other, table::insert), @@ -378,9 +281,7 @@ pub(super) fn link_form(ui: &mut Ui, view: &mut RichEditor, language: Language) let address_name = tr(words::LINK_ADDRESS); inner.scope(|ui| { ui.set_width(200.0); - TextField::new(&mut form.text, &text_name, "rich-link-text") - .compact() - .show(ui); + TextField::new(&mut form.text, &text_name, "rich-link-text").compact().show(ui); }); let address = TextField::new(&mut form.address, &address_name, "rich-link-address") .compact() @@ -400,20 +301,10 @@ pub(super) fn link_form(ui: &mut Ui, view: &mut RichEditor, language: Language) view.refocus = true; let href = Some(address.trim().to_owned()).filter(|href| !href.is_empty()); if view.selection.is_empty() && !text.is_empty() { - let marks = Marks { - link: href, - ..Marks::default() - }; - view.change(Step::Other, |document, selection| { - edit::insert_text(document, selection, &text, &marks) - }); + let marks = Marks { link: href, ..Marks::default() }; + view.change(Step::Other, |document, selection| edit::insert_text(document, selection, &text, &marks)); } else { view.record(Step::Other); - edit::set_mark( - &mut view.document, - &view.selection, - &Mark::Link(href.clone()), - href.is_some(), - ); + edit::set_mark(&mut view.document, &view.selection, &Mark::Link(href.clone()), href.is_some()); } } diff --git a/crates/ui/src/notes/overlays/editor/search_bar.rs b/crates/ui/src/notes/overlays/editor/search_bar.rs index f779c6d3e..baa75cc3e 100644 --- a/crates/ui/src/notes/overlays/editor/search_bar.rs +++ b/crates/ui/src/notes/overlays/editor/search_bar.rs @@ -64,19 +64,13 @@ impl Searchable for Editor { } fn replace_one(&mut self, query: &Query) -> Option { - let edited = self - .buffer - .replace_one(query) - .map(|edited| edited.first_line); + let edited = self.buffer.replace_one(query).map(|edited| edited.first_line); self.reveal_selection(); edited } fn replace_all(&mut self, query: &Query) -> Option { - self.buffer - .replace_all(query) - .1 - .map(|edited| edited.first_line) + self.buffer.replace_all(query).1.map(|edited| edited.first_line) } fn focus(&mut self) { @@ -135,8 +129,7 @@ pub(super) fn show( } }); let rect = ui.min_rect(); - ui.painter() - .hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom(), Stroke::new(1.0, p.line_soft)); if ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) { bar.close(); editor.focus(); @@ -177,45 +170,14 @@ fn find_row( seek_on_enter(ui, bar, editor); } count_label(ui, count, language); - toggle( - ui, - &mut bar.query.case_sensitive, - "Aa", - &tr(keys::editor::search::MATCH_CASE), - "search-case", - ); - toggle( - ui, - &mut bar.query.whole_word, - "ab", - &tr(keys::editor::search::WHOLE_WORD), - "search-word", - ); - toggle( - ui, - &mut bar.query.regexp, - ".*", - &tr(keys::editor::search::REGEXP), - "search-regexp", - ); + toggle(ui, &mut bar.query.case_sensitive, "Aa", &tr(keys::editor::search::MATCH_CASE), "search-case"); + toggle(ui, &mut bar.query.whole_word, "ab", &tr(keys::editor::search::WHOLE_WORD), "search-word"); + toggle(ui, &mut bar.query.regexp, ".*", &tr(keys::editor::search::REGEXP), "search-regexp"); for (icon, key, author_id, direction) in [ - ( - Icon::ArrowUp, - keys::editor::search::PREVIOUS, - "search-previous", - Direction::Backward, - ), - ( - Icon::ArrowDown, - keys::editor::search::NEXT, - "search-next", - Direction::Forward, - ), + (Icon::ArrowUp, keys::editor::search::PREVIOUS, "search-previous", Direction::Backward), + (Icon::ArrowDown, keys::editor::search::NEXT, "search-next", Direction::Forward), ] { - if IconButton::new(icon, &tr(key), author_id) - .show(ui) - .clicked() - { + if IconButton::new(icon, &tr(key), author_id).show(ui).clicked() { step(bar, editor, direction); } } @@ -265,10 +227,7 @@ fn replace_row( /// Enter: the next match; Shift+Enter: the previous one. fn seek_on_enter(ui: &Ui, bar: &SearchBar, editor: &mut impl Searchable) { let (next, previous) = ui.input_mut(|input| { - ( - input.consume_key(Modifiers::NONE, Key::Enter), - input.consume_key(Modifiers::SHIFT, Key::Enter), - ) + (input.consume_key(Modifiers::NONE, Key::Enter), input.consume_key(Modifiers::SHIFT, Key::Enter)) }); if next { step(bar, editor, Direction::Forward); @@ -281,13 +240,7 @@ fn step(bar: &SearchBar, editor: &mut impl Searchable, direction: Direction) { editor.seek(&bar.query, SeekFrom::Past, direction); } -fn field( - ui: &mut Ui, - value: &mut String, - name: &str, - author_id: &str, - valid: bool, -) -> egui::Response { +fn field(ui: &mut Ui, value: &mut String, name: &str, author_id: &str, valid: bool) -> egui::Response { let p = palette(ui.ctx()); let edge = if valid { p.line } else { p.red }; egui::Frame::new() @@ -316,26 +269,11 @@ fn field( fn count_label(ui: &mut Ui, count: Count, language: Language) { let p = palette(ui.ctx()); let total = u32::try_from(count.total).unwrap_or(u32::MAX); - let mut words = i18n::translate( - language, - keys::editor::search::MATCHES, - &[("count", total.into())], - ); + let mut words = i18n::translate(language, keys::editor::search::MATCHES, &[("count", total.into())]); if let Some(current) = count.current { - words = format!( - "{current} / {}{}", - count.total, - if count.capped { "+" } else { "" } - ); + words = format!("{current} / {}{}", count.total, if count.capped { "+" } else { "" }); } - let galley = widgets::text( - ui, - &words, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::META, 400.0, FontFamily::Monospace, p.text_2); let response = ui.label(galley); address(ui, &response, "search-count"); } @@ -351,16 +289,12 @@ fn toggle(ui: &mut Ui, on: &mut bool, glyph: &str, name: &str, author_id: &str) egui::CornerRadius::same(radius::CONTROL), ); if *on { - ui.painter().rect_filled( - response.rect, - egui::CornerRadius::same(radius::CONTROL), - p.bg_3, - ); + ui.painter() + .rect_filled(response.rect, egui::CornerRadius::same(radius::CONTROL), p.bg_3); } let ink = if *on { p.amber_text } else { p.text_1 }; let galley = widgets::text(ui, glyph, font::CONTROL, 600.0, FontFamily::Monospace, ink); - ui.painter() - .galley(response.rect.center() - galley.size() / 2.0, galley, ink); + ui.painter().galley(response.rect.center() - galley.size() / 2.0, galley, ink); if response.clicked() { *on = !*on; } diff --git a/crates/ui/src/notes/overlays/editor/tests.rs b/crates/ui/src/notes/overlays/editor/tests.rs index 7b0cc4e83..c391bd29a 100644 --- a/crates/ui/src/notes/overlays/editor/tests.rs +++ b/crates/ui/src/notes/overlays/editor/tests.rs @@ -7,27 +7,16 @@ use crate::testing; fn stored(harness: &egui_kittest::Harness<'_, Bench>, id: &str) -> DisplayNote { let id = id.to_owned(); - engine::db::run_here(harness.state().backend.engine(), move |engine| { - engine::notes::get_note(engine, &id) - }) - .unwrap() + engine::db::run_here(harness.state().backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() } fn written(harness: &egui_kittest::Harness<'_, Bench>) -> usize { - harness - .state() - .state - .notes_query - .view() - .unwrap() - .cards() - .count() + harness.state().state.notes_query.view().unwrap().cards().count() } fn is_open(harness: &egui_kittest::Harness<'_, Bench>) -> bool { - harness - .query_by(|node| node.author_id() == Some("editor-title")) - .is_some() + harness.query_by(|node| node.author_id() == Some("editor-title")).is_some() } /// The menu's entry, not the rail's row of the same name under the editor. @@ -42,9 +31,7 @@ fn menu_entry(harness: &mut egui_kittest::Harness<'_, Bench>, name: &str) { fn type_into(harness: &mut egui_kittest::Harness<'_, Bench>, id: &str, text: &str) { click_id(harness, id); - harness - .get_by(|node| node.author_id() == Some(id)) - .type_text(text); + harness.get_by(|node| node.author_id() == Some(id)).type_text(text); settle(harness); } @@ -201,11 +188,7 @@ fn folding_the_header_leaves_its_summary_and_is_remembered() { click_id(&mut harness, "note-card-open"); click_id(&mut harness, "editor-fold-header"); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-source")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("editor-source")).is_none()); harness.get_by(|node| node.author_id() == Some("editor-header-summary")); assert!(harness.state().state.settings.editor_header_folded); click_id(&mut harness, "editor-header-summary"); @@ -250,10 +233,7 @@ fn a_deadline_picked_makes_the_note_due_and_clearing_it_makes_it_permanent() { panic!("the note has no deadline"); }; let today = chrono::Local::now().date_naive(); - assert_eq!( - at.with_timezone(&chrono::Local).date_naive(), - today + chrono::Days::new(8) - ); + assert_eq!(at.with_timezone(&chrono::Local).date_naive(), today + chrono::Days::new(8)); harness.get_by(|node| node.author_id() == Some("editor-lifecycle")); click_id(&mut harness, "editor-deadline"); @@ -277,9 +257,7 @@ fn a_day_of_the_month_is_picked_by_the_pointer_and_delete_clears_it() { let day = chrono::Local::now().date_naive().with_day(1).unwrap() + chrono::Months::new(1); let label = i18n::format::date_long(day, i18n::Language::En); harness - .get_by(|node| { - node.author_id() == Some("date-day") && node.label().as_deref() == Some(&label) - }) + .get_by(|node| node.author_id() == Some("date-day") && node.label().as_deref() == Some(&label)) .click(); settle(&mut harness); let NoteLifecycle::Expires { at } = stored(&harness, &id).lifecycle else { @@ -287,9 +265,7 @@ fn a_day_of_the_month_is_picked_by_the_pointer_and_delete_clears_it() { }; assert_eq!(at.with_timezone(&chrono::Local).date_naive(), day); - harness - .get_by(|node| node.author_id() == Some("editor-deadline")) - .focus(); + harness.get_by(|node| node.author_id() == Some("editor-deadline")).focus(); harness.key_press(egui::Key::Delete); settle(&mut harness); assert_eq!(stored(&harness, &id).lifecycle, NoteLifecycle::Permanent); @@ -301,10 +277,7 @@ fn a_note_is_filed_moved_and_prioritised_from_its_header() { use engine::notes::priority::Priority; let (backend, profile) = testing::unlocked(); let note = testing::note(&backend, "psql"); - let home = crate::notes::bench::spaces_of_backend(&backend) - .into_iter() - .next() - .unwrap(); + let home = crate::notes::bench::spaces_of_backend(&backend).into_iter().next().unwrap(); folder(&backend, &home, None, "Databases"); space(&backend, "Archive"); let id = note.id.clone(); @@ -335,10 +308,7 @@ fn a_draft_filed_prioritised_and_moved_is_written_with_all_of_it() { use engine::notes::priority::Priority; let (backend, profile) = testing::unlocked(); testing::note(&backend, "psql"); - let home = crate::notes::bench::spaces_of_backend(&backend) - .into_iter() - .next() - .unwrap(); + let home = crate::notes::bench::spaces_of_backend(&backend).into_iter().next().unwrap(); folder(&backend, &home, None, "Databases"); space(&backend, "Archive"); let mut harness = area(backend, profile); @@ -395,9 +365,7 @@ fn copying_from_the_editor_writes_first_and_full_screen_is_remembered() { click_id(&mut harness, "note-card-open"); type_into(&mut harness, "editor-body", "\nSELECT 2;"); - harness - .get_by(|node| node.author_id() == Some("editor-copy")) - .click(); + harness.get_by(|node| node.author_id() == Some("editor-copy")).click(); let mut copied = None; for _ in 0..60 { harness.step(); @@ -430,16 +398,9 @@ fn expanded_the_note_leaves_the_header_and_its_sidebar_toggle_in_reach() { click_id(&mut harness, "note-card-open"); click_id(&mut harness, "editor-fullscreen"); - let toggle = harness - .get_by(|node| node.author_id() == Some("library-rail-toggle")) - .rect(); - let expand = harness - .get_by(|node| node.author_id() == Some("editor-fullscreen")) - .rect(); - assert!( - toggle.bottom() < expand.top(), - "{toggle:?} above {expand:?}" - ); + let toggle = harness.get_by(|node| node.author_id() == Some("library-rail-toggle")).rect(); + let expand = harness.get_by(|node| node.author_id() == Some("editor-fullscreen")).rect(); + assert!(toggle.bottom() < expand.top(), "{toggle:?} above {expand:?}"); click_id(&mut harness, "library-rail-toggle"); assert!(!harness.state().state.settings.rail_shown); @@ -447,9 +408,7 @@ fn expanded_the_note_leaves_the_header_and_its_sidebar_toggle_in_reach() { } /// Wide enough for the panel beside two columns of cards. -fn wide( - mut harness: egui_kittest::Harness<'static, Bench>, -) -> egui_kittest::Harness<'static, Bench> { +fn wide(mut harness: egui_kittest::Harness<'static, Bench>) -> egui_kittest::Harness<'static, Bench> { harness.set_size(egui::vec2(1_440.0, 800.0)); settle(&mut harness); harness @@ -471,13 +430,7 @@ fn the_header_spans_the_area_whether_the_note_is_beside_the_cards_or_expanded() testing::note(&backend, "psql"); let mut harness = wide(area(backend, profile)); let controls = |harness: &egui_kittest::Harness<'_, Bench>| { - [ - "new-note", - "search-input", - "facets-toggle", - "library-rail-toggle", - ] - .map(|id| rect_of(harness, id)) + ["new-note", "search-input", "facets-toggle", "library-rail-toggle"].map(|id| rect_of(harness, id)) }; let closed = controls(&harness); @@ -509,11 +462,7 @@ fn a_note_opens_beside_the_cards_and_expands_over_them() { click_id(&mut harness, "editor-fullscreen"); assert_eq!(cards(&harness), 0); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-breadcrumb")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("editor-breadcrumb")).is_some()); click_id(&mut harness, "editor-back-to-cards"); assert_eq!(cards(&harness), 1); @@ -529,9 +478,7 @@ fn moving_to_another_note_keeps_the_panel_in_place() { testing::note(&backend, "second"); let mut harness = wide(area(backend, profile)); harness - .get_by(|node| { - node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("first") - }) + .get_by(|node| node.author_id() == Some("note-card-open") && node.label().as_deref() == Some("first")) .click(); settle(&mut harness); let header = rect_of(&harness, "new-note"); @@ -545,12 +492,7 @@ fn moving_to_another_note_keeps_the_panel_in_place() { harness.step(); let now = rect_of(&harness, "new-note"); assert_eq!(now, header, "the cards' width moved at frame {frame}"); - let read = harness - .state() - .state - .editor - .opened() - .and_then(|open| open.note()); + let read = harness.state().state.editor.opened().and_then(|open| open.note()); if read.is_some_and(|note| note.title == "second") { return; } @@ -643,16 +585,10 @@ fn j_and_k_step_through_the_cards_and_escape_steps_back() { harness.key_press(egui::Key::J); settle(&mut harness); - assert_eq!( - harness.state().state.editor.open_id(), - Some(order[1].as_str()) - ); + assert_eq!(harness.state().state.editor.open_id(), Some(order[1].as_str())); harness.key_press(egui::Key::K); settle(&mut harness); - assert_eq!( - harness.state().state.editor.open_id(), - Some(order[0].as_str()) - ); + assert_eq!(harness.state().state.editor.open_id(), Some(order[0].as_str())); click_id(&mut harness, "editor-fullscreen"); let position = harness @@ -662,10 +598,7 @@ fn j_and_k_step_through_the_cards_and_escape_steps_back() { .unwrap_or_default(); assert_eq!(position, "1 / 3"); click_id(&mut harness, "editor-next"); - assert_eq!( - harness.state().state.editor.open_id(), - Some(order[1].as_str()) - ); + assert_eq!(harness.state().state.editor.open_id(), Some(order[1].as_str())); // Stepped to, the note leaves the focus where it was: one Escape leaves full screen. harness.key_press(egui::Key::Escape); @@ -696,9 +629,7 @@ fn full_header(width: f32) -> egui_kittest::Harness<'static, Bench> { let lines = engine::folders::board::PreviewLines::default(); let ids = std::slice::from_ref(¬e); engine::folders::file_notes(engine, ids, Some(&folder.id), lines)?; - let at = chrono::DateTime::parse_from_rfc3339("2026-12-24T22:00:00Z") - .unwrap() - .to_utc(); + let at = chrono::DateTime::parse_from_rfc3339("2026-12-24T22:00:00Z").unwrap().to_utc(); let long = "a-tag-longer-than-a-whole-line-of-the-panel-at-its-narrowest-which-is-cut"; let tags = ["infrastructure", "certificates", "staging", "openssl", long]; engine::notes::update_note( @@ -732,11 +663,7 @@ fn everything_of_the_header_is_inside_the_panel_at_its_narrowest() { // Beside the cards, then over them in the narrowest window. for width in [1_220.0, 640.0] { let harness = full_header(width); - let count = |id: &str| { - harness - .query_all_by(|node| node.author_id() == Some(id)) - .count() - }; + let count = |id: &str| harness.query_all_by(|node| node.author_id() == Some(id)).count(); assert_eq!(count("editor-tag"), 5); assert_eq!(count("attachment-remove"), 2); for id in ["editor-lifecycle", "editor-deadline", "editor-folder"] { @@ -747,11 +674,7 @@ fn everything_of_the_header_is_inside_the_panel_at_its_narrowest() { node.author_id() .is_some_and(|id| id.starts_with("editor-") || id.starts_with("attachment-")) }) { - let id = node - .accesskit_node() - .author_id() - .unwrap_or_default() - .to_owned(); + let id = node.accesskit_node().author_id().unwrap_or_default().to_owned(); let rect = node.rect(); assert!( rect.right() <= width && (rect.left() >= left || id == "editor-panel-edge"), @@ -802,15 +725,8 @@ fn beside_the_cards_the_seldom_used_wait_in_the_menu() { .query_all_by(|node| node.author_id() == Some("note-card")) .map(|node| node.rect()) .collect(); - assert!( - cards.len() == 2 && (cards[0].top() - cards[1].top()).abs() < 1.0, - "{cards:?}" - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-delete")) - .is_none() - ); + assert!(cards.len() == 2 && (cards[0].top() - cards[1].top()).abs() < 1.0, "{cards:?}"); + assert!(harness.query_by(|node| node.author_id() == Some("editor-delete")).is_none()); click_id(&mut harness, "editor-more"); click_id(&mut harness, "editor-delete"); @@ -857,9 +773,7 @@ fn the_panels_edge_moves_and_the_cards_follow() { }); harness.run_steps(1); for step in 1..=8_u8 { - harness.event(egui::Event::PointerMoved( - edge + egui::vec2(20.0 * f32::from(step), 0.0), - )); + harness.event(egui::Event::PointerMoved(edge + egui::vec2(20.0 * f32::from(step), 0.0))); harness.run_steps(1); } harness.event(egui::Event::PointerButton { @@ -892,11 +806,7 @@ fn expanded_the_details_stand_beside_the_body_and_can_be_put_away() { ); click_id(&mut harness, "editor-details"); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-space")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("editor-space")).is_none()); assert!(!harness.state().state.settings.editor_details_open); } @@ -911,3 +821,41 @@ fn expanded_without_room_for_the_details_the_header_holds_them() { assert!(rect_of(&harness, "editor-space").bottom() < rect_of(&harness, "editor-body").top()); } + +#[test] +fn a_tag_is_taken_off_by_its_cross() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let patch = engine::notes::model::NotePatch { + tags: Some(vec!["db".to_owned(), "ops".to_owned()]), + ..Default::default() + }; + let at = id.clone(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); + let mut harness = crate::notes::bench::expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + harness + .query_all_by(|node| node.author_id() == Some("editor-tag-remove")) + .next() + .unwrap() + .click(); + settle(&mut harness); + + assert_eq!(stored(&harness, &id).tags, ["ops"]); +} + +/// Enter keeps the field for the next one. +#[test] +fn tags_are_added_one_after_the_other() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + let mut harness = crate::notes::bench::expanded_area(backend, profile); + click_id(&mut harness, "note-card-open"); + click_id(&mut harness, "editor-tag-add"); + for tag in ["db", "ops"] { + crate::notes::bench::type_and_enter(&mut harness, "editor-tag-add", tag); + } + + assert_eq!(stored(&harness, &id).tags, ["db", "ops"]); +} diff --git a/crates/ui/src/notes/overlays/folder_prompt.rs b/crates/ui/src/notes/overlays/folder_prompt.rs index 6dffd3a32..aa7154217 100644 --- a/crates/ui/src/notes/overlays/folder_prompt.rs +++ b/crates/ui/src/notes/overlays/folder_prompt.rs @@ -16,29 +16,20 @@ const WIDTH: f32 = 380.0; pub(in crate::notes) fn show(ui: &Ui, state: &AppState, name: &mut String, actions: &mut Actions) { let zone = state.board.drawn_zone().is_some(); - let Some(space) = state - .spaces - .active_space() - .filter(|_| state.folders.naming() || zone) - else { + let Some(space) = state.spaces.active_space().filter(|_| state.folders.naming() || zone) else { name.clear(); return; }; let _p = palette(ui.ctx()); - let shown = crate::widgets::modal_panel(ui.ctx(), Id::unique("folder-name-prompt"), |ui| { - prompt(ui, state, name) - }); + let shown = + crate::widgets::modal_panel(ui.ctx(), Id::unique("folder-name-prompt"), |ui| prompt(ui, state, name)); let named = shown.inner.filter(|()| !name.trim().is_empty()); if let Some(()) = named { let name = name.trim().to_owned(); actions.push(Action::Notes(if zone { Asked::NameZone(name) } else { - Asked::CreateFolder { - space_id: space.to_owned(), - parent_id: None, - name, - } + Asked::CreateFolder { space_id: space.to_owned(), parent_id: None, name } })); } if named.is_some() || shown.should_close() || shown.inner.is_some() { @@ -55,14 +46,7 @@ fn prompt(ui: &mut Ui, state: &AppState, name: &mut String) -> Option<()> { ui.set_width(WIDTH.min(ui.ctx().content_rect().width() * 0.9)); ui.spacing_mut().item_spacing.y = gap::GROUPS; let title = tr(keys::board::NAME_THE_ZONE); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); let (rect, _) = ui.allocate_exact_size(words.size(), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); let hint = ui.add( @@ -74,13 +58,9 @@ fn prompt(ui: &mut Ui, state: &AppState, name: &mut String) -> Option<()> { .wrap(), ); widgets::address(ui, &hint, "folder-name-hint"); - let (label, placeholder) = ( - tr(keys::folders::NEW_FOLDER_LABEL), - tr(keys::folders::NEW_FOLDER_PLACEHOLDER), - ); - let field = TextField::new(name, &label, "folder-name-input") - .hint(&placeholder) - .show(ui); + let (label, placeholder) = + (tr(keys::folders::NEW_FOLDER_LABEL), tr(keys::folders::NEW_FOLDER_PLACEHOLDER)); + let field = TextField::new(name, &label, "folder-name-input").hint(&placeholder).show(ui); if !field.has_focus() && name.is_empty() { field.request_focus(); } diff --git a/crates/ui/src/notes/overlays/image_lightbox.rs b/crates/ui/src/notes/overlays/image_lightbox.rs index 97634199a..50ceeb209 100644 --- a/crates/ui/src/notes/overlays/image_lightbox.rs +++ b/crates/ui/src/notes/overlays/image_lightbox.rs @@ -39,22 +39,15 @@ pub(in crate::notes) fn show(ui: &Ui, state: &AppState, actions: &mut Actions) { ui.label(RichText::new(name).size(font::LABEL).color(p.text_1)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { let close = i18n::translate(language, keys::attachments::CLOSE_ZOOM, &[]); - IconButton::new(Icon::X, &close, "lightbox-close") - .show(ui) - .clicked() + IconButton::new(Icon::X, &close, "lightbox-close").show(ui).clicked() }) .inner }) .inner; let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); paint(ui, rect, texture.id()); - let label = i18n::translate( - language, - keys::attachments::PREVIEW, - &[("name", name.into())], - ); - ui.ctx() - .accesskit_node_builder(response.id, |node| node.set_label(label)); + let label = i18n::translate(language, keys::attachments::PREVIEW, &[("name", name.into())]); + ui.ctx().accesskit_node_builder(response.id, |node| node.set_label(label)); widgets::address(ui, &response, "lightbox-image"); closed }); diff --git a/crates/ui/src/notes/overlays/placeholder_form.rs b/crates/ui/src/notes/overlays/placeholder_form.rs index 94c875ee5..13dcd9c17 100644 --- a/crates/ui/src/notes/overlays/placeholder_form.rs +++ b/crates/ui/src/notes/overlays/placeholder_form.rs @@ -32,12 +32,7 @@ fn ask(actions: &mut Actions, asked: Fill) { actions.push(Action::Notes(Asked::Fill(asked))); } -pub(in crate::notes) fn show( - ui: &Ui, - state: &AppState, - view: &mut FillView, - actions: &mut Actions, -) { +pub(in crate::notes) fn show(ui: &Ui, state: &AppState, view: &mut FillView, actions: &mut Actions) { let Some(note) = state.fill.target() else { *view = FillView::default(); return; @@ -45,11 +40,7 @@ pub(in crate::notes) fn show( if view.note.as_deref() != Some(note.id.as_str()) { *view = FillView { note: Some(note.id.clone()), - values: note - .placeholders - .iter() - .map(|field| field.value.clone()) - .collect(), + values: note.placeholders.iter().map(|field| field.value.clone()).collect(), focus: true, }; } @@ -71,32 +62,15 @@ fn form(ui: &mut Ui, state: &AppState, note: &DisplayNote, view: &mut FillView) ui.set_width(WIDTH.min(ui.ctx().content_rect().width() * 0.9)); ui.spacing_mut().item_spacing.y = gap::GROUPS; let title = tr(keys::placeholders::TITLE); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); let (rect, _) = ui.allocate_exact_size(words.size(), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); // A Note holding a field was called a snippet. - let hint = if note.kind == NoteKind::Snippet { - keys::placeholders::HINT - } else { - keys::placeholders::HINT_NOTE - }; + let hint = + if note.kind == NoteKind::Snippet { keys::placeholders::HINT } else { keys::placeholders::HINT_NOTE }; let count = u32::try_from(note.placeholders.len()).unwrap_or(u32::MAX); let hint = i18n::translate(language, hint, &[("count", count.into())]); - let said = ui.add( - egui::Label::new( - egui::RichText::new(hint) - .size(font::CONTROL) - .color(p.text_2), - ) - .wrap(), - ); + let said = ui.add(egui::Label::new(egui::RichText::new(hint).size(font::CONTROL).color(p.text_2)).wrap()); widgets::address(ui, &said, "placeholder-form-hint"); let mut entered = false; // The first field still empty is where typing goes: Enter then copies what was typed. @@ -113,8 +87,7 @@ fn form(ui: &mut Ui, state: &AppState, note: &DisplayNote, view: &mut FillView) entered |= input.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); } let top = ui.cursor().top(); - ui.painter() - .hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); let mut asked = None; ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; @@ -155,21 +128,12 @@ pub(in crate::notes) fn field_row( ui.spacing_mut().item_spacing.x = gap::INSET; // The braces tie the row to the token in the text; the field's name is its label. let name = format!("{{{{{}}}}}", field.name); - let galley = widgets::text( - ui, - &name, - font::LABEL, - 400.0, - FontFamily::Monospace, - p.amber_text, - ); + let galley = widgets::text(ui, &name, font::LABEL, 400.0, FontFamily::Monospace, p.amber_text); let (rect, _) = ui.allocate_exact_size(vec2(NAME_WIDTH, 28.0), Sense::hover()); let at_y = rect.center().y - galley.size().y / 2.0; - ui.painter().with_clip_rect(rect).galley( - egui::pos2(rect.left(), at_y), - galley, - p.amber_text, - ); + ui.painter() + .with_clip_rect(rect) + .galley(egui::pos2(rect.left(), at_y), galley, p.amber_text); let label = i18n::translate( language, keys::placeholders::FIELD_LABEL, @@ -207,19 +171,14 @@ mod tests { fn opened() -> (Harness<'static, Bench>, String) { let (backend, profile) = testing::unlocked(); let id = testing::note(&backend, "psql").id.clone(); - let patch = NotePatch { - content: Some(BODY.into()), - ..NotePatch::default() - }; + let patch = NotePatch { content: Some(BODY.into()), ..NotePatch::default() }; let edited = id.clone(); engine::db::run_here(backend.engine(), move |engine| { engine::notes::update_note(engine, &edited, &patch) }) .unwrap(); let mut harness = area(backend, profile); - harness - .get_by(|node| node.author_id() == Some("note-card-open")) - .hover(); + harness.get_by(|node| node.author_id() == Some("note-card-open")).hover(); settle(&mut harness); click_id(&mut harness, "note-card-fill"); (harness, id) @@ -228,19 +187,19 @@ mod tests { /// `author_id` clicked, then what reached the clipboard: the frame that copies is not the /// last one a settle leaves, so each frame's output is read. fn copy_from(harness: &mut Harness<'_, Bench>, author_id: &str) -> Option { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .click(); + harness.get_by(|node| node.author_id() == Some(author_id)).click(); for _ in 0..60 { harness.step(); harness.state().backend.settle(); - let copied = - harness.output().platform_output.commands.iter().find_map( - |command| match command { - egui::OutputCommand::CopyText(text) => Some(text.clone()), - _ => None, - }, - ); + let copied = harness + .output() + .platform_output + .commands + .iter() + .find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }); if copied.is_some() { settle(harness); return copied; @@ -255,10 +214,7 @@ mod tests { engine::notes::get_note(engine, &id) }) .unwrap(); - note.placeholders - .into_iter() - .map(|field| (field.name, field.value)) - .collect() + note.placeholders.into_iter().map(|field| (field.name, field.value)).collect() } #[test] @@ -283,9 +239,7 @@ mod tests { let copied = copy_from(&mut harness, "placeholder-submit"); assert_eq!(copied.as_deref(), Some("psql -h db.internal -p 5432 -U ")); - let host = stored(&harness, &id) - .into_iter() - .find(|(name, _)| name == "host"); + let host = stored(&harness, &id).into_iter().find(|(name, _)| name == "host"); assert_eq!(host.map(|(_, value)| value).as_deref(), Some("db.internal")); } @@ -295,9 +249,7 @@ mod tests { let copied = copy_from(&mut harness, "placeholder-copy-raw"); assert_eq!(copied.as_deref(), Some(BODY)); - harness - .get_by(|node| node.author_id() == Some("note-card-open")) - .hover(); + harness.get_by(|node| node.author_id() == Some("note-card-open")).hover(); settle(&mut harness); click_id(&mut harness, "note-card-fill"); harness @@ -307,11 +259,7 @@ mod tests { .type_text("discarded"); click_id(&mut harness, "placeholder-cancel"); - assert!( - stored(&harness, &id) - .iter() - .all(|(_, value)| value.is_empty()) - ); + assert!(stored(&harness, &id).iter().all(|(_, value)| value.is_empty())); assert!(!harness.state().state.fill.is_open()); } } diff --git a/crates/ui/src/notes/overlays/presentation.rs b/crates/ui/src/notes/overlays/presentation.rs index 38aee299c..a609907bb 100644 --- a/crates/ui/src/notes/overlays/presentation.rs +++ b/crates/ui/src/notes/overlays/presentation.rs @@ -9,8 +9,8 @@ mod tests; use crate::theme::tokens::{font, gap}; use egui::text::LayoutJob; use egui::{ - Align2, CornerRadius, FontId, Id, Key, Modifiers, Rect, Sense, TextFormat, Ui, UiBuilder, Vec2, - pos2, vec2, + Align2, CornerRadius, FontId, Id, Key, Modifiers, Rect, Sense, TextFormat, Ui, UiBuilder, Vec2, pos2, + vec2, }; use i18n::keys; @@ -42,20 +42,12 @@ impl PresentationView { } } -pub(in crate::notes) fn show( - ui: &Ui, - state: &AppState, - view: &mut PresentationView, - actions: &mut Actions, -) { +pub(in crate::notes) fn show(ui: &Ui, state: &AppState, view: &mut PresentationView, actions: &mut Actions) { let Some(presenting) = state.presentation.shown() else { return; }; if view.session != presenting.session { - *view = PresentationView { - session: presenting.session, - ..PresentationView::default() - }; + *view = PresentationView { session: presenting.session, ..PresentationView::default() }; } let p = palette(ui.ctx()); let id = Id::unique("presentation"); @@ -71,10 +63,7 @@ pub(in crate::notes) fn show( let said = i18n::translate( state.language, keys::presentation::SLIDE, - &[ - ("at", (view.at + 1).to_string().into()), - ("count", count.to_string().into()), - ], + &[("at", (view.at + 1).to_string().into()), ("count", count.to_string().into())], ); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Dialog, true, &said)); widgets::address(ui, &response, "presentation"); @@ -110,12 +99,7 @@ fn keys_of(ui: &Ui, view: &mut PresentationView, count: usize) { let focused = ui.memory(|memory| memory.focused().is_some()); let next = [Key::ArrowRight, Key::ArrowDown, Key::PageDown] .into_iter() - .chain( - (!focused) - .then_some([Key::Space, Key::Enter]) - .into_iter() - .flatten(), - ) + .chain((!focused).then_some([Key::Space, Key::Enter]).into_iter().flatten()) .any(pressed); let previous = [Key::ArrowLeft, Key::ArrowUp, Key::PageUp, Key::Backspace] .into_iter() @@ -142,14 +126,11 @@ fn stage( ) { let p = palette(ui.ctx()); let (vw, vh) = (whole.width() / 100.0, whole.height() / 100.0); - let room = Rect::from_min_max( - whole.min + vec2(6.0 * vw, 6.0 * vh), - whole.max - vec2(6.0 * vw, 10.0 * vh), - ); + let room = + Rect::from_min_max(whole.min + vec2(6.0 * vw, 6.0 * vh), whole.max - vec2(6.0 * vw, 10.0 * vh)); let width = room.width().min(WIDEST); let Some(slide) = at.checked_sub(1).and_then(|at| presenting.slides.get(at)) else { - let mut format = - TextFormat::simple(FontId::proportional((6.0 * vw).clamp(36.0, 72.0)), p.text_0); + let mut format = TextFormat::simple(FontId::proportional((6.0 * vw).clamp(36.0, 72.0)), p.text_0); format.coords.push(*b"wght", 700.0); let mut job = LayoutJob::single_section(presenting.title.clone(), format); job.wrap.max_width = width; @@ -157,9 +138,7 @@ fn stage( let galley = ui.painter().layout_job(job); let rect = Rect::from_center_size(room.center(), galley.size()); let response = widgets::region(ui, rect, "presentation-cover", Sense::hover()); - response.widget_info(|| { - egui::WidgetInfo::labeled(egui::Role::Heading, true, &presenting.title) - }); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Heading, true, &presenting.title)); widgets::address(ui, &response, "presentation-cover"); // Centred lines are laid out around the position they are drawn at. ui.painter().galley(rect.center_top(), galley, p.text_0); @@ -177,12 +156,9 @@ fn stage( .pictures(&pictures, &missing) .show(ui) }; - let place = ui.unique_id().with(( - "presentation-fit", - presenting.session, - at, - room.size().to_string(), - )); + let place = ui + .unique_id() + .with(("presentation-fit", presenting.session, at, room.size().to_string())); let fit = fitted(ui, room, place, |ui, factor| { draw(ui, factor); }); @@ -222,10 +198,7 @@ fn fitted(ui: &mut Ui, room: Rect, place: Id, draw: impl Fn(&mut Ui, f32)) -> Fi let mut measure = |factor: f32| { let mut unseen = ui.new_child(UiBuilder::new().max_rect(room).invisible()); draw(&mut unseen, factor); - Fit { - factor, - height: unseen.min_rect().height(), - } + Fit { factor, height: unseen.min_rect().height() } }; let mut fit = measure(1.0); while fit.height > room.height() && fit.factor > SMALLEST { @@ -244,21 +217,13 @@ fn progress(ui: &Ui, whole: Rect, shown: usize, count: usize) { let done = shown as f32 / count as f32; let p = palette(ui.ctx()); let track = Rect::from_min_max(pos2(whole.left(), whole.bottom() - 3.0), whole.max); - ui.painter() - .rect_filled(track, CornerRadius::ZERO, p.line_soft); + ui.painter().rect_filled(track, CornerRadius::ZERO, p.line_soft); let filled = Rect::from_min_size(track.min, vec2(track.width() * done, track.height())); - ui.painter() - .rect_filled(filled, CornerRadius::ZERO, p.amber_fill); + ui.painter().rect_filled(filled, CornerRadius::ZERO, p.amber_fill); } /// Out of the way of the slide, dimmed until the pointer reaches it; whether it was left. -fn bar( - ui: &mut Ui, - whole: Rect, - state: &AppState, - view: &mut PresentationView, - count: usize, -) -> bool { +fn bar(ui: &mut Ui, whole: Rect, state: &AppState, view: &mut PresentationView, count: usize) -> bool { let tr = |key| i18n::translate(state.language, key, &[]); let room = Rect::from_min_max(whole.max - vec2(320.0, 58.0), whole.max - vec2(16.0, 18.0)); let mut bar_ui = ui.new_child( @@ -270,18 +235,10 @@ fn bar( bar_ui.set_opacity(0.45); } bar_ui.spacing_mut().item_spacing.x = gap::SNUG; - let closed = IconButton::new( - Icon::X, - &tr(keys::presentation::CLOSE), - "presentation-close", - ) - .show(&mut bar_ui) - .clicked(); - let toggle = if view.map { - keys::presentation::SLIDES - } else { - keys::presentation::MAP - }; + let closed = IconButton::new(Icon::X, &tr(keys::presentation::CLOSE), "presentation-close") + .show(&mut bar_ui) + .clicked(); + let toggle = if view.map { keys::presentation::SLIDES } else { keys::presentation::MAP }; if Button::new(&tr(toggle), "presentation-map") .kind(Kind::Outline) .show(&mut bar_ui) @@ -291,9 +248,8 @@ fn bar( } let next = tr(keys::presentation::NEXT); let can = !view.map && view.at + 1 < count; - let next = bar_ui.add_enabled_ui(can, |ui| { - IconButton::new(Icon::ArrowRight, &next, "presentation-next").show(ui) - }); + let next = bar_ui + .add_enabled_ui(can, |ui| IconButton::new(Icon::ArrowRight, &next, "presentation-next").show(ui)); if next.inner.clicked() { view.go(view.at + 1, count); } @@ -301,12 +257,7 @@ fn bar( let p = palette(ui.ctx()); let counted = bar_ui.add_sized( [56.0, 24.0], - egui::Label::new( - egui::RichText::new(words) - .monospace() - .size(font::BODY) - .color(p.text_1), - ), + egui::Label::new(egui::RichText::new(words).monospace().size(font::BODY).color(p.text_1)), ); widgets::address(&bar_ui, &counted, "presentation-count"); let previous = tr(keys::presentation::PREVIOUS); diff --git a/crates/ui/src/notes/overlays/presentation/mind_map.rs b/crates/ui/src/notes/overlays/presentation/mind_map.rs index aef672f83..01bc80f8d 100644 --- a/crates/ui/src/notes/overlays/presentation/mind_map.rs +++ b/crates/ui/src/notes/overlays/presentation/mind_map.rs @@ -45,31 +45,17 @@ struct Point { pub(super) fn layout(title: &str, map: &[MapNode]) -> Layout { let (root, children) = match map { - [only] => ( - point("root", &only.text, Some(only.slide)), - &only.children[..], - ), + [only] => (point("root", &only.text, Some(only.slide)), &only.children[..]), _ => (point("root", title, None), map), }; let mut points = vec![root]; let mut links = Vec::new(); - place( - children, - (-PI / 2.0, 3.0 * PI / 2.0), - 1, - 0, - &mut points, - &mut links, - ); + place(children, (-PI / 2.0, 3.0 * PI / 2.0), 1, 0, &mut points, &mut links); let span_x = points.iter().map(|point| point.x.abs()).fold(0.0, f64::max); let span_y = points.iter().map(|point| point.y.abs()).fold(0.0, f64::max); let scale = |value: f64, span: f64| { - if span == 0.0 { - 50.0 - } else { - 50.0 + value / span * (50.0 - MARGIN) - } + if span == 0.0 { 50.0 } else { 50.0 + value / span * (50.0 - MARGIN) } }; let nodes = points .into_iter() @@ -86,14 +72,7 @@ pub(super) fn layout(title: &str, map: &[MapNode]) -> Layout { } fn point(key: &str, text: &str, slide: Option) -> Point { - Point { - key: key.to_owned(), - text: text.to_owned(), - slide, - depth: 0, - x: 0.0, - y: 0.0, - } + Point { key: key.to_owned(), text: text.to_owned(), slide, depth: 0, x: 0.0, y: 0.0 } } /// `nodes` share the sector `(from, to)` of the point at `parent`, a ring further out. @@ -122,24 +101,13 @@ fn place( y: middle.sin() * ring, }); links.push((parent, at)); - place( - &node.children, - (angle, angle + span), - depth + 1, - at, - points, - links, - ); + place(&node.children, (angle, angle + span), depth + 1, at, points, links); angle += span; } } fn leaves(node: &MapNode) -> f64 { - if node.children.is_empty() { - 1.0 - } else { - node.children.iter().map(leaves).sum() - } + if node.children.is_empty() { 1.0 } else { node.children.iter().map(leaves).sum() } } /// The map over `rect`: the links, then each heading a button over them. Where the heading @@ -188,11 +156,7 @@ fn heading(ui: &mut Ui, node: &Placed, centre: egui::Pos2) -> bool { crate::widgets::pointer(ui, &response); let hovered = response.hovered() || response.has_focus(); let ink = if hovered { p.amber_text } else { colour }; - let edge = if node.depth == 0 || hovered { - p.amber_edge - } else { - p.line - }; + let edge = if node.depth == 0 || hovered { p.amber_edge } else { p.line }; ui.painter().rect( rect, CornerRadius::same(radius::CARD), @@ -200,8 +164,7 @@ fn heading(ui: &mut Ui, node: &Placed, centre: egui::Pos2) -> bool { Stroke::new(1.0, edge), StrokeKind::Inside, ); - ui.painter() - .galley_with_override_text_color(rect.min + padding, galley, ink); + ui.painter().galley_with_override_text_color(rect.min + padding, galley, ink); response.on_hover_text(&node.text).clicked() } @@ -231,8 +194,7 @@ mod tests { #[test] fn every_outline_is_placed_as_its_golden_case_says() { let cases: Value = - serde_json::from_str(include_str!("../../../../../../golden/mind-map/cases.json")) - .unwrap(); + serde_json::from_str(include_str!("../../../../../../golden/mind-map/cases.json")).unwrap(); for case in cases.as_array().unwrap() { let title = case["input"]["title"].as_str().unwrap(); let placed = layout(title, &map_of(&case["input"]["map"])); @@ -249,14 +211,8 @@ mod tests { let links = case["output"]["links"].as_array().unwrap(); assert_eq!(placed.links.len(), links.len(), "{title}"); for ((from, to), expected) in placed.links.iter().zip(links) { - assert_eq!( - placed.nodes[*from].key, - expected["from"]["key"].as_str().unwrap() - ); - assert_eq!( - placed.nodes[*to].key, - expected["to"]["key"].as_str().unwrap() - ); + assert_eq!(placed.nodes[*from].key, expected["from"]["key"].as_str().unwrap()); + assert_eq!(placed.nodes[*to].key, expected["to"]["key"].as_str().unwrap()); } } } diff --git a/crates/ui/src/notes/overlays/presentation/tests.rs b/crates/ui/src/notes/overlays/presentation/tests.rs index 5e539c9f9..b83217ad4 100644 --- a/crates/ui/src/notes/overlays/presentation/tests.rs +++ b/crates/ui/src/notes/overlays/presentation/tests.rs @@ -31,16 +31,12 @@ fn presenting(body: &str) -> Harness<'static> { }) .unwrap(); let mut harness = expanded_area(backend, profile); - harness - .get_by(|node| node.author_id() == Some("search-input")) - .focus(); + harness.get_by(|node| node.author_id() == Some("search-input")).focus(); harness.step(); harness .get_by(|node| node.author_id() == Some("search-input")) .type_text("Bascule"); - until(&mut harness, "the Note alone", |harness| { - crate::notes::bench::cards(harness) == 1 - }); + until(&mut harness, "the Note alone", |harness| crate::notes::bench::cards(harness) == 1); click_id(&mut harness, "note-card-open"); click_id(&mut harness, "editor-more"); click_id(&mut harness, "editor-present"); @@ -65,11 +61,7 @@ fn press(harness: &mut Harness<'_>, key: Key) { fn says(harness: &Harness<'_>, words: &str) -> bool { harness - .query_all_by(|node| { - node.label() - .or_else(|| node.value()) - .is_some_and(|said| said.contains(words)) - }) + .query_all_by(|node| node.label().or_else(|| node.value()).is_some_and(|said| said.contains(words))) .next() .is_some() } @@ -100,11 +92,7 @@ fn the_title_comes_first_then_each_section_a_slide_moved_by_the_keys_and_the_but /// Where the words `said` are drawn. fn place(harness: &Harness<'_>, said: &str) -> egui::Rect { harness - .query_all_by(|node| { - node.label() - .or_else(|| node.value()) - .is_some_and(|words| words == said) - }) + .query_all_by(|node| node.label().or_else(|| node.value()).is_some_and(|words| words == said)) .next() .unwrap_or_else(|| panic!("{said} is not on screen")) .rect() @@ -112,9 +100,8 @@ fn place(harness: &Harness<'_>, said: &str) -> egui::Rect { #[test] fn a_slide_is_where_it_stays_from_its_first_frame() { - let mut harness = presenting( - "## Courte\n\nUne ligne.\n\n## Longue\n\nUne.\n\nDeux.\n\nTrois.\n\nQuatre.\n\nCinq.\n", - ); + let mut harness = + presenting("## Courte\n\nUne ligne.\n\n## Longue\n\nUne.\n\nDeux.\n\nTrois.\n\nQuatre.\n\nCinq.\n"); for title in ["Courte", "Longue"] { // Not `key_press`, whose release takes a frame of its own. harness.input_mut().events.push(egui::Event::Key { @@ -133,9 +120,8 @@ fn a_slide_is_where_it_stays_from_its_first_frame() { #[test] fn titles_and_text_start_at_the_margin_on_every_slide_and_code_is_centred() { - let mut harness = presenting( - "# Un\n\nUne ligne.\n\n## Deux\n\n- Un point\n\n## Trois\n\n```rust\nlet x = 1;\n```\n", - ); + let mut harness = + presenting("# Un\n\nUne ligne.\n\n## Deux\n\n- Un point\n\n## Trois\n\n```rust\nlet x = 1;\n```\n"); harness.set_size(egui::vec2(1_900.0, 900.0)); settle(&mut harness); let margin = 0.06 * 1_900.0; @@ -165,9 +151,7 @@ fn coded(lines: &[String]) -> Harness<'static> { } fn numbered(count: usize) -> Vec { - (1..=count) - .map(|at| format!("let line_{at} = {at};")) - .collect() + (1..=count).map(|at| format!("let line_{at} = {at};")).collect() } /// The code painted: what it covers, what it is clipped to, and its first line's height. @@ -211,10 +195,7 @@ fn a_block_taller_than_the_slide_is_fitted_and_past_the_floor_it_scrolls() { let mut harness = coded(&numbered(60)); let (covered, _, floor) = code(&harness); - assert!( - (floor / full - super::SMALLEST).abs() < 0.05, - "{floor} against {full}" - ); + assert!((floor / full - super::SMALLEST).abs() < 0.05, "{floor} against {full}"); let bottom = 900.0 * 0.9; assert!(covered.bottom() > bottom, "sixty lines do not hold"); harness.event(egui::Event::PointerMoved(egui::pos2(800.0, 400.0))); @@ -229,18 +210,12 @@ fn a_block_taller_than_the_slide_is_fitted_and_past_the_floor_it_scrolls() { harness.step(); } settle(&mut harness); - assert!( - code(&harness).0.bottom() <= bottom, - "the last line is reached" - ); + assert!(code(&harness).0.bottom() <= bottom, "the last line is reached"); } #[test] fn a_fitted_slide_is_where_it_stays_from_its_first_frame() { - let mut harness = presenting(&format!( - "## Titre\n\n```rust\n{}\n```\n", - numbered(30).join("\n") - )); + let mut harness = presenting(&format!("## Titre\n\n```rust\n{}\n```\n", numbered(30).join("\n"))); harness.input_mut().events.push(egui::Event::Key { key: Key::ArrowRight, physical_key: None, @@ -267,8 +242,7 @@ fn the_map_opens_the_slide_of_the_heading_pressed() { harness .get_by(|node| { - node.author_id() == Some("presentation-map-node") - && node.label().as_deref() == Some("DNS") + node.author_id() == Some("presentation-map-node") && node.label().as_deref() == Some("DNS") }) .click(); settle(&mut harness); @@ -287,14 +261,8 @@ fn escape_leaves_and_the_editor_stays() { press(&mut harness, Key::Escape); until(&mut harness, "left", |harness| { - harness - .query_by(|node| node.author_id() == Some("presentation")) - .is_none() + harness.query_by(|node| node.author_id() == Some("presentation")).is_none() }); - assert!( - harness - .query_by(|node| node.author_id() == Some("editor-rich")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("editor-rich")).is_some()); } diff --git a/crates/ui/src/notes/overlays/tag_manager.rs b/crates/ui/src/notes/overlays/tag_manager.rs index a461ddfb1..f05e37e3d 100644 --- a/crates/ui/src/notes/overlays/tag_manager.rs +++ b/crates/ui/src/notes/overlays/tag_manager.rs @@ -4,8 +4,7 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Id, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, - vec2, + Color32, CornerRadius, FontFamily, Id, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, pos2, vec2, }; use engine::notes::model::TagUsage; use i18n::keys; @@ -56,12 +55,7 @@ fn ask(actions: &mut Actions, asked: Tags) { actions.push(Action::Notes(Asked::Tags(asked))); } -pub(in crate::notes) fn show( - ui: &Ui, - state: &AppState, - view: &mut TagManagerView, - actions: &mut Actions, -) { +pub(in crate::notes) fn show(ui: &Ui, state: &AppState, view: &mut TagManagerView, actions: &mut Actions) { if !state.tags.is_open() { view.clear(); return; @@ -85,14 +79,7 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TagManagerView, actions: &mut let closed = ui .horizontal(|ui| { let title = tr(keys::tag_manager::TITLE); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); let room = ui.available_width() - widgets::MIN_TARGET; let (rect, _) = ui.allocate_exact_size(vec2(room, words.size().y), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); @@ -101,29 +88,14 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TagManagerView, actions: &mut .clicked() }) .inner; - say( - ui, - &tr(keys::tag_manager::HINT), - p.text_2, - "tag-manager-hint", - ); + say(ui, &tr(keys::tag_manager::HINT), p.text_2, "tag-manager-hint"); let tags = &state.tags; if tags.is_loading() { - say( - ui, - &tr(keys::tag_manager::LOADING), - p.text_2, - "tag-manager-loading", - ); + say(ui, &tr(keys::tag_manager::LOADING), p.text_2, "tag-manager-loading"); return closed; } if tags.tags().is_empty() { - say( - ui, - &tr(keys::tag_manager::EMPTY), - p.text_2, - "tag-manager-empty", - ); + say(ui, &tr(keys::tag_manager::EMPTY), p.text_2, "tag-manager-empty"); return closed; } list(ui, state, view, actions); @@ -136,19 +108,15 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TagManagerView, actions: &mut } fn say(ui: &mut Ui, words: &str, colour: Color32, author_id: &str) { - let response = ui - .add(egui::Label::new(egui::RichText::new(words).size(font::CONTROL).color(colour)).wrap()); + let response = + ui.add(egui::Label::new(egui::RichText::new(words).size(font::CONTROL).color(colour)).wrap()); widgets::address(ui, &response, author_id); } /// The tags as a cloud that scrolls, only its lines in view drawn. fn list(ui: &mut Ui, state: &AppState, view: &mut TagManagerView, actions: &mut Actions) { let (tags, language) = (&state.tags, state.language); - let widths: Vec = tags - .tags() - .iter() - .map(|usage| chip_width(ui, usage, language)) - .collect(); + let widths: Vec = tags.tags().iter().map(|usage| chip_width(ui, usage, language)).collect(); let room = ui.available_width() - ui.spacing().scroll.allocated_width(); let lines = lines_of(&widths, room); ui.spacing_mut().item_spacing.y = gap::SNUG; @@ -233,28 +201,11 @@ fn chip_texts( ) -> (std::sync::Arc, std::sync::Arc) { let p = palette(ui.ctx()); let name = format!("#{}", usage.tag); - let count = i18n::translate( - language, - keys::tag_manager::NOTE_COUNT, - &[("count", usage.note_count.into())], - ); + let count = + i18n::translate(language, keys::tag_manager::NOTE_COUNT, &[("count", usage.note_count.into())]); ( - widgets::text( - ui, - &name, - font::CONTROL, - 400.0, - FontFamily::Monospace, - p.text_1, - ), - widgets::text( - ui, - &count, - font::CAPTION, - 400.0, - FontFamily::Proportional, - p.text_2, - ), + widgets::text(ui, &name, font::CONTROL, 400.0, FontFamily::Monospace, p.text_1), + widgets::text(ui, &count, font::CAPTION, 400.0, FontFamily::Proportional, p.text_2), ) } @@ -273,45 +224,21 @@ fn item(ui: &mut Ui, usage: &TagUsage, on: bool, language: i18n::Language) -> bo || WidgetInfo::selected(Role::Button, true, on, &name), corner, ); - let lit = if on { - 1.0 - } else { - widgets::hovered(ui, &response) - }; + let lit = if on { 1.0 } else { widgets::hovered(ui, &response) }; let (fill, edge, ink) = if on { - ( - p.amber_fill.gamma_multiply(0.15), - p.amber_fill.gamma_multiply(0.5), - p.amber_text, - ) + (p.amber_fill.gamma_multiply(0.15), p.amber_fill.gamma_multiply(0.5), p.amber_text) } else { - ( - p.bg_2, - widgets::towards(p.line_soft, p.amber_dim, lit), - widgets::towards(p.text_1, p.text_0, lit), - ) + (p.bg_2, widgets::towards(p.line_soft, p.amber_dim, lit), widgets::towards(p.text_1, p.text_0, lit)) }; let rect = response.rect; - ui.painter().rect( - rect, - corner, - fill, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, fill, Stroke::new(1.0, edge), StrokeKind::Inside); let words = widgets::text(ui, &name, font::CONTROL, 400.0, FontFamily::Monospace, ink); let left = rect.left() + 10.0; let width = words.size().x; - ui.painter().galley( - pos2(left, rect.center().y - words.size().y / 2.0), - words, - ink, - ); - let count_ink = if on { - p.amber_text.gamma_multiply(0.75) - } else { - p.text_2 - }; + ui.painter() + .galley(pos2(left, rect.center().y - words.size().y / 2.0), words, ink); + let count_ink = if on { p.amber_text.gamma_multiply(0.75) } else { p.text_2 }; ui.painter().galley( pos2(left + width + 6.0, rect.center().y - counted.size().y / 2.0), counted, @@ -325,31 +252,19 @@ fn form(ui: &mut Ui, state: &AppState, view: &mut TagManagerView, actions: &mut let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let p = palette(ui.ctx()); - say( - ui, - &tr(keys::tag_manager::SELECTION_HINT), - p.text_2, - "tag-selection-hint", - ); + say(ui, &tr(keys::tag_manager::SELECTION_HINT), p.text_2, "tag-selection-hint"); let top = ui.cursor().top(); - ui.painter() - .hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); ui.add_space(gap::TIGHT); let ticked = state.tags.selected() > 0; let refused = refusal(state, &view.target).filter(|_| ticked); - let apply = tr(if state.tags.selected() > 1 { - keys::tag_manager::MERGE - } else { - keys::tag_manager::RENAME - }); + let apply = + tr(if state.tags.selected() > 1 { keys::tag_manager::MERGE } else { keys::tag_manager::RENAME }); let delete = tr(keys::tag_manager::DELETE); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let buttons = 2.0 * 8.0 + Button::width(ui, &apply) + Button::width(ui, &delete); - let (label, hint) = ( - tr(keys::tag_manager::TARGET_LABEL), - tr(keys::tag_manager::TARGET_PLACEHOLDER), - ); + let (label, hint) = (tr(keys::tag_manager::TARGET_LABEL), tr(keys::tag_manager::TARGET_PLACEHOLDER)); let field = ui .allocate_ui(vec2(ui.available_width() - buttons, 32.0), |ui| { TextField::new(&mut view.target, &label, "tag-target") @@ -432,14 +347,8 @@ fn confirmation( let shown = frame.show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = gap::INSET; - let text = ui.add( - egui::Label::new( - egui::RichText::new(&words) - .size(font::READING) - .color(p.text_0), - ) - .wrap(), - ); + let text = + ui.add(egui::Label::new(egui::RichText::new(&words).size(font::READING).color(p.text_0)).wrap()); widgets::address(ui, &text, "tag-confirm-text"); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; @@ -476,12 +385,9 @@ mod tests { /// alpha `staging`, beta `staging` and `urgent`, gamma `preprod`; the manager open. fn tagged() -> Harness<'static, Bench> { let (backend, profile) = testing::unlocked(); - let notes = [ - ("alpha", vec!["staging"]), - ("beta", vec!["staging", "urgent"]), - ("gamma", vec!["preprod"]), - ] - .map(|(title, tags)| (testing::note(&backend, title).id.clone(), tags)); + let notes = + [("alpha", vec!["staging"]), ("beta", vec!["staging", "urgent"]), ("gamma", vec!["preprod"])] + .map(|(title, tags)| (testing::note(&backend, title).id.clone(), tags)); engine::db::run_here(backend.engine(), move |engine| { for (id, tags) in notes { let patch = NotePatch { @@ -511,8 +417,7 @@ mod tests { let name = format!("#{tag}"); harness .get_by(|node| { - node.author_id() == Some("tag-item") - && node.label().as_deref() == Some(name.as_str()) + node.author_id() == Some("tag-item") && node.label().as_deref() == Some(name.as_str()) }) .click(); settle(harness); @@ -523,9 +428,7 @@ mod tests { click_id(harness, "tag-target"); harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); harness.key_press(egui::Key::Backspace); - harness - .get_by(|node| node.author_id() == Some("tag-target")) - .type_text(into); + harness.get_by(|node| node.author_id() == Some("tag-target")).type_text(into); settle(harness); click_id(harness, "tag-apply"); } @@ -558,10 +461,7 @@ mod tests { let tags: Vec = (0..count).map(|rank| format!("tag-{rank:03}")).collect(); for (rank, tags) in tags.chunks(10).enumerate() { let id = testing::note(&backend, &format!("note {rank}")).id.clone(); - let patch = NotePatch { - tags: Some(tags.to_vec()), - ..NotePatch::default() - }; + let patch = NotePatch { tags: Some(tags.to_vec()), ..NotePatch::default() }; engine::db::run_here(backend.engine(), move |engine| { engine::notes::update_note(engine, &id, &patch) }) @@ -579,9 +479,7 @@ mod tests { let mut harness = many(300); let window = harness.ctx.content_rect(); for author_id in ["tag-manager-close", "tag-target", "tag-apply", "tag-delete"] { - let rect = harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect(); + let rect = harness.get_by(|node| node.author_id() == Some(author_id)).rect(); assert!(window.contains_rect(rect), "{author_id} at {rect:?}"); } assert!(listed(&harness).len() < 300, "only what shows is drawn"); @@ -607,9 +505,7 @@ mod tests { assert!(listed(&harness).contains(&"#tag-299".to_owned())); tick(&mut harness, "tag-299"); propose(&mut harness, "last"); - let confirm = harness - .get_by(|node| node.author_id() == Some("tag-confirm-apply")) - .rect(); + let confirm = harness.get_by(|node| node.author_id() == Some("tag-confirm-apply")).rect(); assert!(window.contains_rect(confirm), "{confirm:?}"); } @@ -623,9 +519,7 @@ mod tests { assert!(!applies(&harness), "nothing would change yet"); assert!(reason(&harness).is_some()); - harness - .get_by(|node| node.author_id() == Some("tag-target")) - .type_text("-eu"); + harness.get_by(|node| node.author_id() == Some("tag-target")).type_text("-eu"); settle(&mut harness); assert_eq!(field(&harness), "-eu", "typed over the selection"); assert!(applies(&harness)); @@ -642,11 +536,7 @@ mod tests { propose(&mut harness, typed); assert!(!applies(&harness), "{typed:?} changes nothing"); assert!(reason(&harness).is_some(), "{typed:?} is said"); - assert!( - harness - .query_by(|node| node.author_id() == Some("tag-confirm-text")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("tag-confirm-text")).is_none()); } propose(&mut harness, "#recette"); assert!(said(&harness).contains("recette"), "{}", said(&harness)); @@ -665,11 +555,7 @@ mod tests { let mut harness = tagged(); tick(&mut harness, "staging"); propose(&mut harness, "recette"); - assert!( - said(&harness).contains('2'), - "two notes carry it: {}", - said(&harness) - ); + assert!(said(&harness).contains('2'), "two notes carry it: {}", said(&harness)); click_id(&mut harness, "tag-confirm-cancel"); assert_eq!(listed(&harness), ["#preprod", "#staging", "#urgent"]); @@ -699,4 +585,45 @@ mod tests { assert_eq!(listed(&harness), ["#preprod", "#staging"]); assert_eq!(crate::notes::bench::cards(&harness), 3); } + + /// Said before: it is the notes of both that end on one name. + #[test] + fn a_merge_is_asked_as_one() { + let mut harness = tagged(); + tick(&mut harness, "staging"); + propose(&mut harness, "preprod"); + let merged = said(&harness); + click_id(&mut harness, "tag-confirm-cancel"); + propose(&mut harness, "validation"); + + assert_ne!(merged, said(&harness)); + assert!(merged.contains("preprod"), "{merged}"); + } + + /// Unticked down to one, it is that one's name that is edited. + #[test] + fn the_last_tag_left_ticked_fills_the_field() { + let mut harness = tagged(); + tick(&mut harness, "staging"); + tick(&mut harness, "urgent"); + tick(&mut harness, "staging"); + + assert_eq!(field(&harness), "urgent"); + } + + #[test] + fn a_library_with_no_tag_says_so() { + let (backend, profile) = testing::unlocked(); + testing::note(&backend, "alpha"); + let mut harness = area(backend, profile); + let bench = harness.state_mut(); + bench.state.apply( + crate::action::Action::Notes(crate::notes::Action::Tags(crate::notes::Tags::Open)), + &egui::Context::default(), + &bench.backend, + ); + settle(&mut harness); + + harness.get_by(|node| node.author_id() == Some("tag-manager-empty")); + } } diff --git a/crates/ui/src/notes/overlays/trash_panel.rs b/crates/ui/src/notes/overlays/trash_panel.rs index 50efe194e..36f8a9eaa 100644 --- a/crates/ui/src/notes/overlays/trash_panel.rs +++ b/crates/ui/src/notes/overlays/trash_panel.rs @@ -5,8 +5,8 @@ use crate::theme::tokens::{font, gap, radius}; use chrono::{DateTime, Utc}; use egui::{ - CornerRadius, FontFamily, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, UiBuilder, WidgetInfo, - pos2, vec2, + CornerRadius, FontFamily, Id, Rect, Role, Sense, Stroke, StrokeKind, Ui, UiBuilder, WidgetInfo, pos2, + vec2, }; use engine::notes::kind::NoteKind; use engine::notes::trash::TrashedNote; @@ -35,12 +35,7 @@ pub(in crate::notes) struct TrashView { searching: bool, } -pub(in crate::notes) fn show( - ui: &Ui, - state: &AppState, - view: &mut TrashView, - actions: &mut Actions, -) { +pub(in crate::notes) fn show(ui: &Ui, state: &AppState, view: &mut TrashView, actions: &mut Actions) { if !state.trash.is_open() { *view = TrashView::default(); return; @@ -69,14 +64,7 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TrashView, actions: &mut Acti let closed = ui .horizontal(|ui| { let title = tr(keys::trash::TITLE); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); let room = ui.available_width() - widgets::MIN_TARGET; let (rect, _) = ui.allocate_exact_size(vec2(room, words.size().y), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); @@ -89,10 +77,7 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TrashView, actions: &mut Acti let notes = state.trash.notes(); if !notes.is_empty() || state.trash.searching() { let mut typed = state.trash.search().to_owned(); - let (label, hint) = ( - tr(keys::trash::SEARCH_LABEL), - tr(keys::trash::SEARCH_PLACEHOLDER), - ); + let (label, hint) = (tr(keys::trash::SEARCH_LABEL), tr(keys::trash::SEARCH_PLACEHOLDER)); if TextField::new(&mut typed, &label, "trash-search") .hint(&hint) .show(ui) @@ -104,11 +89,7 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TrashView, actions: &mut Acti if state.trash.is_loading() { say(ui, &tr(keys::trash::LOADING), "trash-loading"); } else if notes.is_empty() { - let key = if state.trash.searching() { - keys::trash::NO_MATCH - } else { - keys::trash::EMPTY - }; + let key = if state.trash.searching() { keys::trash::NO_MATCH } else { keys::trash::EMPTY }; say(ui, &tr(key), "trash-empty-state"); } else { list(ui, state, notes, view, actions); @@ -120,18 +101,12 @@ fn panel(ui: &mut Ui, state: &AppState, view: &mut TrashView, actions: &mut Acti /// A line of quiet text, read by its name. fn say(ui: &mut Ui, words: &str, author_id: &str) { let p = palette(ui.ctx()); - let response = ui - .add(egui::Label::new(egui::RichText::new(words).size(font::LABEL).color(p.text_2)).wrap()); + let response = + ui.add(egui::Label::new(egui::RichText::new(words).size(font::LABEL).color(p.text_2)).wrap()); widgets::address(ui, &response, author_id); } -fn list( - ui: &mut Ui, - state: &AppState, - notes: &[TrashedNote], - view: &mut TrashView, - actions: &mut Actions, -) { +fn list(ui: &mut Ui, state: &AppState, notes: &[TrashedNote], view: &mut TrashView, actions: &mut Actions) { #[expect(clippy::cast_precision_loss, reason = "rows on a screen")] let whole = notes.len() as f32 * (ROW + GAP) - GAP; let tallest = (ui.ctx().content_rect().height() * 0.5).max(ROW * 2.0); @@ -151,77 +126,36 @@ fn list( ui.spacing_mut().item_spacing.y = gap::INSET; } -fn row( - ui: &mut Ui, - state: &AppState, - note: &TrashedNote, - view: &mut TrashView, - actions: &mut Actions, -) { +fn row(ui: &mut Ui, state: &AppState, note: &TrashedNote, view: &mut TrashView, actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let width = ui.available_width(); let (rect, response) = ui.allocate_exact_size(vec2(width, ROW), Sense::hover()); - let title = if note.note.title.trim().is_empty() { - tr(keys::trash::UNTITLED) - } else { - note.note.title.clone() - }; + let title = + if note.note.title.trim().is_empty() { tr(keys::trash::UNTITLED) } else { note.note.title.clone() }; response.widget_info(|| WidgetInfo::labeled(Role::ListItem, true, &title)); widgets::address(ui, &response, "trash-row"); let corner = CornerRadius::same(radius::MENU); - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(1.0, p.line_soft), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, p.bg_2, Stroke::new(1.0, p.line_soft), StrokeKind::Inside); let inner = rect.shrink2(vec2(11.0, 9.0)); let left = buttons(ui, inner, state, ¬e.note.id, view, actions); let text = Rect::from_min_max(inner.min, pos2(left - 12.0, inner.bottom())); let mut words = ui.new_child(UiBuilder::new().max_rect(text)); words.set_clip_rect(text.intersect(ui.clip_rect())); words.spacing_mut().item_spacing.y = gap::TIGHT; - line( - &mut words, - &title, - 12.5, - FontFamily::Proportional, - p.text_0, - "trash-row-title", - 1, - ); + line(&mut words, &title, 12.5, FontFamily::Proportional, p.text_0, "trash-row-title", 1); let preview = if note.note.kind == NoteKind::Checklist { tr(keys::trash::CHECKLIST_NOTE) } else { note.preview.clone() }; - let mono = if note.note.kind == NoteKind::Checklist { - FontFamily::Proportional - } else { - FontFamily::Monospace - }; - line( - &mut words, - &preview, - 11.0, - mono, - p.text_2, - "trash-row-snippet", - SNIPPET_LINES, - ); + let mono = + if note.note.kind == NoteKind::Checklist { FontFamily::Proportional } else { FontFamily::Monospace }; + line(&mut words, &preview, 11.0, mono, p.text_2, "trash-row-snippet", SNIPPET_LINES); let meta = meta(ui, state, note.deleted_at, note.purge_at); - line( - &mut words, - &meta, - 11.0, - FontFamily::Proportional, - p.text_2, - "trash-row-meta", - 1, - ); + line(&mut words, &meta, 11.0, FontFamily::Proportional, p.text_2, "trash-row-meta", 1); } /// Restore, and the purge in two clicks, at the row's right; answers where they begin. @@ -242,11 +176,7 @@ fn buttons( ); buttons.spacing_mut().item_spacing.x = gap::SNUG; let confirming = view.confirming_purge.as_deref() == Some(id); - let purge = tr(if confirming { - keys::trash::PURGE_CONFIRM - } else { - keys::trash::PURGE - }); + let purge = tr(if confirming { keys::trash::PURGE_CONFIRM } else { keys::trash::PURGE }); if Button::new(&purge, "trash-purge") .kind(Kind::Destructive) .armed(confirming) @@ -300,11 +230,7 @@ fn meta(ui: &Ui, state: &AppState, deleted: DateTime, purge: DateTime) let language = state.language; let (ago, wait) = crate::services::time::relative(deleted, state.clock.as_ref()); ui.ctx().request_repaint_after(wait); - let deleted = i18n::translate( - language, - keys::trash::DELETED_AT, - &[("when", ago.text(language).into())], - ); + let deleted = i18n::translate(language, keys::trash::DELETED_AT, &[("when", ago.text(language).into())]); let purges = match days_left(purge, state.clock.now()) { 0 => i18n::translate(language, keys::trash::PURGES_TODAY, &[]), days => i18n::translate(language, keys::trash::PURGES_IN, &[("count", days.into())]), @@ -330,19 +256,12 @@ fn days_left(purge: DateTime, now: DateTime) -> u32 { /// Restore all, empty: the one action here nothing puts back says what it would erase and is /// confirmed elsewhere than on the button that asked. It stands aside while the trash is /// searched: it would erase notes not shown. -fn footer( - ui: &mut Ui, - state: &AppState, - count: usize, - view: &mut TrashView, - actions: &mut Actions, -) { +fn footer(ui: &mut Ui, state: &AppState, count: usize, view: &mut TrashView, actions: &mut Actions) { let p = palette(ui.ctx()); let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let top = ui.cursor().top(); - ui.painter() - .hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); ui.add_space(gap::TIGHT); let count = u32::try_from(count).unwrap_or(u32::MAX); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -367,22 +286,14 @@ fn footer( let warning = if count == 1 { tr(keys::trash::EMPTY_TRASH_WARNING_ONE) } else { - i18n::translate( - language, - keys::trash::EMPTY_TRASH_WARNING, - &[("count", count.into())], - ) + i18n::translate(language, keys::trash::EMPTY_TRASH_WARNING, &[("count", count.into())]) }; let room = ui.available_width(); ui.allocate_ui(vec2(room, 24.0), |ui| { ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { let response = ui.add( - egui::Label::new( - egui::RichText::new(&warning) - .size(font::CONTROL) - .color(p.red), - ) - .wrap(), + egui::Label::new(egui::RichText::new(&warning).size(font::CONTROL).color(p.red)) + .wrap(), ); response.widget_info(|| WidgetInfo::labeled(Role::Alert, true, &warning)); widgets::address(ui, &response, "trash-empty-warning"); @@ -398,16 +309,9 @@ fn footer( { view.confirming_empty = true; } - let key = if state.trash.searching() { - keys::trash::RESTORE_FOUND - } else { - keys::trash::RESTORE_ALL - }; + let key = if state.trash.searching() { keys::trash::RESTORE_FOUND } else { keys::trash::RESTORE_ALL }; let restore = i18n::translate(language, key, &[("count", count.into())]); - if Button::new(&restore, "trash-restore-all") - .show(ui) - .clicked() - { + if Button::new(&restore, "trash-restore-all").show(ui).clicked() { actions.push(Action::Notes(Asked::Trash(Trash::RestoreAll))); } }); @@ -427,14 +331,9 @@ mod tests { fn trashed(gone: &[&str]) -> Harness<'static, Bench> { let (backend, profile) = testing::unlocked(); testing::note(&backend, "kept"); - let ids: Vec = gone - .iter() - .map(|title| testing::note(&backend, title).id.clone()) - .collect(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::delete_notes(engine, &ids) - }) - .unwrap(); + let ids: Vec = gone.iter().map(|title| testing::note(&backend, title).id.clone()).collect(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::delete_notes(engine, &ids)) + .unwrap(); let mut harness = area(backend, profile); click_id(&mut harness, "trash-open"); harness @@ -451,9 +350,7 @@ mod tests { } fn has(harness: &Harness<'_, Bench>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } #[test] @@ -487,15 +384,11 @@ mod tests { harness .get_by(|node| node.author_id() == Some("trash-search")) .type_text("rollout"); - until(&mut harness, "the search narrows the trash", |harness| { - rows(harness).len() == 2 - }); + until(&mut harness, "the search narrows the trash", |harness| rows(harness).len() == 2); assert!(!has(&harness, "trash-empty"), "emptying stands aside"); click_id(&mut harness, "trash-restore-all"); - until(&mut harness, "the found notes leave the trash", |harness| { - has(harness, "trash-empty-state") - }); + until(&mut harness, "the found notes leave the trash", |harness| has(harness, "trash-empty-state")); assert_eq!(cards(&harness), 3); } @@ -560,4 +453,33 @@ mod tests { assert_eq!(days_left(now + TimeDelta::hours(5), now), 0); assert_eq!(days_left(now - TimeDelta::hours(5), now), 0); } + + /// A list has no body to preview, a note with no title still has a row of its own. + #[test] + fn what_has_no_title_or_no_body_says_what_it_is() { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "gone").id.clone(); + let patch = engine::notes::model::NotePatch { + title: Some(String::new()), + kind: Some(engine::notes::kind::NoteKind::Checklist), + content: Some(String::new()), + items: Some(vec![engine::notes::checklist::ChecklistItem { + text: "milk".to_owned(), + done: false, + }]), + ..Default::default() + }; + engine::db::run_here(backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch)?; + engine::notes::delete_notes(engine, &[id]) + }) + .unwrap(); + let mut harness = area(backend, profile); + click_id(&mut harness, "trash-open"); + let tr = |key| i18n::translate(i18n::Language::En, key, &[]); + + assert_eq!(rows(&harness), [tr(i18n::keys::trash::UNTITLED)]); + let painted = testing::painted(&harness); + assert!(painted.contains(&tr(i18n::keys::trash::CHECKLIST_NOTE)), "{painted:?}"); + } } diff --git a/crates/ui/src/notes/overlays/undo_bar.rs b/crates/ui/src/notes/overlays/undo_bar.rs index e0099f069..9703bb36c 100644 --- a/crates/ui/src/notes/overlays/undo_bar.rs +++ b/crates/ui/src/notes/overlays/undo_bar.rs @@ -4,8 +4,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Align2, CornerRadius, FontFamily, Id, LayerId, Order, Role, Sense, Stroke, StrokeKind, Ui, - WidgetInfo, vec2, + Align2, CornerRadius, FontFamily, Id, LayerId, Order, Role, Sense, Stroke, StrokeKind, Ui, WidgetInfo, + vec2, }; use engine::notes::kind::NoteKind; use i18n::{Key, keys}; @@ -28,8 +28,7 @@ pub(in crate::notes) fn show(ui: &Ui, state: &AppState, actions: &mut Actions) { return; }; if let Some(left) = state.undo.banner_left(now) { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(left)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(left)); } let p = palette(ui.ctx()); let frame = egui::Frame::new() @@ -48,10 +47,7 @@ pub(in crate::notes) fn show(ui: &Ui, state: &AppState, actions: &mut Actions) { message(ui, action, state.language); restore(ui, state.language, actions); let dismiss = i18n::translate(state.language, keys::undo::DISMISS, &[]); - if IconButton::new(Icon::X, &dismiss, "undo-dismiss") - .show(ui) - .clicked() - { + if IconButton::new(Icon::X, &dismiss, "undo-dismiss").show(ui).clicked() { actions.push(Action::Notes(crate::notes::Action::DismissUndo)); } }); @@ -75,14 +71,7 @@ fn message(ui: &mut Ui, action: &Reversible, language: i18n::Language) { } _ => i18n::translate(language, said(action), &[("count", count.into())]), }; - let galley = widgets::text( - ui, - &words, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, &words, font::BODY, 400.0, FontFamily::Proportional, p.text_1); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "undo-text"); @@ -101,9 +90,9 @@ fn said(action: &Reversible) -> Key { Reversible::Priority(_) => keys::undo::PRIORITISED, Reversible::File(_) => keys::undo::FILED, Reversible::Arrangement { .. } => keys::undo::ARRANGED, - Reversible::FolderMove { - was, into: Some(_), .. - } if !was.notes.is_empty() => keys::undo::FOLDER_MOVED_WITH_NOTES, + Reversible::FolderMove { was, into: Some(_), .. } if !was.notes.is_empty() => { + keys::undo::FOLDER_MOVED_WITH_NOTES + } Reversible::FolderMove { into: Some(_), .. } => keys::undo::FOLDER_MOVED, Reversible::FolderMove { into: None, .. } => keys::undo::FOLDER_MOVED_TOP, Reversible::Convert { into, .. } => match into { @@ -122,22 +111,8 @@ fn restore(ui: &mut Ui, language: i18n::Language, actions: &mut Actions) { let p = palette(ui.ctx()); let label = i18n::translate(language, keys::undo::RESTORE, &[]); let cap = i18n::translate(language, keys::undo::RESTORE_KEY, &[]); - let words = widgets::text( - ui, - &label, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.amber_text, - ); - let key = widgets::text( - ui, - &cap, - font::CAPTION, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let words = widgets::text(ui, &label, font::LABEL, 400.0, FontFamily::Proportional, p.amber_text); + let key = widgets::text(ui, &cap, font::CAPTION, 400.0, FontFamily::Monospace, p.text_2); let cap_size = key.size() + vec2(10.0, 2.0); let wanted = vec2(words.size().x + 6.0 + cap_size.x, words.size().y) + vec2(20.0, 8.0); let corner = CornerRadius::same(radius::CONTROL); @@ -150,25 +125,12 @@ fn restore(ui: &mut Ui, language: i18n::Language, actions: &mut Actions) { corner, ); let rect = response.rect; - let (fill, edge) = if response.hovered() { - (p.bg_3, p.amber_edge) - } else { - (p.bg_2, p.line_soft) - }; + let (fill, edge) = if response.hovered() { (p.bg_3, p.amber_edge) } else { (p.bg_2, p.line_soft) }; let painter = ui.painter(); - painter.rect( - rect, - corner, - fill, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + painter.rect(rect, corner, fill, Stroke::new(1.0, edge), StrokeKind::Inside); let words_at = egui::pos2(rect.left() + 10.0, rect.center().y - words.size().y / 2.0); let cap_rect = egui::Rect::from_min_size( - egui::pos2( - words_at.x + words.size().x + 6.0, - rect.center().y - cap_size.y / 2.0, - ), + egui::pos2(words_at.x + words.size().x + 6.0, rect.center().y - cap_size.y / 2.0), cap_size, ); painter.galley(words_at, words, p.amber_text); @@ -186,6 +148,7 @@ fn restore(ui: &mut Ui, language: i18n::Language, actions: &mut Actions) { #[cfg(test)] mod tests { + use super::*; use egui::{Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; @@ -211,9 +174,7 @@ mod tests { } fn offered(harness: &Harness<'_, Bench>) -> bool { - harness - .query_by(|node| node.author_id() == Some("undo-bar")) - .is_some() + harness.query_by(|node| node.author_id() == Some("undo-bar")).is_some() } #[test] @@ -293,4 +254,45 @@ mod tests { let view = harness.state().state.notes_query.view().unwrap(); assert!(view.cards().all(|card| !card.pinned)); } + + /// « 3 notes deleted » and « 3 notes moved » are not the same sentence. + #[test] + fn each_kind_of_thing_undone_has_its_own_words() { + use engine::notes::convert::NoteBody; + + let pin = |pinned| Reversible::Pin { ids: Vec::new(), pinned }; + let converted = |into| Reversible::Convert { + id: String::new(), + into, + previous: NoteBody { + kind: NoteKind::Snippet, + language: engine::notes::language::Language::Txt, + content: String::new(), + items: Vec::new(), + }, + }; + let mut words: Vec = [ + Reversible::Deletion { ids: Vec::new(), count: 2 }, + Reversible::Move(Vec::new()), + Reversible::Tag(Vec::new()), + Reversible::Untag(Vec::new()), + pin(true), + pin(false), + Reversible::Priority(Vec::new()), + Reversible::File(Vec::new()), + converted(NoteKind::Snippet), + converted(NoteKind::Note), + converted(NoteKind::Checklist), + converted(NoteKind::Calc), + converted(NoteKind::Drawing), + ] + .iter() + .map(|action| i18n::translate(i18n::Language::En, super::said(action), &[("count", 2_u32.into())])) + .collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count, "{words:?}"); + } } diff --git a/crates/ui/src/notes/panel.rs b/crates/ui/src/notes/panel.rs index c3b089a21..243f2df34 100644 --- a/crates/ui/src/notes/panel.rs +++ b/crates/ui/src/notes/panel.rs @@ -29,10 +29,7 @@ pub(super) struct Draft { impl Default for Draft { fn default() -> Self { - Self { - name: String::new(), - focus: true, - } + Self { name: String::new(), focus: true } } } @@ -46,11 +43,7 @@ pub(super) struct Words { impl Words { pub(super) fn new(language: i18n::Language, field: Key, hint: Key, submit: Key) -> Self { let tr = |key| i18n::translate(language, key, &[]); - Self { - field: tr(field), - hint: tr(hint), - submit: tr(submit), - } + Self { field: tr(field), hint: tr(hint), submit: tr(submit) } } } @@ -95,13 +88,7 @@ enum Renamed { Escaped, } -fn rename_field( - ui: &mut Ui, - name: &mut String, - focus: &mut bool, - label: &str, - id: &str, -) -> Renamed { +fn rename_field(ui: &mut Ui, name: &mut String, focus: &mut bool, label: &str, id: &str) -> Renamed { let field = TextField::new(name, label, id).compact().show(ui); if std::mem::take(focus) { field.request_focus(); @@ -109,12 +96,8 @@ fn rename_field( if !field.lost_focus() { return Renamed::Kept; } - let (enter, escape) = ui.input(|input| { - ( - input.key_pressed(egui::Key::Enter), - input.key_pressed(egui::Key::Escape), - ) - }); + let (enter, escape) = + ui.input(|input| (input.key_pressed(egui::Key::Enter), input.key_pressed(egui::Key::Escape))); if escape { Renamed::Escaped } else if enter { @@ -162,37 +145,15 @@ pub(super) fn space( let mut close = false; frame(ui, |ui| { title(ui, &space.name); - let pin = tr(if space.pinned { - keys::notes::UNPIN_SPACE - } else { - keys::notes::PIN_SPACE - }); + let pin = tr(if space.pinned { keys::notes::UNPIN_SPACE } else { keys::notes::PIN_SPACE }); if pin_toggle(ui, &pin, space.pinned).clicked() { - push( - actions, - Action::PinSpace { - id: space.id.clone(), - pinned: !space.pinned, - }, - ); + push(actions, Action::PinSpace { id: space.id.clone(), pinned: !space.pinned }); } let label = tr(keys::notes::RENAME_SPACE_LABEL); let rename = |actions: &mut Actions, name: String| { - push( - actions, - Action::RenameSpace { - id: space.id.clone(), - name, - }, - ); + push(actions, Action::RenameSpace { id: space.id.clone(), name }); }; - match rename_field( - ui, - &mut edit.name, - &mut edit.focus, - &label, - "space-rename-input", - ) { + match rename_field(ui, &mut edit.name, &mut edit.focus, &label, "space-rename-input") { Renamed::Kept => {} Renamed::Left(name) => rename(actions, name), Renamed::Entered(name) => { @@ -202,19 +163,12 @@ pub(super) fn space( Renamed::Escaped => close = true, } let submit = tr(keys::notes::RENAME_SPACE_SUBMIT); - if Button::new(&submit, "space-rename-submit") - .show(ui) - .clicked() - { + if Button::new(&submit, "space-rename-submit").show(ui).clicked() { rename(actions, edit.name.clone()); close = true; } if others.is_empty() { - note( - ui, - &tr(keys::notes::DELETE_SPACE_NEEDS_ANOTHER), - "space-delete-blocked", - ); + note(ui, &tr(keys::notes::DELETE_SPACE_NEEDS_ANOTHER), "space-delete-blocked"); return; } close |= deletion(ui, edit, space, others, contents, language, actions); @@ -245,17 +199,11 @@ fn pin_toggle(ui: &mut Ui, label: &str, on: bool) -> Response { if response.hovered() { ui.painter().rect_filled(rect, corner, p.bg_2); } - let glyph = Rect::from_center_size( - egui::pos2(rect.left() + 14.0, rect.center().y), - Vec2::splat(12.0), - ); + let glyph = Rect::from_center_size(egui::pos2(rect.left() + 14.0, rect.center().y), Vec2::splat(12.0)); icons::paint(ui, glyph, Icon::Pin, ink); let galley = widgets::text(ui, label, font::META, 400.0, FontFamily::Proportional, ink); - ui.painter().galley( - egui::pos2(rect.left() + 26.0, rect.center().y - galley.size().y / 2.0), - galley, - ink, - ); + ui.painter() + .galley(egui::pos2(rect.left() + 26.0, rect.center().y - galley.size().y / 2.0), galley, ink); response } @@ -281,18 +229,12 @@ fn deletion( }); note(ui, &move_to, "space-move-label"); edit.refuge = edit.refuge.min(others.len() - 1); - let options: Vec<(usize, &str)> = others - .iter() - .enumerate() - .map(|(at, other)| (at, other.name.as_str())) - .collect(); + let options: Vec<(usize, &str)> = + others.iter().enumerate().map(|(at, other)| (at, other.name.as_str())).collect(); ChoiceMenu::new(&move_to, "space-move-target", &options).show(ui, &mut edit.refuge); let refuge = others[edit.refuge]; - let label = tr(if edit.confirming { - keys::notes::DELETE_SPACE_CONFIRM - } else { - keys::notes::DELETE_SPACE - }); + let label = + tr(if edit.confirming { keys::notes::DELETE_SPACE_CONFIRM } else { keys::notes::DELETE_SPACE }); let mut close = false; let delete = Button::new(&label, "space-delete") .kind(Kind::Destructive) @@ -302,11 +244,7 @@ fn deletion( if edit.confirming { push( actions, - Action::DeleteSpace { - id: space.id.clone(), - refuge: refuge.id.clone(), - held: edit.held, - }, + Action::DeleteSpace { id: space.id.clone(), refuge: refuge.id.clone(), held: edit.held }, ); close = true; } else { @@ -314,34 +252,20 @@ fn deletion( } } if let Some(contents) = contents { - note( - ui, - &consequences(*contents, (&refuge.name, edit.held), language), - "space-delete-consequence", - ); + note(ui, &consequences(*contents, (&refuge.name, edit.held), language), "space-delete-consequence"); } close } /// What becomes of the notes: kept, as before, or put in the trash with what holds them. `true` /// when the choice changed. -fn held_choice( - ui: &mut Ui, - held: &mut HeldNotes, - author_id: &str, - language: i18n::Language, -) -> bool { +fn held_choice(ui: &mut Ui, held: &mut HeldNotes, author_id: &str, language: i18n::Language) -> bool { let tr = |key| i18n::translate(language, key, &[]); let label = tr(keys::notes::HELD_NOTES); note(ui, &label, &format!("{author_id}-label")); let (keep, trash) = (tr(keys::notes::KEEP_NOTES), tr(keys::notes::TRASH_NOTES)); - let options = [ - (HeldNotes::Keep, keep.as_str()), - (HeldNotes::Trash, trash.as_str()), - ]; - ChoiceMenu::new(&label, author_id, &options) - .show(ui, held) - .changed() + let options = [(HeldNotes::Keep, keep.as_str()), (HeldNotes::Trash, trash.as_str())]; + ChoiceMenu::new(&label, author_id, &options).show(ui, held).changed() } /// The notes and where they go, or that they go to the trash and come back there; then the @@ -358,20 +282,13 @@ fn consequences( HeldNotes::Keep => keys::notes::DELETE_SPACE_NOTES, HeldNotes::Trash => keys::notes::DELETE_SPACE_TRASH_NOTES, }; - i18n::translate( - language, - key, - &[("count", contents.notes.into()), ("refuge", refuge.into())], - ) + i18n::translate(language, key, &[("count", contents.notes.into()), ("refuge", refuge.into())]) }; if contents.folders == 0 { return notes; } - let folders = i18n::translate( - language, - keys::notes::DELETE_SPACE_FOLDERS, - &[("count", contents.folders.into())], - ); + let folders = + i18n::translate(language, keys::notes::DELETE_SPACE_FOLDERS, &[("count", contents.folders.into())]); format!("{notes} {folders}") } @@ -413,21 +330,9 @@ pub(super) fn folder( colours(ui, folder, language, actions); let label = tr(keys::folders::RENAME_LABEL); let rename = |actions: &mut Actions, name: String| { - push( - actions, - Action::RenameFolder { - id: folder.id.clone(), - name, - }, - ); + push(actions, Action::RenameFolder { id: folder.id.clone(), name }); }; - match rename_field( - ui, - &mut edit.name, - &mut edit.focus, - &label, - "folder-rename-input", - ) { + match rename_field(ui, &mut edit.name, &mut edit.focus, &label, "folder-rename-input") { Renamed::Kept => {} Renamed::Left(name) => rename(actions, name), Renamed::Entered(name) => { @@ -437,10 +342,7 @@ pub(super) fn folder( Renamed::Escaped => close = true, } let submit = tr(keys::folders::RENAME_SUBMIT); - if Button::new(&submit, "folder-rename-submit") - .show(ui) - .clicked() - { + if Button::new(&submit, "folder-rename-submit").show(ui).clicked() { rename(actions, edit.name.clone()); close = true; } @@ -449,24 +351,14 @@ pub(super) fn folder( if held_choice(ui, &mut edit.held, "folder-delete-held", language) { edit.confirming = false; } - let label = tr(if edit.confirming { - keys::folders::DELETE_CONFIRM - } else { - keys::folders::DELETE - }); + let label = tr(if edit.confirming { keys::folders::DELETE_CONFIRM } else { keys::folders::DELETE }); let delete = Button::new(&label, "folder-delete") .kind(Kind::Destructive) .armed(edit.confirming) .show(ui); if delete.clicked() { if edit.confirming { - push( - actions, - Action::DeleteFolder { - id: folder.id.clone(), - held: edit.held, - }, - ); + push(actions, Action::DeleteFolder { id: folder.id.clone(), held: edit.held }); close = true; } else { edit.confirming = true; @@ -481,20 +373,10 @@ pub(super) fn folder( } /// What the folder's deletion does to the notes and the sub-folders under it, counted by the core. -fn folder_consequences( - contents: FolderContents, - held: HeldNotes, - language: i18n::Language, -) -> String { +fn folder_consequences(contents: FolderContents, held: HeldNotes, language: i18n::Language) -> String { let (notes, folders) = match held { - HeldNotes::Keep => ( - keys::folders::DELETE_KEEP_NOTES, - keys::folders::DELETE_KEEP_FOLDERS, - ), - HeldNotes::Trash => ( - keys::folders::DELETE_TRASH_NOTES, - keys::folders::DELETE_TRASH_FOLDERS, - ), + HeldNotes::Keep => (keys::folders::DELETE_KEEP_NOTES, keys::folders::DELETE_KEEP_FOLDERS), + HeldNotes::Trash => (keys::folders::DELETE_TRASH_NOTES, keys::folders::DELETE_TRASH_FOLDERS), }; let notes = i18n::translate(language, notes, &[("count", contents.notes.into())]); if contents.folders == 0 { @@ -513,10 +395,7 @@ fn sub_folder( ) -> bool { let Some(draft) = &mut edit.nesting else { let open = i18n::translate(language, keys::folders::NEW_SUBFOLDER, &[]); - if Button::new(&open, "folder-subfolder-open") - .show(ui) - .clicked() - { + if Button::new(&open, "folder-subfolder-open").show(ui).clicked() { edit.nesting = Some(Draft::default()); } return false; @@ -568,13 +447,7 @@ fn colours(ui: &mut Ui, folder: &Folder, language: i18n::Language, actions: &mut ); swatch(ui, &response, folder_hue(ui, colour), on); if response.clicked() && !on { - push( - actions, - Action::RecolourFolder { - id: folder.id.clone(), - colour, - }, - ); + push(actions, Action::RecolourFolder { id: folder.id.clone(), colour }); } } }); @@ -582,11 +455,7 @@ fn colours(ui: &mut Ui, folder: &Folder, language: i18n::Language, actions: &mut fn swatch(ui: &Ui, response: &Response, hue: Color32, on: bool) { let rect = Rect::from_center_size(response.rect.center(), Vec2::splat(18.0)); - let shown = if on || response.hovered() { - hue - } else { - hue.gamma_multiply(0.45) - }; + let shown = if on || response.hovered() { hue } else { hue.gamma_multiply(0.45) }; let corner = CornerRadius::same(radius::TAG); ui.painter().rect_filled(rect, corner, shown); if on { @@ -612,12 +481,7 @@ fn colour_name(colour: FolderColour) -> i18n::Key { /// Not indented with its row: the rail is narrow enough. fn frame(ui: &mut Ui, content: impl FnOnce(&mut Ui)) { egui::Frame::new() - .inner_margin(egui::Margin { - left: 4, - right: 4, - top: 6, - bottom: 10, - }) + .inner_margin(egui::Margin { left: 4, right: 4, top: 6, bottom: 10 }) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = gap::CONTROLS; content(ui); @@ -627,14 +491,7 @@ fn frame(ui: &mut Ui, content: impl FnOnce(&mut Ui)) { fn title(ui: &mut Ui, name: &str) { let p = palette(ui.ctx()); let upper = name.to_uppercase(); - let galley = widgets::text( - ui, - &upper, - font::META, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &upper, font::META, 600.0, FontFamily::Proportional, p.text_2); let (rect, _) = ui.allocate_exact_size(galley.size(), Sense::hover()); ui.painter().galley(rect.min, galley, p.text_2); } @@ -644,10 +501,7 @@ fn note(ui: &mut Ui, words: &str, author_id: &str) { let p = palette(ui.ctx()); let mut job = egui::text::LayoutJob::single_section( words.to_owned(), - egui::TextFormat::simple( - egui::FontId::new(font::META, FontFamily::Proportional), - p.text_2, - ), + egui::TextFormat::simple(egui::FontId::new(font::META, FontFamily::Proportional), p.text_2), ); job.wrap.max_width = ui.available_width().max(1.0); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); diff --git a/crates/ui/src/notes/parity_tests.rs b/crates/ui/src/notes/parity_tests.rs index b9c8bc6fc..5aa8b0127 100644 --- a/crates/ui/src/notes/parity_tests.rs +++ b/crates/ui/src/notes/parity_tests.rs @@ -13,37 +13,25 @@ use crate::state::Area; use crate::testing; fn present(harness: &Harness<'_, Bench>, author_id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(author_id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(author_id)).is_some() } fn rect(harness: &Harness<'_, Bench>, author_id: &str) -> egui::Rect { - harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() + harness.get_by(|node| node.author_id() == Some(author_id)).rect() } fn hover_first_card(harness: &mut Harness<'_, Bench>) { - harness - .get_by(|node| node.author_id() == Some("note-card-open")) - .hover(); + harness.get_by(|node| node.author_id() == Some("note-card-open")).hover(); settle(harness); } /// `title`, of `kind`, holding `content`, through the core. fn note(backend: &Backend, title: &str, kind: NoteKind, content: &str) -> String { let id = testing::note(backend, title).id.clone(); - let patch = NotePatch { - kind: Some(kind), - content: Some(content.to_owned()), - ..NotePatch::default() - }; + let patch = NotePatch { kind: Some(kind), content: Some(content.to_owned()), ..NotePatch::default() }; let at = id.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); id } @@ -56,10 +44,7 @@ fn the_controls_of_the_header_stand_on_one_line() { let middle = rect(&harness, "new-note").center().y; for author_id in ["sort-trigger", "facets-toggle", "quick-filter-0"] { let off = (rect(&harness, author_id).center().y - middle).abs(); - assert!( - off <= 1.0, - "{author_id} is {off} away from the row's middle" - ); + assert!(off <= 1.0, "{author_id} is {off} away from the row's middle"); } } @@ -103,15 +88,11 @@ fn a_search_that_finds_nothing_offers_to_clear_it() { harness .get_by(|node| node.author_id() == Some("search-input")) .type_text("zzzz"); - until(&mut harness, "the search found nothing", |harness| { - present(harness, "canvas-clear-filters") - }); + until(&mut harness, "the search found nothing", |harness| present(harness, "canvas-clear-filters")); click_id(&mut harness, "canvas-clear-filters"); - until(&mut harness, "the card is back", |harness| { - cards(harness) == 1 - }); + until(&mut harness, "the card is back", |harness| cards(harness) == 1); } #[test] @@ -203,10 +184,7 @@ fn the_priorities_of_a_card_menu_close_when_the_pointer_leaves_them() { .unwrap() .click(); settle(&mut harness); - assert!( - !present(&harness, "note-card-priority"), - "a pick closes the menu" - ); + assert!(!present(&harness, "note-card-priority"), "a pick closes the menu"); } fn open_palette(harness: &mut Harness<'_, Bench>) { @@ -234,12 +212,7 @@ fn type_in_palette(harness: &mut Harness<'_, Bench>, words: &str) { fn with_a_request() -> Harness<'static, Bench> { let (backend, profile) = testing::unlocked(); let api = crate::http::tests::collection(&backend, "API"); - crate::http::tests::request( - &backend, - (&api, None), - "Lister", - (RequestKind::Http, HttpMethod::Get), - ); + crate::http::tests::request(&backend, (&api, None), "Lister", (RequestKind::Http, HttpMethod::Get)); area(backend, profile) } @@ -253,9 +226,7 @@ fn the_palette_recalls_the_requests_and_opens_one_in_its_area() { type_in_palette(&mut harness, "Lister"); until(&mut harness, "the request alone is found", |harness| { - options(harness) - .first() - .is_some_and(|name| name == "Lister") + options(harness).first().is_some_and(|name| name == "Lister") }); harness.key_press(Key::Enter); settle(&mut harness); @@ -272,9 +243,7 @@ fn the_palette_finds_a_tool_by_its_name_first_and_opens_it() { open_palette(&mut harness); type_in_palette(&mut harness, "json"); - until(&mut harness, "the tools are found", |harness| { - !options(harness).is_empty() - }); + until(&mut harness, "the tools are found", |harness| !options(harness).is_empty()); let first = options(&harness).remove(0); assert!(first.to_lowercase().contains("json"), "{first} comes first"); harness.key_press(Key::Enter); @@ -293,18 +262,14 @@ fn the_palette_narrows_to_requests_and_to_tools_with_a_chip() { type_in_palette(&mut harness, "@requests"); harness.key_press(Key::Tab); settle(&mut harness); - until(&mut harness, "only the request is left", |harness| { - options(harness) == ["Lister"] - }); + until(&mut harness, "only the request is left", |harness| options(harness) == ["Lister"]); harness.key_press(Key::Backspace); settle(&mut harness); type_in_palette(&mut harness, "@tools"); harness.key_press(Key::Tab); settle(&mut harness); - until(&mut harness, "the tools are listed", |harness| { - options(harness).len() >= 3 - }); + until(&mut harness, "the tools are listed", |harness| options(harness).len() >= 3); } #[test] @@ -314,9 +279,7 @@ fn the_palette_runs_the_commands_of_the_other_areas() { open_palette(&mut harness); type_in_palette(&mut harness, "> new request"); - until(&mut harness, "the command is offered", |harness| { - options(harness).len() == 1 - }); + until(&mut harness, "the command is offered", |harness| options(harness).len() == 1); harness.key_press(Key::Enter); settle(&mut harness); @@ -330,9 +293,7 @@ fn the_palette_says_how_many_fields_a_note_waits_for() { let mut harness = area(backend, profile); open_palette(&mut harness); - until(&mut harness, "the note is recalled", |harness| { - options(harness).iter().any(|name| name == "psql") - }); + until(&mut harness, "the note is recalled", |harness| options(harness).iter().any(|name| name == "psql")); } #[test] @@ -352,20 +313,13 @@ fn a_drawing_is_inserted_from_the_toolbar_of_a_note() { let (backend, profile) = testing::unlocked(); let written = note(&backend, "Procédure", NoteKind::Note, "# Titre"); let scene = testing::note(&backend, "Schéma").id.clone(); - let patch = NotePatch { - kind: Some(NoteKind::Drawing), - ..NotePatch::default() - }; + let patch = NotePatch { kind: Some(NoteKind::Drawing), ..NotePatch::default() }; let at = scene.clone(); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::update_note(engine, &at, &patch) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::update_note(engine, &at, &patch)) + .unwrap(); let mut harness = crate::notes::bench::expanded_area(backend, profile); click(&mut harness, "note-card-open", "Procédure"); - until(&mut harness, "the toolbar offers the drawing", |harness| { - present(harness, "rich-embed-drawing") - }); + until(&mut harness, "the toolbar offers the drawing", |harness| present(harness, "rich-embed-drawing")); click_id(&mut harness, "rich-embed-drawing"); click_id(&mut harness, "rich-embed-drawing-0"); @@ -373,15 +327,10 @@ fn a_drawing_is_inserted_from_the_toolbar_of_a_note() { settle(&mut harness); let backend = &harness.state().backend; - let stored = engine::db::run_here(backend.engine(), move |engine| { - engine::notes::get_note(engine, &written) - }) - .unwrap(); - assert!( - stored - .content - .contains(&format!("devnotes:drawing/{scene}")) - ); + let stored = + engine::db::run_here(backend.engine(), move |engine| engine::notes::get_note(engine, &written)) + .unwrap(); + assert!(stored.content.contains(&format!("devnotes:drawing/{scene}"))); } #[test] @@ -390,9 +339,7 @@ fn a_sheet_sets_its_decimals_from_its_footer() { note(&backend, "Budget", NoteKind::Calc, "total = 10 + 3"); let mut harness = area(backend, profile); click(&mut harness, "note-card-open", "Budget"); - until(&mut harness, "the sheet is open", |harness| { - present(harness, "calc-decimals") - }); + until(&mut harness, "the sheet is open", |harness| present(harness, "calc-decimals")); click_id(&mut harness, "calc-decimals"); click_id(&mut harness, "calc-decimals-3"); diff --git a/crates/ui/src/notes/pointer_tests.rs b/crates/ui/src/notes/pointer_tests.rs index 1ada1b872..701b20b9c 100644 --- a/crates/ui/src/notes/pointer_tests.rs +++ b/crates/ui/src/notes/pointer_tests.rs @@ -29,14 +29,8 @@ fn a_hand_over_what_clicks_an_i_beam_over_text() { let mut harness = area(backend, profile); assert_eq!(over(&mut harness, "new-note"), CursorIcon::PointingHand); - assert_eq!( - over(&mut harness, "note-card-open"), - CursorIcon::PointingHand - ); - assert_eq!( - over(&mut harness, "folder-option"), - CursorIcon::PointingHand - ); + assert_eq!(over(&mut harness, "note-card-open"), CursorIcon::PointingHand); + assert_eq!(over(&mut harness, "folder-option"), CursorIcon::PointingHand); assert_eq!(over(&mut harness, "search-input"), CursorIcon::Text); click_id(&mut harness, "note-card-open"); @@ -61,17 +55,11 @@ fn a_row_dragged_closes_the_hand() { crate::notes::bench::folder(&backend, &home, None, "Runbooks"); let mut harness = area(backend, profile); - let row = harness - .get_by(|node| node.author_id() == Some("folder-option")) - .rect() - .center(); + let row = harness.get_by(|node| node.author_id() == Some("folder-option")).rect().center(); harness.drag_at(row); harness.run(); harness.event(egui::Event::PointerMoved(row + egui::vec2(0.0, 30.0))); harness.run(); - assert_eq!( - harness.output().platform_output.cursor_icon, - CursorIcon::Grabbing - ); + assert_eq!(harness.output().platform_output.cursor_icon, CursorIcon::Grabbing); } diff --git a/crates/ui/src/notes/prettier.rs b/crates/ui/src/notes/prettier.rs index a21cb37c5..2c5786ce8 100644 --- a/crates/ui/src/notes/prettier.rs +++ b/crates/ui/src/notes/prettier.rs @@ -19,12 +19,8 @@ pub enum Indentation { } impl Indentation { - pub const ALL: [Indentation; 4] = [ - Indentation::Editor, - Indentation::Two, - Indentation::Four, - Indentation::Tab, - ]; + pub const ALL: [Indentation; 4] = + [Indentation::Editor, Indentation::Two, Indentation::Four, Indentation::Tab]; fn id(self) -> &'static str { match self { @@ -37,10 +33,7 @@ impl Indentation { } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -#[expect( - clippy::struct_excessive_bools, - reason = "the switches as the reference stored them" -)] +#[expect(clippy::struct_excessive_bools, reason = "the switches as the reference stored them")] pub struct PrettierSettings { pub print_width: u32, pub indentation: Indentation, @@ -67,12 +60,10 @@ impl PrettierSettings { /// Trusted no further than it reads: what the file does not name stays default. pub fn read(stored: Option<&str>) -> Self { let fallback = Self::default(); - let Some(Value::Object(value)) = stored.and_then(|text| serde_json::from_str(text).ok()) - else { + let Some(Value::Object(value)) = stored.and_then(|text| serde_json::from_str(text).ok()) else { return fallback; }; - let flag = - |key: &str, default: bool| value.get(key).and_then(Value::as_bool).unwrap_or(default); + let flag = |key: &str, default: bool| value.get(key).and_then(Value::as_bool).unwrap_or(default); let indentation = value.get("indentation").and_then(Value::as_str); Self { print_width: value @@ -118,11 +109,7 @@ impl PrettierSettings { let tabs = indent == "\t"; Options { print_width: self.print_width, - tab_width: if tabs { - TAB_WIDTH - } else { - u32::try_from(indent.len()).unwrap_or(2) - }, + tab_width: if tabs { TAB_WIDTH } else { u32::try_from(indent.len()).unwrap_or(2) }, use_tabs: tabs, single_quote: self.single_quote, semi: self.semicolons, @@ -138,11 +125,7 @@ pub fn clamp_width(value: f64) -> Option { } let (min, max) = WIDTH_RANGE; let clamped = value.round().clamp(f64::from(min), f64::from(max)); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "clamped to a few hundred" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "clamped to a few hundred")] let width = clamped as u32; Some(width) } @@ -160,10 +143,7 @@ mod tests { assert_eq!(read.indentation, Indentation::Tab); assert!(!read.single_quote); assert!(read.semicolons, "not a boolean: the default"); - assert_eq!( - PrettierSettings::read(Some("{")), - PrettierSettings::default() - ); + assert_eq!(PrettierSettings::read(Some("{")), PrettierSettings::default()); assert_eq!(PrettierSettings::read(Some(&read.written())), read); } @@ -171,14 +151,42 @@ mod tests { fn the_editor_s_level_is_the_language_s_and_a_tab_counts_four() { let settings = PrettierSettings::default(); assert_eq!(settings.options(" ").tab_width, 4); - let tabs = PrettierSettings { - indentation: Indentation::Tab, - ..settings - } - .options(" "); + let tabs = PrettierSettings { indentation: Indentation::Tab, ..settings }.options(" "); assert!(tabs.use_tabs); assert_eq!(tabs.tab_width, 4); assert_eq!(clamp_width(12.4), Some(40)); assert_eq!(clamp_width(f64::NAN), None); } + + #[test] + fn what_is_written_reads_back_the_same() { + for indentation in Indentation::ALL { + for single_quote in [true, false] { + let settings = PrettierSettings { + print_width: 88, + indentation, + single_quote, + semicolons: single_quote, + trailing_commas: !single_quote, + format_on_save: single_quote, + }; + assert_eq!(PrettierSettings::read(Some(&settings.written())), settings); + } + } + } + + #[test] + fn each_indentation_is_what_prettier_is_asked() { + for (indentation, editor, (width, tabs)) in [ + (Indentation::Editor, " ", (3, false)), + (Indentation::Editor, "\t", (TAB_WIDTH, true)), + (Indentation::Two, " ", (2, false)), + (Indentation::Four, " ", (4, false)), + (Indentation::Tab, " ", (TAB_WIDTH, true)), + ] { + let settings = PrettierSettings { indentation, ..PrettierSettings::default() }; + let options = settings.options(editor); + assert_eq!((options.tab_width, options.use_tabs), (width, tabs), "{indentation:?}"); + } + } } diff --git a/crates/ui/src/notes/sidebar/mod.rs b/crates/ui/src/notes/sidebar/mod.rs index 35d5380ec..70c3dc577 100644 --- a/crates/ui/src/notes/sidebar/mod.rs +++ b/crates/ui/src/notes/sidebar/mod.rs @@ -85,12 +85,7 @@ impl SidebarView { pub fn show(ui: &mut Ui, state: &AppState, view: &mut SidebarView, actions: &mut Actions) { let s = spacing(ui.ctx()); - let margin = Margin { - left: 10, - right: 10, - top: to_margin(s.card), - bottom: to_margin(s.canvas), - }; + let margin = Margin { left: 10, right: 10, top: to_margin(s.card), bottom: to_margin(s.canvas) }; egui::Frame::new().inner_margin(margin).show(ui, |ui| { ui.set_min_height(ui.available_height()); ui.spacing_mut().item_spacing.y = gap::SNUG; @@ -114,12 +109,10 @@ pub fn show(ui: &mut Ui, state: &AppState, view: &mut SidebarView, actions: &mut panel::Typed::Typing => {} } } - egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 0.0; - tree_rows(ui, state, view, actions); - }); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + ui.spacing_mut().item_spacing.y = 0.0; + tree_rows(ui, state, view, actions); + }); }); } @@ -139,14 +132,7 @@ fn head(ui: &mut Ui, view: &mut SidebarView, language: i18n::Language) { ui.horizontal(|ui| { ui.add_space(gap::TIGHT); let title = i18n::translate(language, keys::sidebar::LIBRARY, &[]).to_uppercase(); - let galley = widgets::text( - ui, - &title, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &title, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); let room = ui.available_width() - widgets::MIN_TARGET - ui.spacing().item_spacing.x; let (rect, _) = ui.allocate_exact_size(egui::vec2(room, 24.0), egui::Sense::hover()); ui.painter().galley( @@ -155,10 +141,7 @@ fn head(ui: &mut Ui, view: &mut SidebarView, language: i18n::Language) { p.text_2, ); let label = i18n::translate(language, keys::notes::NEW_SPACE, &[]); - if IconButton::new(Icon::Plus, &label, "space-create-open") - .show(ui) - .clicked() - { + if IconButton::new(Icon::Plus, &label, "space-create-open").show(ui).clicked() { view.panel = Panel::NewSpace(Draft::default()); } }); @@ -168,12 +151,7 @@ fn tree_rows(ui: &mut Ui, state: &AppState, view: &mut SidebarView, actions: &mu let language = state.language; let spaces = &state.spaces; let active_space = spaces.active_space(); - let rows = tree::rows( - spaces.spaces(), - state.folders.list(), - active_space, - &view.collapsed, - ); + let rows = tree::rows(spaces.spaces(), state.folders.list(), active_space, &view.collapsed); view.rows.clear(); for row in rows { match row { @@ -194,17 +172,8 @@ fn tree_rows(ui: &mut Ui, state: &AppState, view: &mut SidebarView, actions: &mu Row::Space { space, open } => { space_row(ui, state, view, actions, space, open); } - Row::Folder { - folder, - depth, - nested, - open, - } => { - let at = Place { - depth, - nested, - open, - }; + Row::Folder { folder, depth, nested, open } => { + let at = Place { depth, nested, open }; folder_row(ui, state, view, actions, folder, at); } Row::NewFolder { space } => new_folder(ui, view, actions, &space.id, language), @@ -213,20 +182,13 @@ fn tree_rows(ui: &mut Ui, state: &AppState, view: &mut SidebarView, actions: &mu ui.horizontal(|ui| { ui.add_space(row::INDENT + 8.0); let words = i18n::translate(language, keys::sidebar::NO_FOLDERS, &[]); - let galley = widgets::text( - ui, - &words, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = + widgets::text(ui, &words, font::META, 400.0, FontFamily::Proportional, p.text_2); let (rect, _) = ui.allocate_exact_size( egui::vec2(galley.size().x, galley.size().y + 8.0), egui::Sense::hover(), ); - ui.painter() - .galley(rect.min + egui::vec2(0.0, 4.0), galley, p.text_2); + ui.painter().galley(rect.min + egui::vec2(0.0, 4.0), galley, p.text_2); }); } } @@ -247,11 +209,7 @@ fn folder_row( view: &mut SidebarView, actions: &mut Actions, folder: &engine::folders::model::Folder, - Place { - depth, - nested, - open, - }: Place, + Place { depth, nested, open }: Place, ) { let language = state.language; let active_folder = state.active_folder(); @@ -259,20 +217,12 @@ fn folder_row( open, label: i18n::translate( language, - if open { - keys::sidebar::COLLAPSE_FOLDER - } else { - keys::sidebar::EXPAND_FOLDER - }, + if open { keys::sidebar::COLLAPSE_FOLDER } else { keys::sidebar::EXPAND_FOLDER }, &[("name", folder.name.as_str().into())], ), author_id: "folder-twisty", }; - let lead = if nested { - Lead::Twisty(twisty) - } else { - Lead::Blank - }; + let lead = if nested { Lead::Twisty(twisty) } else { Lead::Blank }; let name = Name { label: folder.name.clone(), author_id: "folder-option", @@ -280,11 +230,8 @@ fn folder_row( active: active_folder == Some(folder.id.as_str()), lit: view.lit(&folder.id), }; - let menu = i18n::translate( - language, - keys::folders::OPTIONS_LABEL, - &[("name", folder.name.as_str().into())], - ); + let menu = + i18n::translate(language, keys::folders::OPTIONS_LABEL, &[("name", folder.name.as_str().into())]); let drawn = row::show(ui, depth + 1, &lead, &name, Some((&menu, "folder-edit"))); view.rows.push(RailRow { rect: drawn.name.rect, @@ -300,10 +247,7 @@ fn folder_row( } if drawn.name.clicked() { view.panel = Panel::None; - push( - actions, - crate::notes::Action::ChooseFolder(folder.id.clone()), - ); + push(actions, crate::notes::Action::ChooseFolder(folder.id.clone())); } if drawn.menu.is_some_and(|menu| menu.clicked()) { view.panel = match &view.panel { @@ -340,11 +284,7 @@ fn space_row( open, label: i18n::translate( language, - if open { - keys::sidebar::COLLAPSE - } else { - keys::sidebar::EXPAND - }, + if open { keys::sidebar::COLLAPSE } else { keys::sidebar::EXPAND }, &named, ), author_id: "space-twisty", @@ -352,38 +292,21 @@ fn space_row( let name = Name { label: space.name.clone(), author_id: "space-option", - mark: if space.pinned { - Mark::Pin - } else { - Mark::Nothing - }, - active: state.spaces.active_space() == Some(space.id.as_str()) - && state.active_folder().is_none(), + mark: if space.pinned { Mark::Pin } else { Mark::Nothing }, + active: state.spaces.active_space() == Some(space.id.as_str()) && state.active_folder().is_none(), lit: view.lit(&space.id), }; let menu = i18n::translate(language, keys::notes::SPACE_OPTIONS_LABEL, &named); - let drawn = row::show( - ui, - 0, - &Lead::Twisty(twisty), - &name, - Some((&menu, "space-edit")), - ); - view.rows.push(RailRow { - rect: drawn.name.rect, - space_id: space.id.clone(), - folder_id: None, - }); + let drawn = row::show(ui, 0, &Lead::Twisty(twisty), &name, Some((&menu, "space-edit"))); + view.rows + .push(RailRow { rect: drawn.name.rect, space_id: space.id.clone(), folder_id: None }); if drawn.twisty.is_some_and(|twisty| twisty.clicked()) { view.toggle(&space.id); } if drawn.name.clicked() { view.panel = Panel::None; view.reveal(&space.id); - push( - actions, - crate::notes::Action::ChooseSpace(Some(space.id.clone())), - ); + push(actions, crate::notes::Action::ChooseSpace(Some(space.id.clone()))); } if drawn.menu.is_some_and(|menu| menu.clicked()) { view.panel = match &view.panel { @@ -394,12 +317,7 @@ fn space_row( if let Panel::Space(edit) = &mut view.panel && edit.id == space.id { - let targets: Vec<_> = state - .spaces - .spaces() - .iter() - .filter(|other| other.id != space.id) - .collect(); + let targets: Vec<_> = state.spaces.spaces().iter().filter(|other| other.id != space.id).collect(); let contents = state.spaces.contents(&space.id); if panel::space(ui, edit, space, &targets, contents, language, actions) { view.panel = Panel::None; @@ -439,14 +357,7 @@ fn drop_folder(ui: &Ui, view: &mut SidebarView, actions: &mut Actions) { view.dragging = None; view.lit = None; if let Some(row) = over { - push( - actions, - crate::notes::Action::MoveFolder { - id, - parent: row.folder_id, - space: row.space_id, - }, - ); + push(actions, crate::notes::Action::MoveFolder { id, parent: row.folder_id, space: row.space_id }); } } @@ -469,8 +380,7 @@ fn new_folder( let typed = ui .horizontal(|ui| { ui.add_space(row::INDENT); - ui.vertical(|ui| panel::name_form(ui, draft, &words, ids)) - .inner + ui.vertical(|ui| panel::name_form(ui, draft, &words, ids)).inner }) .inner; match typed { diff --git a/crates/ui/src/notes/sidebar/row.rs b/crates/ui/src/notes/sidebar/row.rs index 209120e2d..e0153f009 100644 --- a/crates/ui/src/notes/sidebar/row.rs +++ b/crates/ui/src/notes/sidebar/row.rs @@ -3,9 +3,7 @@ //! tooltip. The ⋯ sits over the end of the name: the name gives it room only when it shows. use crate::theme::tokens::{gap, radius}; -use egui::{ - Color32, CornerRadius, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2, vec2, -}; +use egui::{Color32, CornerRadius, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2, vec2}; use engine::folders::model::FolderColour; use crate::notes::ui::folder_hue; @@ -84,11 +82,7 @@ pub(super) fn show( }) .inner }); - Drawn { - twisty, - name: name_response, - menu, - } + Drawn { twisty, name: name_response, menu } }) .inner } @@ -102,8 +96,7 @@ fn level_lines(ui: &Ui, start: egui::Pos2, depth: usize) { for level in 0..depth { #[expect(clippy::cast_precision_loss, reason = "a few levels")] let x = start.x + level as f32 * INDENT + MIN_TARGET / 2.0; - ui.painter() - .vline(x.round() + 0.5, rows.clone(), Stroke::new(1.0, p.line)); + ui.painter().vline(x.round() + 0.5, rows.clone(), Stroke::new(1.0, p.line)); } } @@ -135,11 +128,7 @@ fn lead_column(ui: &mut Ui, lead: &Lead) -> Option { }, CornerRadius::same(radius::CONTROL), ); - let ink = if response.hovered() { - p.text_0 - } else { - p.text_2 - }; + let ink = if response.hovered() { p.text_0 } else { p.text_2 }; widgets::triangle(ui, response.rect.center(), twisty.open, ink); Some(response) } @@ -170,12 +159,8 @@ fn name_button(ui: &mut Ui, width: f32, kept: Option, name: &Name) -> Respo }; ui.painter().rect_filled(rect, corner, fill); if name.lit { - ui.painter().rect_stroke( - rect, - corner, - Stroke::new(1.0, p.amber_edge), - egui::StrokeKind::Inside, - ); + ui.painter() + .rect_stroke(rect, corner, Stroke::new(1.0, p.amber_edge), egui::StrokeKind::Inside); } let mut left = rect.left() + 8.0; let middle = rect.center().y; @@ -188,11 +173,8 @@ fn name_button(ui: &mut Ui, width: f32, kept: Option, name: &Name) -> Respo } Mark::Swatch(colour) => { let swatch = Rect::from_center_size(pos2(left + 4.0, middle), Vec2::splat(8.0)); - ui.painter().rect_filled( - swatch, - CornerRadius::same(radius::MARK), - folder_hue(ui, colour), - ); + ui.painter() + .rect_filled(swatch, CornerRadius::same(radius::MARK), folder_hue(ui, colour)); left += 8.0 + 6.0; } Mark::Plus => { @@ -201,11 +183,7 @@ fn name_button(ui: &mut Ui, width: f32, kept: Option, name: &Name) -> Respo left += 12.0 + 6.0; } } - let (size, ink) = if matches!(name.mark, Mark::Plus) { - (11.5, p.text_2) - } else { - (12.5, ink) - }; + let (size, ink) = if matches!(name.mark, Mark::Plus) { (11.5, p.text_2) } else { (12.5, ink) }; let galley = widgets::one_line( ui, &name.label, @@ -214,11 +192,8 @@ fn name_button(ui: &mut Ui, width: f32, kept: Option, name: &Name) -> Respo rect.right() - 8.0 - left - kept.unwrap_or(0.0), ); let cut = galley.elided; - ui.painter().galley( - pos2(left, middle - galley.size().y / 2.0), - galley, - Color32::TRANSPARENT, - ); + ui.painter() + .galley(pos2(left, middle - galley.size().y / 2.0), galley, Color32::TRANSPARENT); if cut { return widgets::tooltip(response, &name.label); } diff --git a/crates/ui/src/notes/sidebar/tests.rs b/crates/ui/src/notes/sidebar/tests.rs index ee1fefd50..8bd966640 100644 --- a/crates/ui/src/notes/sidebar/tests.rs +++ b/crates/ui/src/notes/sidebar/tests.rs @@ -6,8 +6,7 @@ use engine::folders::board::PreviewLines; use engine::folders::model::FolderColour; use crate::notes::bench::{ - Bench, area, cards, click, click_id, folder, names, remembered, settle, space, spaces_of, - type_and_enter, + Bench, area, cards, click, click_id, folder, names, remembered, settle, space, spaces_of, type_and_enter, }; use crate::state::spaces::ACTIVE_SPACE_KEY; use crate::testing; @@ -24,17 +23,10 @@ fn spaces_and_their_folders_are_a_tree() { let mut harness = area(backend, profile); assert_eq!(names(&harness, "space-option"), ["Home", "Work"]); - assert_eq!( - names(&harness, "folder-option"), - ["Archive", "Runbooks", "api"] - ); + assert_eq!(names(&harness, "folder-option"), ["Archive", "Runbooks", "api"]); harness.get_by(|node| node.author_id() == Some("space-option-all")); - click( - &mut harness, - "folder-twisty", - "Collapse the folder Runbooks", - ); + click(&mut harness, "folder-twisty", "Collapse the folder Runbooks"); assert_eq!(names(&harness, "folder-option"), ["Archive", "Runbooks"]); click(&mut harness, "space-twisty", "Collapse space Home"); assert!(names(&harness, "folder-option").is_empty()); @@ -46,20 +38,14 @@ fn a_space_chosen_narrows_the_canvas_and_is_remembered() { testing::note(&backend, "in home"); let work = space(&backend, "Work"); let draft = testing::snippet(work.id.clone(), "in work".into()); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::create_note(engine, draft) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::create_note(engine, draft)).unwrap(); let mut harness = area(backend, profile); assert_eq!(cards(&harness), 2); click(&mut harness, "space-option", "Work"); assert_eq!(cards(&harness), 1); - assert_eq!( - remembered(&harness, ACTIVE_SPACE_KEY).as_deref(), - Some(work.id.as_str()) - ); + assert_eq!(remembered(&harness, ACTIVE_SPACE_KEY).as_deref(), Some(work.id.as_str())); click_id(&mut harness, "space-option-all"); assert_eq!(cards(&harness), 2); } @@ -86,10 +72,7 @@ fn a_folder_chosen_shows_its_notes_in_its_space() { click(&mut harness, "folder-option", "Runbooks"); assert_eq!(cards(&harness), 1); - assert_eq!( - harness.state().state.spaces.active_space(), - Some(spaces[0].id.as_str()) - ); + assert_eq!(harness.state().state.spaces.active_space(), Some(spaces[0].id.as_str())); } #[test] @@ -102,14 +85,8 @@ fn a_space_is_created_from_the_head_and_shown() { type_and_enter(&mut harness, "space-create-input", "Reading"); assert_eq!(names(&harness, "space-option"), ["Home", "Reading"]); - let reading = spaces_of(&harness) - .into_iter() - .find(|space| space.name == "Reading") - .unwrap(); - assert_eq!( - harness.state().state.spaces.active_space(), - Some(reading.id.as_str()) - ); + let reading = spaces_of(&harness).into_iter().find(|space| space.name == "Reading").unwrap(); + assert_eq!(harness.state().state.spaces.active_space(), Some(reading.id.as_str())); assert_eq!(cards(&harness), 0); } @@ -140,11 +117,7 @@ fn the_only_space_cannot_be_deleted() { click(&mut harness, "space-edit", "Options for space Home"); harness.get_by(|node| node.author_id() == Some("space-delete-blocked")); - assert!( - harness - .query_by(|node| node.author_id() == Some("space-delete")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("space-delete")).is_none()); } #[test] @@ -154,10 +127,7 @@ fn deleting_a_space_says_where_its_notes_go_then_moves_them_there() { let reading = space(&backend, "Reading"); folder(&backend, &reading, None, "Read"); let draft = testing::snippet(reading.id.clone(), "an article".into()); - engine::db::run_here(backend.engine(), move |engine| { - engine::notes::create_note(engine, draft) - }) - .unwrap(); + engine::db::run_here(backend.engine(), move |engine| engine::notes::create_note(engine, draft)).unwrap(); let mut harness = area(backend, profile); click(&mut harness, "space-edit", "Options for space Reading"); @@ -173,10 +143,7 @@ fn deleting_a_space_says_where_its_notes_go_then_moves_them_there() { click_id(&mut harness, "space-delete"); assert_eq!(names(&harness, "space-option"), ["Home"]); - assert_eq!( - harness.state().state.spaces.active_space(), - Some(home.id.as_str()) - ); + assert_eq!(harness.state().state.spaces.active_space(), Some(home.id.as_str())); assert_eq!(cards(&harness), 1); } @@ -204,10 +171,7 @@ fn a_folder_is_made_recoloured_nested_and_deleted_from_the_rail() { }) .unwrap() }; - let runbooks = folders(&harness) - .into_iter() - .find(|folder| folder.name == "Runbooks") - .unwrap(); + let runbooks = folders(&harness).into_iter().find(|folder| folder.name == "Runbooks").unwrap(); assert_eq!(runbooks.colour, FolderColour::Green); click(&mut harness, "folder-edit", "Options for folder Runbooks"); @@ -256,12 +220,7 @@ fn parent_of(harness: &Harness<'_, Bench>, name: &str) -> Option { .iter() .find(|folder| folder.name == name) .and_then(|folder| folder.parent_id.clone())?; - harness - .state() - .state - .folders - .find(&parent) - .map(|folder| folder.name.clone()) + harness.state().state.folders.find(&parent).map(|folder| folder.name.clone()) } #[test] @@ -289,12 +248,7 @@ fn a_folder_dragged_onto_another_goes_inside_it_and_the_undo_bar_puts_it_back() let to = row(&harness, "folder-option", "Index").center(); drag(&mut harness, from, to); assert_eq!(parent_of(&harness, "Bases"), None); - let said = harness - .state() - .state - .status - .latest() - .map(|(_, message)| message.key); + let said = harness.state().state.status.latest().map(|(_, message)| message.key); assert_eq!(said, Some(i18n::keys::sidebar::moved::refused::THERE)); click_id(&mut harness, "undo-restore"); @@ -314,12 +268,7 @@ fn space_of(harness: &Harness<'_, Bench>, name: &str) -> String { } fn latest(harness: &Harness<'_, Bench>) -> Option { - harness - .state() - .state - .status - .latest() - .map(|(_, message)| message.key) + harness.state().state.status.latest().map(|(_, message)| message.key) } #[test] @@ -384,9 +333,7 @@ fn alt_and_the_arrows_move_a_folder_in_and_out_saying_what_they_refuse() { click(&mut harness, "space-option", "Home"); let press = |harness: &mut Harness<'_, Bench>, name: &str, key| { harness - .get_by(|node| { - node.author_id() == Some("folder-option") && node.label().as_deref() == Some(name) - }) + .get_by(|node| node.author_id() == Some("folder-option") && node.label().as_deref() == Some(name)) .focus(); harness.step(); harness.key_press_modifiers(egui::Modifiers::ALT, key); @@ -399,23 +346,11 @@ fn alt_and_the_arrows_move_a_folder_in_and_out_saying_what_they_refuse() { assert_eq!(parent_of(&harness, "Index"), None); press(&mut harness, "Bases", egui::Key::ArrowLeft); - let said = |harness: &Harness<'_, Bench>| { - harness - .state() - .state - .status - .latest() - .map(|(_, message)| message.key) - }; - assert_eq!( - said(&harness), - Some(i18n::keys::sidebar::moved::refused::AT_TOP) - ); + let said = + |harness: &Harness<'_, Bench>| harness.state().state.status.latest().map(|(_, message)| message.key); + assert_eq!(said(&harness), Some(i18n::keys::sidebar::moved::refused::AT_TOP)); press(&mut harness, "Bases", egui::Key::ArrowRight); - assert_eq!( - said(&harness), - Some(i18n::keys::sidebar::moved::refused::NO_FOLDER_ABOVE) - ); + assert_eq!(said(&harness), Some(i18n::keys::sidebar::moved::refused::NO_FOLDER_ABOVE)); } /// A folder in each of five levels, `Level 0` at the top: the names, from the top. @@ -437,15 +372,9 @@ fn each_level_of_folders_is_one_indent_further() { let names = five_levels(&backend); let harness = area(backend, profile); - let lefts: Vec = names - .iter() - .map(|name| row(&harness, "folder-option", name).left()) - .collect(); + let lefts: Vec = names.iter().map(|name| row(&harness, "folder-option", name).left()).collect(); for pair in lefts.windows(2) { - assert!( - (pair[1] - pair[0] - super::row::INDENT).abs() < 0.5, - "{lefts:?}" - ); + assert!((pair[1] - pair[0] - super::row::INDENT).abs() < 0.5, "{lefts:?}"); } // Twelve letters at 12.5 px, the swatch and the name's insets: « Exploitation ». let two_down = row(&harness, "folder-option", &names[2]).width(); @@ -459,24 +388,16 @@ fn a_name_cut_in_the_rail_is_read_whole_on_hover_and_its_menu_stays_in_reach() { let long = "Runbooks de la production et de la préproduction"; folder(&backend, &home, None, long); let mut harness = area(backend, profile); - harness - .ctx - .all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + harness.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); - harness - .get_by(|node| node.author_id() == Some("folder-option")) - .hover(); + harness.get_by(|node| node.author_id() == Some("folder-option")).hover(); for _ in 0..10 { harness.step(); } let said = harness .query_all_by(|node| node.author_id() != Some("folder-option")) - .filter_map(|node| { - node.accesskit_node() - .label() - .or(node.accesskit_node().value()) - }) + .filter_map(|node| node.accesskit_node().label().or(node.accesskit_node().value())) .any(|words| words == long); assert!(said, "the full name in a tooltip"); harness.get_by(|node| node.author_id() == Some("folder-edit")); @@ -492,13 +413,11 @@ fn said_by(harness: &Harness<'_, Bench>, author_id: &str) -> String { fn trashed(harness: &Harness<'_, Bench>) -> Vec { let backend = &harness.state().backend; - engine::db::run_here(backend.engine(), |engine| { - engine::notes::list_trash(engine, "") - }) - .unwrap() - .into_iter() - .map(|row| row.note.id) - .collect() + engine::db::run_here(backend.engine(), |engine| engine::notes::list_trash(engine, "")) + .unwrap() + .into_iter() + .map(|row| row.note.id) + .collect() } fn latest_report(harness: &Harness<'_, Bench>) -> Option { @@ -512,12 +431,11 @@ fn a_space_deleted_with_its_notes_puts_them_in_the_trash_restored_in_its_refuge( space(&backend, "Home"); let reading = space(&backend, "Reading"); let draft = testing::snippet(reading.id.clone(), "an article".into()); - let article = engine::db::run_here(backend.engine(), move |engine| { - engine::notes::create_note(engine, draft) - }) - .unwrap() - .note - .id; + let article = + engine::db::run_here(backend.engine(), move |engine| engine::notes::create_note(engine, draft)) + .unwrap() + .note + .id; let mut harness = area(backend, profile); click(&mut harness, "space-edit", "Options for space Reading"); @@ -526,20 +444,14 @@ fn a_space_deleted_with_its_notes_puts_them_in_the_trash_restored_in_its_refuge( click_id(&mut harness, "space-delete-held-1"); let trashing = said_by(&harness, "space-delete-consequence"); assert_ne!(kept, trashing, "the choice switches what is said"); - assert!( - trashing.contains("trash") && trashing.contains("“Home”"), - "{trashing}" - ); + assert!(trashing.contains("trash") && trashing.contains("“Home”"), "{trashing}"); click_id(&mut harness, "space-delete"); click_id(&mut harness, "space-delete"); assert_eq!(names(&harness, "space-option"), ["Home"]); assert_eq!(trashed(&harness), [article]); assert_eq!(cards(&harness), 0); - assert_eq!( - latest_report(&harness), - Some(i18n::keys::notes::SPACE_DELETED_TRASHED) - ); + assert_eq!(latest_report(&harness), Some(i18n::keys::notes::SPACE_DELETED_TRASHED)); } #[test] @@ -562,10 +474,7 @@ fn a_folder_deleted_with_its_notes_takes_its_sub_folder_and_trashes_them() { click(&mut harness, "folder-edit", "Options for folder Runbooks"); let kept = said_by(&harness, "folder-delete-note"); - assert!( - kept.contains("2 notes stay") && kept.contains("sub-folder"), - "{kept}" - ); + assert!(kept.contains("2 notes stay") && kept.contains("sub-folder"), "{kept}"); click_id(&mut harness, "folder-delete-held"); click_id(&mut harness, "folder-delete-held-1"); let trashing = said_by(&harness, "folder-delete-note"); @@ -580,8 +489,124 @@ fn a_folder_deleted_with_its_notes_takes_its_sub_folder_and_trashes_them() { expected.sort(); assert_eq!(gone, expected); assert_eq!(cards(&harness), 1, "the loose note stays"); - assert_eq!( - latest_report(&harness), - Some(i18n::keys::folders::DELETED_TRASHED) - ); + assert_eq!(latest_report(&harness), Some(i18n::keys::folders::DELETED_TRASHED)); +} + +fn shows(harness: &Harness<'_, Bench>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn press(harness: &mut Harness<'_, Bench>, key: egui::Key) { + harness.key_press(key); + settle(harness); +} + +/// A space « Work » beside « Home », which holds a folder « Runbooks ». +fn rail() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + let home = space(&backend, "Home"); + space(&backend, "Work"); + folder(&backend, &home, None, "Runbooks"); + area(backend, profile) +} + +const PANELS: [(&str, &str, &str, &str); 2] = [ + ("space-edit", "Options for space Work", "space-rename-input", "space-rename-submit"), + ("folder-edit", "Options for folder Runbooks", "folder-rename-input", "folder-rename-submit"), +]; + +/// Its ⋯ again, or Escape in its field. +#[test] +fn a_panel_closes_as_it_opened_or_on_escape() { + for (edit, name, field, _) in PANELS { + let mut harness = rail(); + click(&mut harness, edit, name); + assert!(shows(&harness, field)); + click(&mut harness, edit, name); + assert!(!shows(&harness, field), "{edit}"); + + click(&mut harness, edit, name); + press(&mut harness, egui::Key::Escape); + assert!(!shows(&harness, field), "{edit}"); + } +} + +fn every_name(harness: &Harness<'_, Bench>) -> Vec { + let mut names: Vec = spaces_of(harness).into_iter().map(|space| space.name).collect(); + let folders = harness.state().state.folders.list(); + names.extend(folders.iter().map(|folder| folder.name.clone())); + names +} + +#[test] +fn a_name_is_written_on_enter_and_by_its_button() { + for (edit, name, field, submit) in PANELS { + for by_button in [false, true] { + let mut harness = rail(); + click(&mut harness, edit, name); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.get_by(|node| node.author_id() == Some(field)).type_text("Renamed"); + settle(&mut harness); + if by_button { + click_id(&mut harness, submit); + } else { + press(&mut harness, egui::Key::Enter); + } + assert!(every_name(&harness).contains(&"Renamed".to_owned()), "{edit}"); + assert!(!shows(&harness, field), "{edit} closed"); + } + } +} + +#[test] +fn escape_drops_the_name_of_what_was_being_made() { + for open in ["space-create-open", "folder-create-open"] { + let mut harness = rail(); + if open == "folder-create-open" { + click(&mut harness, "space-option", "Home"); + } + let before = every_name(&harness); + if !shows(&harness, open) { + continue; + } + click_id(&mut harness, open); + let input = open.replace("open", "input"); + harness + .get_by(|node| node.author_id() == Some(input.as_str())) + .type_text("Dropped"); + settle(&mut harness); + press(&mut harness, egui::Key::Escape); + + assert_eq!(every_name(&harness), before, "{open}"); + assert!(!shows(&harness, &input), "{open}"); + } +} + +/// Nothing to move, it is said rather than counted. +#[test] +fn a_space_with_no_note_says_so_before_it_goes() { + let mut harness = rail(); + click(&mut harness, "space-edit", "Options for space Work"); + crate::notes::bench::until(&mut harness, "it is counted", |harness| { + shows(harness, "space-delete-consequence") + }); + let said = said_by(&harness, "space-delete-consequence"); + let none = i18n::translate(i18n::Language::En, i18n::keys::notes::DELETE_SPACE_NO_NOTES, &[]); + + assert!(said.starts_with(&none), "{said}"); +} + +#[test] +fn the_rail_s_width_is_kept_once_its_edge_rests() { + let mut harness = rail(); + harness.get_by(|node| node.author_id() == Some("library-rail-edge")).focus(); + settle(&mut harness); + let before = harness.state().state.settings.rail_width; + press(&mut harness, egui::Key::ArrowRight); + press(&mut harness, egui::Key::ArrowRight); + + assert!(harness.state().state.settings.rail_width > before); } diff --git a/crates/ui/src/notes/sidebar/tree.rs b/crates/ui/src/notes/sidebar/tree.rs index 0315e75f2..5f6b7fbe1 100644 --- a/crates/ui/src/notes/sidebar/tree.rs +++ b/crates/ui/src/notes/sidebar/tree.rs @@ -50,16 +50,9 @@ pub(in crate::notes) fn rows<'a>( .filter(|folder| folder.space_id == space.id) .map(|folder| (folder.id.as_str(), folder)) .collect(); - let lineage = Lineage::new( - inside - .values() - .map(|folder| (folder.id.clone(), folder.parent_id.clone())), - ); - let level = Level { - inside: &inside, - lineage: &lineage, - collapsed, - }; + let lineage = + Lineage::new(inside.values().map(|folder| (folder.id.clone(), folder.parent_id.clone()))); + let level = Level { inside: &inside, lineage: &lineage, collapsed }; level.push(&mut rows, None, 0); if active_space == Some(space.id.as_str()) { rows.push(Row::NewFolder { space }); @@ -89,12 +82,7 @@ impl<'a> Level<'a, '_> { for folder in children { let nested = !self.lineage.children(Some(&folder.id)).is_empty(); let open = !self.collapsed.contains(&folder.id); - rows.push(Row::Folder { - folder, - depth, - nested, - open, - }); + rows.push(Row::Folder { folder, depth, nested, open }); if nested && open { self.push(rows, Some(&folder.id), depth + 1); } @@ -110,11 +98,7 @@ mod tests { use super::*; fn space(id: &str) -> Space { - Space { - id: id.into(), - name: id.into(), - pinned: false, - } + Space { id: id.into(), name: id.into(), pinned: false } } fn folder(id: &str, space: &str, parent: Option<&str>) -> Folder { @@ -157,39 +141,20 @@ mod tests { assert_eq!( shape(&rows), - [ - "all", - "home", - " Archive", - " élan", - " runbooks", - " api", - "work", - " none" - ] + ["all", "home", " Archive", " élan", " runbooks", " api", "work", " none"] ); } #[test] fn a_closed_row_hides_what_it_holds() { let spaces = [space("home"), space("work")]; - let folders = [ - folder("runbooks", "home", None), - folder("api", "home", Some("runbooks")), - ]; + let folders = [folder("runbooks", "home", None), folder("api", "home", Some("runbooks"))]; let closed = HashSet::from(["runbooks".to_string(), "work".to_string()]); let rows = rows(&spaces, &folders, None, &closed); assert_eq!(shape(&rows), ["all", "home", " runbooks", "work"]); - assert!(matches!( - rows[2], - Row::Folder { - nested: true, - open: false, - .. - } - )); + assert!(matches!(rows[2], Row::Folder { nested: true, open: false, .. })); } #[test] diff --git a/crates/ui/src/notes/ui.rs b/crates/ui/src/notes/ui.rs index 5507d789e..ff81a297c 100644 --- a/crates/ui/src/notes/ui.rs +++ b/crates/ui/src/notes/ui.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, - Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, + WidgetInfo, }; use engine::folders::model::FolderColour; use engine::notes::kind::NoteKind; @@ -56,8 +56,7 @@ fn kind_glyph(kind: NoteKind) -> Icon { pub fn kind_tile(ui: &Ui, rect: Rect, kind: NoteKind) { let hue = kind_hue(ui, kind); let corner = CornerRadius::same(rect_corner(rect)); - ui.painter() - .rect_filled(rect, corner, hue.gamma_multiply(0.18)); + ui.painter().rect_filled(rect, corner, hue.gamma_multiply(0.18)); let glyph = Rect::from_center_size(rect.center(), Vec2::splat(rect.width() * 2.0 / 3.0)); icons::paint(ui, glyph, kind_glyph(kind), hue); } @@ -96,15 +95,9 @@ pub fn format_label( } let p = palette(ui.ctx()); let (words, hue) = if language == Language::Txt { - ( - i18n::translate(locale, keys::notes::kind_tag::PLAIN, &[]), - p.text_1, - ) + (i18n::translate(locale, keys::notes::kind_tag::PLAIN, &[]), p.text_1) } else { - ( - languages::label(language).to_string(), - language_hue(ui, language), - ) + (languages::label(language).to_string(), language_hue(ui, language)) }; let galley = widgets::text(ui, &words, font::CAPTION, 600.0, FontFamily::Monospace, hue); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); @@ -116,12 +109,7 @@ pub fn format_label( } /// How a row names a note's kind: the icon, and a snippet's format after it. -pub fn kind_mark( - ui: &mut Ui, - kind: NoteKind, - language: Language, - locale: i18n::Language, -) -> Response { +pub fn kind_mark(ui: &mut Ui, kind: NoteKind, language: Language, locale: i18n::Language) -> Response { let icon = kind_icon(ui, kind, locale); match format_label(ui, kind, language, locale) { Some(format) => icon.union(format), @@ -147,26 +135,15 @@ pub fn language_hue(ui: &Ui, language: Language) -> Color32 { pub fn priority_bars(ui: &mut Ui, priority: Priority, locale: i18n::Language) -> Option { let (ink, _, key) = bars_of(ui, priority)?; let name = i18n::translate(locale, key, &[]); - let word = (priority == Priority::Urgent).then(|| { - widgets::text( - ui, - &name, - font::CAPTION, - 700.0, - FontFamily::Proportional, - ink, - ) - }); + let word = (priority == Priority::Urgent) + .then(|| widgets::text(ui, &name, font::CAPTION, 700.0, FontFamily::Proportional, ink)); let width = BARS_WIDTH + word.as_ref().map_or(0.0, |word| 4.0 + word.size().x); let (rect, response) = ui.allocate_exact_size(Vec2::new(width, 12.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &name)); address(ui, &response, "priority-bars"); paint_bars(ui, (rect.left(), rect.center().y + 5.0), priority); if let Some(word) = word { - let at = Pos2::new( - rect.left() + BARS_WIDTH + 4.0, - rect.center().y - word.size().y / 2.0, - ); + let at = Pos2::new(rect.left() + BARS_WIDTH + 4.0, rect.center().y - word.size().y / 2.0); ui.painter().galley(at, word, ink); } Some(widgets::tooltip(response, &name)) @@ -194,19 +171,11 @@ pub fn paint_bars(ui: &Ui, (left, bottom): (f32, f32), priority: Priority) { return; }; for (bar, height) in [4.0, 7.0, 10.0].into_iter().enumerate() { - let colour = if bar < lit { - ink - } else { - ink.gamma_multiply(0.28) - }; + let colour = if bar < lit { ink } else { ink.gamma_multiply(0.28) }; #[expect(clippy::cast_precision_loss, reason = "three bars")] let left = left + bar as f32 * 3.0; - let shape = Rect::from_min_max( - Pos2::new(left, bottom - height), - Pos2::new(left + 2.0, bottom), - ); - ui.painter() - .rect_filled(shape, CornerRadius::same(radius::MARK), colour); + let shape = Rect::from_min_max(Pos2::new(left, bottom - height), Pos2::new(left + 2.0, bottom)); + ui.painter().rect_filled(shape, CornerRadius::same(radius::MARK), colour); } } diff --git a/crates/ui/src/palette/list_tests.rs b/crates/ui/src/palette/list_tests.rs new file mode 100644 index 000000000..97df8b713 --- /dev/null +++ b/crates/ui/src/palette/list_tests.rs @@ -0,0 +1,229 @@ +//! What the palette lists, narrows to and runs. + +use egui::{Key, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use engine::http::model::{HttpMethod, RequestKind}; +use engine::notes::kind::NoteKind; + +use super::commands::{COMMANDS, Command}; +use crate::notes::bench::{Bench, area, settle, space, until}; +use crate::services::shortcuts::Bindings; +use crate::state::Area; +use crate::testing; + +/// A library of two spaces, a note tagged `db` and a request. +fn palette() -> Harness<'static, Bench> { + let (backend, profile) = testing::unlocked(); + let home = space(&backend, "Home"); + space(&backend, "Work"); + let mut draft = testing::snippet(home.id, "psql prod".to_owned()); + draft.tags = vec!["db".to_owned()]; + engine::db::run_here(backend.engine(), move |engine| engine::notes::create_note(engine, draft)).unwrap(); + let api = crate::http::tests::collection(&backend, "API"); + let socket = (RequestKind::Websocket, HttpMethod::Get); + crate::http::tests::request(&backend, (&api, None), "Events", socket); + let mut harness = area(backend, profile); + harness.key_press_modifiers(Modifiers::COMMAND | Modifiers::ALT, Key::P); + settle(&mut harness); + harness +} + +fn options(harness: &Harness<'_, Bench>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("palette-option")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() +} + +fn typed(harness: &mut Harness<'_, Bench>, words: &str) { + harness + .get_by(|node| node.author_id() == Some("palette-input")) + .type_text(words); + for _ in 0..20 { + harness.step(); + } + settle(harness); +} + +fn press(harness: &mut Harness<'_, Bench>, key: Key) { + harness.key_press(key); + settle(harness); +} + +fn lists(harness: &mut Harness<'_, Bench>, what: &str, holds: impl Fn(&[String]) -> bool) { + until(harness, what, |harness| holds(&options(harness))); +} + +fn chips(harness: &Harness<'_, Bench>) -> usize { + harness.state().state.palette.chips().len() +} + +// What it offers + +#[test] +fn a_space_is_found_by_its_name_and_shown() { + let mut harness = palette(); + typed(&mut harness, "Work"); + lists(&mut harness, "the space is found", |names| names.iter().any(|name| name == "Work")); + let at = options(&harness).iter().position(|name| name == "Work").unwrap(); + for _ in 0..at { + press(&mut harness, Key::ArrowDown); + } + press(&mut harness, Key::Enter); + + let state = &harness.state().state; + let shown = state.spaces.active_space().unwrap(); + assert_eq!(state.spaces.spaces().iter().find(|space| space.id == shown).unwrap().name, "Work"); +} + +#[test] +fn what_is_found_nowhere_is_offered_as_a_note() { + let mut harness = palette(); + typed(&mut harness, "pg_dump nightly"); + until(&mut harness, "the creation is offered", |harness| { + harness.query_by(|node| node.author_id() == Some("palette-create")).is_some() + }); + press(&mut harness, Key::Enter); + + let opened = harness.state().state.editor.opened().unwrap(); + assert_eq!(opened.note().unwrap().title, "pg_dump nightly"); +} + +#[test] +fn what_matches_no_chip_and_no_command_says_so() { + for words in ["@zzzz", "#zzzz", "> zzzz"] { + let mut harness = palette(); + typed(&mut harness, words); + lists(&mut harness, words, <[String]>::is_empty); + assert!(harness.query_by(|node| node.author_id() == Some("palette-empty")).is_some(), "{words}"); + } +} + +// The chips + +#[test] +fn a_tag_narrows_to_the_notes_that_carry_it() { + let mut harness = palette(); + typed(&mut harness, "#d"); + lists(&mut harness, "the tag is offered", |names| names.len() == 1); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 1); + + lists(&mut harness, "its note alone", |names| names == ["psql prod"]); +} + +#[test] +fn a_space_narrows_to_its_notes() { + let mut harness = palette(); + typed(&mut harness, "@Work"); + lists(&mut harness, "the space is offered", |names| names.len() == 1); + press(&mut harness, Key::Enter); + + assert_eq!(chips(&harness), 1); + lists(&mut harness, "no note there", |names| !names.iter().any(|name| name == "psql prod")); +} + +#[test] +fn each_scope_lists_its_own() { + for (scope, holds) in [("@notes", "psql prod"), ("@requests", "Events"), ("@spaces", "Work")] { + let mut harness = palette(); + typed(&mut harness, scope); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 1, "{scope}"); + lists(&mut harness, scope, |names| names.iter().any(|name| name == holds)); + } +} + +#[test] +fn a_chip_is_taken_off_by_the_key_before_it_or_by_its_cross() { + let mut harness = palette(); + typed(&mut harness, "@notes"); + press(&mut harness, Key::Tab); + typed(&mut harness, "#db"); + press(&mut harness, Key::Tab); + assert_eq!(chips(&harness), 2); + + press(&mut harness, Key::Backspace); + assert_eq!(chips(&harness), 1); + harness.get_by(|node| node.author_id() == Some("palette-chip-remove")).click(); + settle(&mut harness); + assert_eq!(chips(&harness), 0); +} + +// The keys + +#[test] +fn the_arrows_and_tab_walk_the_options_and_stay_on_them() { + let mut harness = palette(); + lists(&mut harness, "they are listed", |names| names.len() >= 2); + let last = options(&harness).len(); + let on = |harness: &Harness<'_, Bench>| harness.state().state.palette_view.highlighted; + assert_eq!(on(&harness), 0); + press(&mut harness, Key::ArrowUp); + assert_eq!(on(&harness), 0); + press(&mut harness, Key::Tab); + assert_eq!(on(&harness), 1); + harness.key_press_modifiers(Modifiers::SHIFT, Key::Tab); + settle(&mut harness); + assert_eq!(on(&harness), 0); + for _ in 0..last + 3 { + press(&mut harness, Key::ArrowDown); + } + assert_eq!(on(&harness), last - 1); +} + +#[test] +fn ctrl_c_copies_the_note_in_hand_and_closes() { + let mut harness = palette(); + typed(&mut harness, "psql prod"); + lists(&mut harness, "the note is found", |names| names.first().is_some_and(|name| name == "psql prod")); + harness.key_press_modifiers(Modifiers::COMMAND, Key::C); + settle(&mut harness); + until(&mut harness, "it is copied", |harness| harness.state().state.status.latest().is_some()); + + assert!(!harness.state().state.palette.is_open()); +} + +#[test] +fn escape_closes_it() { + let mut harness = palette(); + press(&mut harness, Key::Escape); + + assert!(!harness.state().state.palette.is_open()); +} + +// The commands + +#[test] +fn every_command_is_listed_by_its_prefix_and_found_by_its_words() { + let mut harness = palette(); + typed(&mut harness, ">"); + lists(&mut harness, "all of them", |names| names.len() >= COMMANDS.len() - 1); + + let mut harness = palette(); + typed(&mut harness, "> http"); + lists(&mut harness, "the area", |names| names.len() == 1); + press(&mut harness, Key::Enter); + assert_eq!(harness.state().state.settings.area, Area::Http); +} + +#[test] +fn each_command_has_its_own_name_and_the_key_it_answers_to() { + let bindings = Bindings::default(); + let mut ids: Vec = COMMANDS.iter().map(|command| command.id()).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), COMMANDS.len()); + for (command, keys) in [ + (Command::Create(NoteKind::Snippet), vec!["Ctrl", "N"]), + (Command::Create(NoteKind::Note), vec!["Ctrl", "Shift", "N"]), + (Command::Area(Area::Notes), vec!["Ctrl", "1"]), + (Command::Area(Area::Tools), vec!["Ctrl", "2"]), + (Command::Area(Area::Http), vec!["Ctrl", "3"]), + (Command::Request, vec![]), + (Command::Preferences, vec![]), + ] { + assert_eq!(command.keys(&bindings), keys, "{command:?}"); + } +} diff --git a/crates/ui/src/palette/mod.rs b/crates/ui/src/palette/mod.rs index 97a2581b7..5c87f6db3 100644 --- a/crates/ui/src/palette/mod.rs +++ b/crates/ui/src/palette/mod.rs @@ -3,13 +3,15 @@ //! one current row, and Enter or a click opens it, as everywhere else in the application. pub mod commands; +#[cfg(test)] +mod list_tests; pub mod options; use crate::theme::tokens::{font, gap, radius}; use egui::text::{LayoutJob, TextFormat}; use egui::{ - Align2, Color32, CornerRadius, FontFamily, FontId, Id, Key, Margin, Modifiers, Rect, Role, - Sense, Stroke, Ui, UiBuilder, WidgetInfo, pos2, vec2, + Align2, Color32, CornerRadius, FontFamily, FontId, Id, Key, Margin, Modifiers, Rect, Role, Sense, Stroke, + Ui, UiBuilder, WidgetInfo, pos2, vec2, }; use engine::http::model::RequestKind; use engine::notes::kind::NoteKind; @@ -93,8 +95,7 @@ pub fn show(ctx: &egui::Context, state: &AppState, view: &mut PaletteView, actio .inner_margin(gap::margin(gap::GROUPS, gap::GROUPS)); // Near the top rather than centred: the list grows downwards, and a centred panel would // slide under the pointer as it fills. - let area = - egui::Modal::default_area(Id::unique("palette")).anchor(Align2::CENTER_TOP, vec2(0.0, top)); + let area = egui::Modal::default_area(Id::unique("palette")).anchor(Align2::CENTER_TOP, vec2(0.0, top)); let shown = egui::Modal::new(Id::unique("palette")) .area(area) .backdrop_color(p.backdrop.gamma_multiply(0.7)) @@ -181,9 +182,7 @@ fn panel( if let Some(empty) = options::empty(state, groups) { let words = empty.text(language); let said = ui.add(egui::Label::new( - egui::RichText::new(&words) - .size(font::BODY) - .color(palette(ui.ctx()).text_2), + egui::RichText::new(&words).size(font::BODY).color(palette(ui.ctx()).text_2), )); widgets::address(ui, &said, "palette-empty"); } @@ -250,8 +249,7 @@ fn field(ui: &mut Ui, state: &AppState, actions: &mut Actions) { .min_size(vec2(140.0, 32.0)), ); let label = tr(keys::palette::SEARCH_LABEL); - ui.ctx() - .accesskit_node_builder(typed.id, |node| node.set_label(label.clone())); + ui.ctx().accesskit_node_builder(typed.id, |node| node.set_label(label.clone())); widgets::address(ui, &typed, "palette-input"); if !state.fill.is_open() && !typed.has_focus() { typed.request_focus(); @@ -289,40 +287,20 @@ fn chip_shown(ui: &mut Ui, chip: &Chip, language: i18n::Language) -> bool { Chip::Tag(_) => p.pink, }; let label = chip_label(chip, language); - let words = widgets::text( - ui, - &label, - font::LABEL, - 600.0, - FontFamily::Proportional, - hue, - ); + let words = widgets::text(ui, &label, font::LABEL, 600.0, FontFamily::Proportional, hue); let shown = egui::Frame::new() .fill(p.bg_3) .corner_radius(CornerRadius::same(radius::CONTROL)) - .inner_margin(Margin { - left: 8, - right: 2, - top: 0, - bottom: 0, - }) + .inner_margin(Margin { left: 8, right: 2, top: 0, bottom: 0 }) .show(ui, |ui| { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::LINE; let (rect, _) = ui.allocate_exact_size(vec2(words.size().x, 24.0), Sense::hover()); - ui.painter().galley( - pos2(rect.left(), rect.center().y - words.size().y / 2.0), - words, - hue, - ); - let remove = i18n::translate( - language, - keys::palette::REMOVE_CHIP, - &[("chip", label.as_str().into())], - ); - IconButton::new(Icon::X, &remove, "palette-chip-remove") - .show(ui) - .clicked() + ui.painter() + .galley(pos2(rect.left(), rect.center().y - words.size().y / 2.0), words, hue); + let remove = + i18n::translate(language, keys::palette::REMOVE_CHIP, &[("chip", label.as_str().into())]); + IconButton::new(Icon::X, &remove, "palette-chip-remove").show(ui).clicked() }) .inner }); @@ -337,27 +315,14 @@ fn heading_row(ui: &mut Ui, heading: i18n::Key, count: Option, language: ui.horizontal(|ui| { ui.add_space(gap::INSET); ui.spacing_mut().item_spacing.x = gap::CONTROLS; - let galley = widgets::text( - ui, - &words, - font::CAPTION, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &words, font::CAPTION, 600.0, FontFamily::Proportional, p.text_2); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); widgets::address(ui, &response, "palette-group"); ui.painter().galley(rect.min, galley, p.text_2); if let Some(count) = count { - let counted = widgets::text( - ui, - &count.to_string(), - font::CAPTION, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let counted = + widgets::text(ui, &count.to_string(), font::CAPTION, 400.0, FontFamily::Monospace, p.text_2); let (rect, _) = ui.allocate_exact_size(counted.size(), Sense::hover()); ui.painter().galley(rect.min, counted, p.text_2); } @@ -368,17 +333,10 @@ fn heading_row(ui: &mut Ui, heading: i18n::Key, count: Option, language: fn row(ui: &mut Ui, state: &AppState, item: &Item, on: bool) -> (bool, bool, bool) { let p = palette(ui.ctx()); let language = state.language; - let compact = !matches!( - item, - Item::Note(_) | Item::Request(_) | Item::Tool(_) | Item::Space { .. } - ); + let compact = !matches!(item, Item::Note(_) | Item::Request(_) | Item::Tool(_) | Item::Space { .. }); let height = if compact { 34.0 } else { 44.0 }; let title = title_of(item, language); - let author_id = if matches!(item, Item::Create(_)) { - "palette-create" - } else { - "palette-option" - }; + let author_id = if matches!(item, Item::Create(_)) { "palette-create" } else { "palette-option" }; let width = ui.available_width(); let corner = CornerRadius::same(radius::MENU); let response = widgets::interact( @@ -395,10 +353,8 @@ fn row(ui: &mut Ui, state: &AppState, item: &Item, on: bool) -> (bool, bool, boo } let copyable = matches!(item, Item::Note(note) if note.kind != NoteKind::Drawing); let copy_room = if copyable { 34.0 } else { 0.0 }; - let inner = Rect::from_min_max( - rect.min + vec2(10.0, 0.0), - pos2(rect.right() - 10.0 - copy_room, rect.bottom()), - ); + let inner = + Rect::from_min_max(rect.min + vec2(10.0, 0.0), pos2(rect.right() - 10.0 - copy_room, rect.bottom())); let main_left = mark(ui, item, inner, language); let side_width = side(ui, state, item, inner, on); let main = Rect::from_min_max( @@ -409,21 +365,12 @@ fn row(ui: &mut Ui, state: &AppState, item: &Item, on: bool) -> (bool, bool, boo let mut copied = false; if copyable { let place = Rect::from_min_size( - pos2( - rect.right() - 6.0 - widgets::MIN_TARGET - 4.0, - rect.center().y - 14.0, - ), + pos2(rect.right() - 6.0 - widgets::MIN_TARGET - 4.0, rect.center().y - 14.0), vec2(widgets::MIN_TARGET + 4.0, 28.0), ); let mut child = ui.new_child(UiBuilder::new().max_rect(place)); - let label = i18n::translate( - language, - keys::palette::COPY_LABEL, - &[("title", title.as_str().into())], - ); - copied = IconButton::new(Icon::Copy, &label, "palette-copy") - .show(&mut child) - .clicked(); + let label = i18n::translate(language, keys::palette::COPY_LABEL, &[("title", title.as_str().into())]); + copied = IconButton::new(Icon::Copy, &label, "palette-copy").show(&mut child).clicked(); } (response.clicked() && !copied, response.hovered(), copied) } @@ -443,26 +390,20 @@ fn title_of(item: &Item, language: i18n::Language) -> String { Chip::Space { name, .. } => name.clone(), Chip::Tag(tag) => tag.clone(), }, - Item::Create(query) => i18n::translate( - language, - keys::palette::CREATE_NOTE, - &[("query", query.as_str().into())], - ), + Item::Create(query) => { + i18n::translate(language, keys::palette::CREATE_NOTE, &[("query", query.as_str().into())]) + } } } /// The kind's badge or a tile; answers where the words begin. fn mark(ui: &mut Ui, item: &Item, inner: Rect, language: i18n::Language) -> f32 { let p = palette(ui.ctx()); - let tile = Rect::from_min_size( - pos2(inner.left(), inner.center().y - 13.0), - vec2(26.0, 26.0), - ); + let tile = Rect::from_min_size(pos2(inner.left(), inner.center().y - 13.0), vec2(26.0, 26.0)); let corner = CornerRadius::same(radius::CONTROL); match item { Item::Note(note) => { - let place = - Rect::from_min_size(pos2(inner.left(), inner.center().y - 9.0), vec2(90.0, 18.0)); + let place = Rect::from_min_size(pos2(inner.left(), inner.center().y - 9.0), vec2(90.0, 18.0)); let row = egui::Layout::left_to_right(egui::Align::Center); let mut child = ui.new_child(UiBuilder::new().max_rect(place).layout(row)); child.spacing_mut().item_spacing.x = gap::SNUG; @@ -476,14 +417,7 @@ fn mark(ui: &mut Ui, item: &Item, inner: Rect, language: i18n::Language) -> f32 RequestKind::Websocket => Badge::Websocket, }; let hue = crate::http::badge_hue(ui, badge); - let word = widgets::text( - ui, - badge.short(), - font::META, - 700.0, - FontFamily::Monospace, - hue, - ); + let word = widgets::text(ui, badge.short(), font::META, 700.0, FontFamily::Monospace, hue); let at = pos2(inner.left(), inner.center().y - word.size().y / 2.0); let right = at.x + word.size().x; ui.painter().galley(at, word, hue); @@ -492,8 +426,7 @@ fn mark(ui: &mut Ui, item: &Item, inner: Rect, language: i18n::Language) -> f32 Item::Tool(id) => { if let Some(tool) = catalogue::find(id) { let hue = tool.category.hue(p); - ui.painter() - .rect_filled(tile, corner, hue.gamma_multiply(0.15)); + ui.painter().rect_filled(tile, corner, hue.gamma_multiply(0.15)); let glyph = Rect::from_center_size(tile.center(), vec2(14.0, 14.0)); crate::theme::icons::paint(ui, glyph, tool.category.icon(), hue); } @@ -505,27 +438,20 @@ fn mark(ui: &mut Ui, item: &Item, inner: Rect, language: i18n::Language) -> f32 crate::notes::ui::kind_tile(ui, tile, *kind); tile.right() + 10.0 } - Item::Space { .. } - | Item::Chip { - chip: Chip::Space { .. }, - .. - } => { + Item::Space { .. } | Item::Chip { chip: Chip::Space { .. }, .. } => { ui.painter().rect_filled(tile, corner, p.bg_3); ui.painter().circle_filled(tile.center(), 4.0, p.amber_fill); tile.right() + 10.0 } Item::Command(_) | Item::Chip { .. } => { let (glyph, hue) = match item { - Item::Chip { - chip: Chip::Tag(_), .. - } => ("#", p.pink), + Item::Chip { chip: Chip::Tag(_), .. } => ("#", p.pink), Item::Chip { .. } => ("@", p.teal), _ => (">", p.text_1), }; ui.painter().rect_filled(tile, corner, p.bg_3); let galley = widgets::text(ui, glyph, font::READING, 600.0, FontFamily::Monospace, hue); - ui.painter() - .galley(tile.center() - galley.size() / 2.0, galley, hue); + ui.painter().galley(tile.center() - galley.size() / 2.0, galley, hue); tile.right() + 10.0 } } @@ -536,25 +462,16 @@ fn main_text(ui: &Ui, state: &AppState, item: &Item, title: &str, rect: Rect) { let p = palette(ui.ctx()); let painter = ui.painter().with_clip_rect(rect.intersect(ui.clip_rect())); // The offer to create says what was typed; it is no match. - let term = if matches!(item, Item::Create(_)) { - String::new() - } else { - term_of(state) - }; + let term = if matches!(item, Item::Create(_)) { String::new() } else { term_of(state) }; let mut job = lit(title, &term, rect.width(), p.amber_text); if let Item::Note(note) = item && !note.placeholders.is_empty() { let count = u32::try_from(note.placeholders.len()).unwrap_or(u32::MAX); - let fields = i18n::translate( - state.language, - keys::notes::PLACEHOLDERS_COUNT, - &[("count", count.into())], - ); - let mut format = TextFormat::simple( - FontId::new(font::CAPTION, FontFamily::Proportional), - p.amber_text, - ); + let fields = + i18n::translate(state.language, keys::notes::PLACEHOLDERS_COUNT, &[("count", count.into())]); + let mut format = + TextFormat::simple(FontId::new(font::CAPTION, FontFamily::Proportional), p.amber_text); format.coords.push(*b"wght", 500.0); job.append(&fields, 8.0, format); } @@ -562,38 +479,18 @@ fn main_text(ui: &Ui, state: &AppState, item: &Item, title: &str, rect: Rect) { let sub = match item { Item::Note(note) => first_line(note), Item::Request(request) => request.url.clone(), - Item::Tool(id) => { - catalogue::find(id).map_or_else(String::new, |tool| tool.line(state.language)) - } + Item::Tool(id) => catalogue::find(id).map_or_else(String::new, |tool| tool.line(state.language)), Item::Chip { chip, count } => chip_line(chip, *count, state.language), _ => String::new(), }; - let ink = if matches!( - item, - Item::Chip { - chip: Chip::Scope(_), - .. - } - ) { - p.teal - } else { - p.text_0 - }; + let ink = if matches!(item, Item::Chip { chip: Chip::Scope(_), .. }) { p.teal } else { p.text_0 }; if sub.is_empty() { - painter.galley( - pos2(rect.left(), rect.center().y - galley.size().y / 2.0), - galley, - ink, - ); + painter.galley(pos2(rect.left(), rect.center().y - galley.size().y / 2.0), galley, ink); return; } let mono = matches!(item, Item::Request(_)) || matches!(item, Item::Note(note) if note.kind == NoteKind::Snippet); - let (size, family) = if mono { - (11.0, FontFamily::Monospace) - } else { - (11.5, FontFamily::Proportional) - }; + let (size, family) = if mono { (11.0, FontFamily::Monospace) } else { (11.5, FontFamily::Proportional) }; let mut line = LayoutJob::simple_singleline(sub, FontId::new(size, family), p.text_2); line.wrap.max_width = rect.width(); line.wrap.max_rows = 1; @@ -614,9 +511,8 @@ fn term_of(state: &AppState) -> String { /// What was typed, lit in the title, when folding keeps the title's length. fn lit(title: &str, term: &str, width: f32, hit: Color32) -> LayoutJob { - let format = |colour: Color32| { - TextFormat::simple(FontId::new(font::READING, FontFamily::Proportional), colour) - }; + let format = + |colour: Color32| TextFormat::simple(FontId::new(font::READING, FontFamily::Proportional), colour); let mut job = LayoutJob::default(); job.wrap.max_width = width; job.wrap.max_rows = 1; @@ -634,11 +530,8 @@ fn lit(title: &str, term: &str, width: f32, hit: Color32) -> LayoutJob { let start = folded[..at].chars().count(); let length = term.chars().count(); let chars: Vec = title.chars().collect(); - let part = |from: usize, to: usize| { - chars[from.min(chars.len())..to.min(chars.len())] - .iter() - .collect::() - }; + let part = + |from: usize, to: usize| chars[from.min(chars.len())..to.min(chars.len())].iter().collect::(); job.append(&part(0, start), 0.0, format(normal)); job.append(&part(start, start + length), 0.0, format(hit)); job.append(&part(start + length, chars.len()), 0.0, format(normal)); @@ -648,11 +541,7 @@ fn lit(title: &str, term: &str, width: f32, hit: Color32) -> LayoutJob { /// The first line that says something: a list's first item, a note's first line. fn first_line(note: &engine::notes::model::DisplayNote) -> String { if note.kind == NoteKind::Checklist { - return note - .items - .first() - .map(|item| item.text.clone()) - .unwrap_or_default(); + return note.items.first().map(|item| item.text.clone()).unwrap_or_default(); } note.content .lines() @@ -664,24 +553,14 @@ fn first_line(note: &engine::notes::model::DisplayNote) -> String { fn chip_line(chip: &Chip, count: Option, language: i18n::Language) -> String { match chip { - Chip::Scope(Scope::Notes) => { - i18n::translate(language, keys::palette::scope_lines::NOTES, &[]) - } - Chip::Scope(Scope::Requests) => { - i18n::translate(language, keys::palette::scope_lines::REQUESTS, &[]) - } - Chip::Scope(Scope::Tools) => { - i18n::translate(language, keys::palette::scope_lines::TOOLS, &[]) - } - Chip::Scope(Scope::Spaces) => { - i18n::translate(language, keys::palette::scope_lines::SPACES, &[]) - } + Chip::Scope(Scope::Notes) => i18n::translate(language, keys::palette::scope_lines::NOTES, &[]), + Chip::Scope(Scope::Requests) => i18n::translate(language, keys::palette::scope_lines::REQUESTS, &[]), + Chip::Scope(Scope::Tools) => i18n::translate(language, keys::palette::scope_lines::TOOLS, &[]), + Chip::Scope(Scope::Spaces) => i18n::translate(language, keys::palette::scope_lines::SPACES, &[]), Chip::Space { .. } => i18n::translate(language, keys::palette::scope_lines::SPACE, &[]), - Chip::Tag(_) => i18n::translate( - language, - keys::palette::TAG_COUNT, - &[("count", count.unwrap_or(0).into())], - ), + Chip::Tag(_) => { + i18n::translate(language, keys::palette::TAG_COUNT, &[("count", count.unwrap_or(0).into())]) + } } } @@ -695,10 +574,8 @@ fn side(ui: &mut Ui, state: &AppState, item: &Item, inner: Rect, on: bool) -> f3 return 0.0; } let width: f32 = caps.iter().map(|word| cap_width(ui, word) + 3.0).sum(); - let place = Rect::from_min_size( - pos2(inner.right() - width, inner.center().y - 9.0), - vec2(width, 18.0), - ); + let place = + Rect::from_min_size(pos2(inner.right() - width, inner.center().y - 9.0), vec2(width, 18.0)); let mut child = ui.new_child( UiBuilder::new() .max_rect(place) @@ -731,18 +608,12 @@ fn side(ui: &mut Ui, state: &AppState, item: &Item, inner: Rect, on: bool) -> f3 .find(|space| space.id == note.space_id) .map(|space| space.name.clone()) .unwrap_or_default(); - let tags: Vec = note - .tags - .iter() - .take(2) - .map(|tag| format!("#{tag}")) - .collect(); + let tags: Vec = note.tags.iter().take(2).map(|tag| format!("#{tag}")).collect(); [vec![space], tags].concat().join(" ") } Item::Request(request) => request.place.join(" › "), - Item::Tool(id) => catalogue::find(id).map_or_else(String::new, |tool| { - i18n::translate(language, tool.category.name(), &[]) - }), + Item::Tool(id) => catalogue::find(id) + .map_or_else(String::new, |tool| i18n::translate(language, tool.category.name(), &[])), _ => String::new(), } }; @@ -772,13 +643,7 @@ fn cap(ui: &mut Ui, word: &str) { Stroke::new(1.0, p.line), egui::StrokeKind::Inside, ); - widgets::arrowed( - ui, - Some(pos2(rect.left() + 6.0, rect.center().y)), - word, - font::CAPTION, - p.text_1, - ); + widgets::arrowed(ui, Some(pos2(rect.left() + 6.0, rect.center().y)), word, font::CAPTION, p.text_1); } /// What `@`, `#` and `>` do, under the empty field's recent notes. @@ -803,10 +668,7 @@ fn prefixes(ui: &mut Ui, language: i18n::Language) { job.append( &format!(" {}", i18n::translate(language, key, &[])), 0.0, - TextFormat::simple( - FontId::new(font::CONTROL, FontFamily::Proportional), - p.text_2, - ), + TextFormat::simple(FontId::new(font::CONTROL, FontFamily::Proportional), p.text_2), ); ui.label(job); } @@ -838,8 +700,7 @@ fn hints(ui: &mut Ui, state: &AppState, current: Option<&Item>) { } hints.push((&["Esc"], keys::palette::keys::CLOSE)); let top = ui.cursor().top(); - ui.painter() - .hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); + ui.painter().hline(ui.max_rect().x_range(), top, Stroke::new(1.0, p.line_soft)); ui.add_space(gap::TIGHT); let response = ui .horizontal_wrapped(|ui| { @@ -850,16 +711,8 @@ fn hints(ui: &mut Ui, state: &AppState, current: Option<&Item>) { cap(ui, word); } let words = i18n::translate(language, key, &[]); - let galley = widgets::text( - ui, - &words, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, _) = - ui.allocate_exact_size(galley.size() + vec2(10.0, 0.0), Sense::hover()); + let galley = widgets::text(ui, &words, font::META, 400.0, FontFamily::Proportional, p.text_2); + let (rect, _) = ui.allocate_exact_size(galley.size() + vec2(10.0, 0.0), Sense::hover()); ui.painter().galley(rect.min, galley, p.text_2); } }) @@ -887,10 +740,7 @@ mod tests { let (backend, profile) = testing::unlocked(); let reset = testing::note(&backend, "Reset the dev database").id.clone(); testing::note(&backend, "Unrelated note"); - let patch = NotePatch { - tags: Some(vec!["ops".into()]), - ..NotePatch::default() - }; + let patch = NotePatch { tags: Some(vec!["ops".into()]), ..NotePatch::default() }; engine::db::run_here(backend.engine(), move |engine| { engine::notes::update_note(engine, &reset, &patch) }) @@ -922,9 +772,7 @@ mod tests { fn it_narrows_to_what_is_typed_and_enter_opens_the_note() { let mut harness = opened(); type_in(&mut harness, "reset"); - until(&mut harness, "one note found", |harness| { - options(harness) == ["Reset the dev database"] - }); + until(&mut harness, "one note found", |harness| options(harness) == ["Reset the dev database"]); press(&mut harness, Modifiers::NONE, Key::Enter); @@ -945,16 +793,10 @@ mod tests { let mut harness = opened(); type_in(&mut harness, "nothing matches this"); until(&mut harness, "the offer to create", |harness| { - harness - .query_by(|node| node.author_id() == Some("palette-create")) - .is_some() + harness.query_by(|node| node.author_id() == Some("palette-create")).is_some() }); assert!(options(&harness).is_empty()); - assert!( - harness - .query_by(|node| node.author_id() == Some("palette-empty")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("palette-empty")).is_some()); press(&mut harness, Modifiers::NONE, Key::Enter); until(&mut harness, "the note is written", |harness| { @@ -973,10 +815,7 @@ mod tests { let mut harness = opened(); type_in(&mut harness, "#op"); press(&mut harness, Modifiers::NONE, Key::Tab); - assert_eq!( - harness.state().state.palette.chips(), - [crate::state::palette::Chip::Tag("ops".into())] - ); + assert_eq!(harness.state().state.palette.chips(), [crate::state::palette::Chip::Tag("ops".into())]); until(&mut harness, "the tagged note alone", |harness| { options(harness) == ["Reset the dev database"] }); @@ -990,11 +829,7 @@ mod tests { let mut harness = opened(); let spaces = crate::notes::bench::spaces_of_backend(&harness.state().backend); let space = spaces[0].id.clone(); - harness - .state_mut() - .state - .spaces - .choose_space(Some(space.clone())); + harness.state_mut().state.spaces.choose_space(Some(space.clone())); type_in(&mut harness, "> folder"); press(&mut harness, Modifiers::NONE, Key::Enter); harness diff --git a/crates/ui/src/palette/options.rs b/crates/ui/src/palette/options.rs index 34dc08f8c..8717f0806 100644 --- a/crates/ui/src/palette/options.rs +++ b/crates/ui/src/palette/options.rs @@ -116,11 +116,7 @@ pub fn groups(state: &AppState) -> Vec { return if items.is_empty() { Vec::new() } else { - vec![Group { - heading: Some(keys::palette::groups::RECENT), - count: None, - items, - }] + vec![Group { heading: Some(keys::palette::groups::RECENT), count: None, items }] }; } search_groups(state, (notes, requests, tools), &term) @@ -152,21 +148,14 @@ fn found_requests(state: &AppState) -> Vec { fn found_tools(state: &AppState, term: &str) -> Vec { let palette = &state.palette; if palette.recent() { - return state - .tools - .recents() - .map(|(tool, _)| Item::Tool(tool.id)) - .collect(); + return state.tools.recents().map(|(tool, _)| Item::Tool(tool.id)).collect(); } if !palette.searched(Scope::Tools) { return Vec::new(); } let wanted = api::tools::fold(term); let language = state.language; - let mut found: Vec<_> = TOOLS - .iter() - .filter(|tool| matches(tool, &wanted, language)) - .collect(); + let mut found: Vec<_> = TOOLS.iter().filter(|tool| matches(tool, &wanted, language)).collect(); found.sort_by_key(|tool| !api::tools::fold(&tool.name(language)).contains(&wanted)); found.into_iter().map(|tool| Item::Tool(tool.id)).collect() } @@ -184,52 +173,30 @@ fn search_groups( .spaces() .iter() .filter(|space| api::notes::fold(&space.name).contains(&wanted)) - .map(|space| Item::Space { - id: space.id.clone(), - name: space.name.clone(), - }) + .map(|space| Item::Space { id: space.id.clone(), name: space.name.clone() }) .collect() } else { Vec::new() }; - let alone = SCOPES - .iter() - .filter(|scope| palette.searched(**scope)) - .count() - == 1; + let alone = SCOPES.iter().filter(|scope| palette.searched(**scope)).count() == 1; let found = [ (keys::palette::groups::NOTES, notes, SHARED_NOTES), (keys::palette::groups::REQUESTS, requests, SHARED), (keys::palette::groups::TOOLS, tools, SHARED), (keys::palette::groups::SPACES, spaces, SHARED), ]; - let several = found - .iter() - .filter(|(_, items, _)| !items.is_empty()) - .count() - > 1; + let several = found.iter().filter(|(_, items, _)| !items.is_empty()).count() > 1; let mut groups: Vec = found .into_iter() .filter(|(_, items, _)| !items.is_empty()) .map(|(heading, items, shared)| { - let items: Vec = items - .into_iter() - .take(if alone { ALONE } else { shared }) - .collect(); - Group { - heading: several.then_some(heading), - count: several.then_some(items.len()), - items, - } + let items: Vec = items.into_iter().take(if alone { ALONE } else { shared }).collect(); + Group { heading: several.then_some(heading), count: several.then_some(items.len()), items } }) .collect(); // After the results: finding something keeps first place. if !term.is_empty() && palette.searched(Scope::Notes) { - groups.push(Group { - heading: None, - count: None, - items: vec![Item::Create(term.to_owned())], - }); + groups.push(Group { heading: None, count: None, items: vec![Item::Create(term.to_owned())] }); } groups } @@ -239,15 +206,8 @@ fn scope_groups(state: &AppState, word: &str) -> Vec { let scopes: Vec = SCOPES .iter() .filter(|scope| !chosen.contains(&Chip::Scope(**scope))) - .filter(|scope| { - scope_words(**scope) - .iter() - .any(|each| each.starts_with(word)) - }) - .map(|scope| Item::Chip { - chip: Chip::Scope(*scope), - count: None, - }) + .filter(|scope| scope_words(**scope).iter().any(|each| each.starts_with(word))) + .map(|scope| Item::Chip { chip: Chip::Scope(*scope), count: None }) .collect(); let spaces: Vec = state .spaces @@ -255,25 +215,15 @@ fn scope_groups(state: &AppState, word: &str) -> Vec { .iter() .filter(|space| api::notes::fold(&space.name).starts_with(word)) .map(|space| Item::Chip { - chip: Chip::Space { - id: space.id.clone(), - name: space.name.clone(), - }, + chip: Chip::Space { id: space.id.clone(), name: space.name.clone() }, count: None, }) .collect(); - [ - (keys::palette::groups::SCOPES, scopes), - (keys::palette::groups::SPACE_NOTES, spaces), - ] - .into_iter() - .filter(|(_, items)| !items.is_empty()) - .map(|(heading, items)| Group { - heading: Some(heading), - count: None, - items, - }) - .collect() + [(keys::palette::groups::SCOPES, scopes), (keys::palette::groups::SPACE_NOTES, spaces)] + .into_iter() + .filter(|(_, items)| !items.is_empty()) + .map(|(heading, items)| Group { heading: Some(heading), count: None, items }) + .collect() } /// The most used first. @@ -290,19 +240,12 @@ fn tag_groups(state: &AppState, word: &str) -> Vec { let items: Vec = tags .into_iter() .take(MAX_TAGS) - .map(|usage| Item::Chip { - chip: Chip::Tag(usage.tag.clone()), - count: Some(usage.note_count), - }) + .map(|usage| Item::Chip { chip: Chip::Tag(usage.tag.clone()), count: Some(usage.note_count) }) .collect(); if items.is_empty() { return Vec::new(); } - vec![Group { - heading: Some(keys::palette::groups::TAGS), - count: None, - items, - }] + vec![Group { heading: Some(keys::palette::groups::TAGS), count: None, items }] } fn command_groups(state: &AppState, term: &str) -> Vec { @@ -318,11 +261,7 @@ fn command_groups(state: &AppState, term: &str) -> Vec { if items.is_empty() { return Vec::new(); } - vec![Group { - heading: Some(keys::palette::groups::COMMANDS), - count: Some(items.len()), - items, - }] + vec![Group { heading: Some(keys::palette::groups::COMMANDS), count: Some(items.len()), items }] } /// Said in place of a list, above the offer to create: what was looked for, so a typo shows. @@ -335,12 +274,8 @@ pub fn empty(state: &AppState, groups: &[Group]) -> Option { return None; } let message = match state.palette.mode() { - Mode::Scopes(word) => { - i18n::Message::new(keys::palette::empty::SCOPES).with("word", word.as_str()) - } - Mode::Tags(word) => { - i18n::Message::new(keys::palette::empty::TAGS).with("word", word.as_str()) - } + Mode::Scopes(word) => i18n::Message::new(keys::palette::empty::SCOPES).with("word", word.as_str()), + Mode::Tags(word) => i18n::Message::new(keys::palette::empty::TAGS).with("word", word.as_str()), Mode::Commands(term) => { i18n::Message::new(keys::palette::empty::COMMANDS).with("term", term.as_str()) } @@ -349,9 +284,7 @@ pub fn empty(state: &AppState, groups: &[Group]) -> Option { } Mode::Search(_) => match state.palette.chips() { [Chip::Scope(Scope::Notes)] => i18n::Message::new(keys::palette::empty::none::NOTES), - [Chip::Scope(Scope::Requests)] => { - i18n::Message::new(keys::palette::empty::none::REQUESTS) - } + [Chip::Scope(Scope::Requests)] => i18n::Message::new(keys::palette::empty::none::REQUESTS), [Chip::Scope(Scope::Tools)] => i18n::Message::new(keys::palette::empty::none::TOOLS), [Chip::Scope(Scope::Spaces)] => i18n::Message::new(keys::palette::empty::none::SPACES), _ => i18n::Message::new(keys::palette::empty::NOTHING), diff --git a/crates/ui/src/services/autostart.rs b/crates/ui/src/services/autostart.rs index 34027eecf..e529073c2 100644 --- a/crates/ui/src/services/autostart.rs +++ b/crates/ui/src/services/autostart.rs @@ -25,11 +25,7 @@ impl Default for AutostartState { impl AutostartState { pub fn with(system: Arc) -> Self { - Self { - system, - reading: None, - known: None, - } + Self { system, reading: None, known: None } } pub fn read(&mut self, backend: &Backend) { @@ -125,10 +121,7 @@ mod tests { #[test] fn the_preference_follows_what_the_system_holds() { let fake = Arc::new(Fake::default()); - let mut settings = Settings { - start_with_system: true, - ..Settings::default() - }; + let mut settings = Settings { start_with_system: true, ..Settings::default() }; let (_, _, followed) = launched(&fake, &mut settings); @@ -167,14 +160,42 @@ mod tests { fn a_system_that_cannot_be_read_leaves_the_switch_alone() { let fake = Arc::new(Fake::default()); *fake.unreadable.lock().unwrap() = true; - let mut settings = Settings { - start_with_system: true, - ..Settings::default() - }; + let mut settings = Settings { start_with_system: true, ..Settings::default() }; let (_, _, followed) = launched(&fake, &mut settings); assert!(!followed); assert!(settings.start_with_system); } + + #[test] + fn a_system_that_could_not_be_read_is_told_nothing_until_the_switch_moves() { + let fake = Arc::new(Fake::default()); + *fake.unreadable.lock().unwrap() = true; + let mut settings = Settings::default(); + let (mut state, backend, _) = launched(&fake, &mut settings); + + state.update(&backend, &mut settings); + backend.settle(); + assert!(fake.writes.lock().unwrap().is_empty()); + + settings.start_with_system = true; + state.update(&backend, &mut settings); + backend.settle(); + assert_eq!(*fake.writes.lock().unwrap(), [true]); + } + + /// Turned off from the system meanwhile, writing the same again would bring the entry back. + #[test] + fn a_system_that_already_agrees_is_not_written_to() { + let fake = Arc::new(Fake::default()); + let mut settings = Settings::default(); + let (mut state, backend, _) = launched(&fake, &mut settings); + *fake.enabled.lock().unwrap() = true; + + settings.start_with_system = true; + state.update(&backend, &mut settings); + backend.settle(); + assert!(fake.writes.lock().unwrap().is_empty()); + } } diff --git a/crates/ui/src/services/docs_quotes.rs b/crates/ui/src/services/docs_quotes.rs index 32a77b967..564bcb155 100644 --- a/crates/ui/src/services/docs_quotes.rs +++ b/crates/ui/src/services/docs_quotes.rs @@ -28,9 +28,7 @@ const KEYS: [(&str, &str); 8] = [ ]; fn pages(language: &str) -> impl Iterator { - docs_index() - .pages() - .filter_map(move |entry| docs_page(language, &entry.id)) + docs_index().pages().filter_map(move |entry| docs_page(language, &entry.id)) } fn runs(block: &Block) -> Vec { @@ -38,10 +36,7 @@ fn runs(block: &Block) -> Vec { Block::Paragraph(text) | Block::Note { text, .. } => text.clone(), Block::List { items, .. } => items.concat(), Block::Table { rows, .. } => rows.concat().concat(), - Block::Shortcuts { rows, .. } => rows - .iter() - .map(|row| Inline::Keys(row.keys.clone())) - .collect(), + Block::Shortcuts { rows, .. } => rows.iter().map(|row| Inline::Keys(row.keys.clone())).collect(), Block::Heading { .. } | Block::Code { .. } | Block::Pages(_) => Vec::new(), } } @@ -88,10 +83,7 @@ fn fits(text: &str, label: &str) -> bool { fn a_label_fits_its_text_and_what_its_placeholder_holds() { assert!(fits("Tableau", "Tableau")); assert!(fits("Quitter {{app}}", "Quitter DevNotes")); - assert!(fits( - "+ Créer une note « {{query}} »", - "+ Créer une note « … »" - )); + assert!(fits("+ Créer une note « {{query}} »", "+ Créer une note « … »")); assert!(!fits("Tableau", "Le tableau")); assert!(!fits("Quitter {{app}}", "Quitter")); assert!(!fits("{{count}} / {{all}}", "Ranger dans")); @@ -102,10 +94,7 @@ fn every_label_the_pages_quote_is_the_application_s() { let mut stale = Vec::new(); for (language, json) in LANGUAGES { let mut known = BTreeSet::new(); - texts( - &serde_json::from_str(json).expect("the translations"), - &mut known, - ); + texts(&serde_json::from_str(json).expect("the translations"), &mut known); for page in pages(language) { for run in page.body.iter().flat_map(runs) { let Inline::Label(label) = run else { continue }; @@ -116,11 +105,7 @@ fn every_label_the_pages_quote_is_the_application_s() { } } } - assert!( - stale.is_empty(), - "these labels are no text of the application:\n{}", - stale.join("\n") - ); + assert!(stale.is_empty(), "these labels are no text of the application:\n{}", stale.join("\n")); } /// Every combination the application answers to, by default, as `Ctrl Alt P`. @@ -159,18 +144,10 @@ fn every_shortcut_the_pages_quote_is_the_application_s() { .collect(); let held = matches!(named[0], "Ctrl" | "Alt" | "Shift" | "Meta"); if held && named.len() > 1 && !known.contains(&named.join(" ")) { - stale.push(place( - language, - page, - &format!("{}", keys.join(" ")), - )); + stale.push(place(language, page, &format!("{}", keys.join(" ")))); } } } } - assert!( - stale.is_empty(), - "these shortcuts are none of the application's:\n{}", - stale.join("\n") - ); + assert!(stale.is_empty(), "these shortcuts are none of the application's:\n{}", stale.join("\n")); } diff --git a/crates/ui/src/services/errors.rs b/crates/ui/src/services/errors.rs index 755354907..a71b9801e 100644 --- a/crates/ui/src/services/errors.rs +++ b/crates/ui/src/services/errors.rs @@ -53,9 +53,7 @@ pub fn message_of(error: &AppError) -> Option { error .params .iter() - .fold(Message::new(key), |message, (name, value)| { - message.with(name.as_str(), value.as_str()) - }), + .fold(Message::new(key), |message, (name, value)| message.with(name.as_str(), value.as_str())), ) } @@ -118,10 +116,7 @@ fn key_of(error: &AppError) -> Option { /// `errors.httpTimeout.folder`: the sub-key the parameter names, `request` when it names none. fn variant(error: &AppError, group: &str, parameter: &str) -> Option { - let value = error - .params - .get(parameter) - .map_or("request", String::as_str); + let value = error.params.get(parameter).map_or("request", String::as_str); Key::find(&format!("{group}.{value}")) } @@ -155,9 +150,7 @@ mod tests { fn a_variant_is_chosen_by_its_parameter() { let mut error = AppError::from(engine::error::StorageError::WrongPassphrase); error.code = ErrorCode::HttpTimeout; - error - .params - .insert("source".to_string(), "folder".to_string()); + error.params.insert("source".to_string(), "folder".to_string()); error.params.insert("name".to_string(), "API".to_string()); let message = message_of(&error).unwrap(); @@ -165,9 +158,123 @@ mod tests { assert_eq!(message.key.path(), "errors.httpTimeout.folder"); assert!(message.text(i18n::Language::En).contains("API")); error.params.remove("source"); - assert_eq!( - message_of(&error).unwrap().key.path(), - "errors.httpTimeout.request" + assert_eq!(message_of(&error).unwrap().key.path(), "errors.httpTimeout.request"); + } + + /// Every sub-key of a group is chosen by its value; a value the interface does not know leaves + /// the action's own message. + #[test] + fn each_sentence_of_a_group_is_chosen_by_its_value() { + let translations: serde_json::Value = + serde_json::from_str(include_str!("../../../i18n/translations/en.json")).unwrap(); + for (code, group, parameter) in [ + (ErrorCode::HttpTimeout, "httpTimeout", "source"), + (ErrorCode::HttpTooManyRedirects, "httpTooManyRedirects", "source"), + (ErrorCode::HttpHeaderName, "httpHeaderName", "source"), + (ErrorCode::HttpHeaderValue, "httpHeaderValue", "source"), + (ErrorCode::HttpScript, "httpScript", "failure"), + (ErrorCode::HttpRunData, "httpRunData", "fault"), + ] { + let values = translations["errors"][group].as_object().unwrap(); + assert!(!values.is_empty(), "{group}"); + for value in values.keys() { + let error = of(code, &[(parameter, value)]); + let key = message_of(&error).unwrap().key; + assert_eq!(key.path(), format!("errors.{group}.{value}")); + } + assert_eq!(message_of(&of(code, &[(parameter, "unknown")])), None, "{group}"); + } + } + + fn of(code: ErrorCode, params: &[(&str, &str)]) -> AppError { + let mut error = AppError::from(engine::error::StorageError::WrongPassphrase); + error.code = code; + error.params = params + .iter() + .map(|(name, value)| ((*name).to_owned(), (*value).to_owned())) + .collect(); + error + } + + #[test] + fn a_sentence_carries_the_values_of_its_error() { + let error = of(ErrorCode::FileTooLarge, &[("name", "plan.pdf"), ("limitMb", "10")]); + let message = message_of(&error).unwrap(); + + assert_eq!(message.key, keys::errors::FILE_TOO_LARGE); + assert_eq!(message.params.len(), 2); + assert!(message.text(i18n::Language::En).contains("plan.pdf")); + } + + #[test] + fn a_fallback_that_carries_what_was_typed_gives_way_to_a_sentence_of_the_core() { + let mut errors = ErrorNotifier::default(); + let typed = || Message::new(keys::errors::FOLDER_CREATE_FAILED).with("name", "Runbooks"); + + errors.report_message( + typed(), + &AppError::from(engine::error::ValidationError::new("name", "too long")), ); + assert!(errors.notice().unwrap().text(i18n::Language::En).contains("Runbooks")); + errors.report_message(typed(), &of(ErrorCode::DuplicateFolderName, &[])); + assert_eq!(errors.notice().unwrap().key, keys::errors::FOLDER_NAME_TAKEN); + } + + #[test] + fn the_same_failure_stands_once() { + let mut errors = ErrorNotifier::default(); + for _ in 0..3 { + errors.report(keys::errors::UNLOCK_FAILED, &of(ErrorCode::WrongPassphrase, &[])); + } + + assert_eq!(errors.shown().count(), 1); + } + + /// Two codes are never said in the same words: the sentence is what tells them apart. + #[test] + fn each_code_has_its_own_sentence() { + use engine::error::ErrorCode; + + let sentence = |code| { + key_of(&AppError { code, params: std::collections::BTreeMap::default(), detail: String::new() }) + }; + let said: Vec = [ + ErrorCode::SpaceNotFound, + ErrorCode::FolderNotFound, + ErrorCode::AttachmentNotFound, + ErrorCode::HttpEnvironmentNotFound, + ErrorCode::DuplicateEnvironmentName, + ErrorCode::RevisionNotFound, + ErrorCode::LibraryOpen, + ErrorCode::LastLibrary, + ErrorCode::NothingToSetAside, + ErrorCode::BackupNotFound, + ErrorCode::BackupUnopenable, + ErrorCode::StorageUnavailable, + ErrorCode::PassphraseRequired, + ErrorCode::LibraryDamaged, + ErrorCode::HttpVariable, + ErrorCode::HttpInvalidUrl, + ErrorCode::HttpTls, + ErrorCode::HttpFileUnreadable, + ErrorCode::HttpFileTooLarge, + ErrorCode::HttpFell, + ErrorCode::HttpGraphqlVariables, + ErrorCode::HttpWebsocketRefused, + ErrorCode::HttpScriptSkipped, + ErrorCode::HttpScriptMethod, + ErrorCode::HttpScriptProtected, + ErrorCode::HttpScriptFile, + ] + .into_iter() + .map(|code| sentence(code).unwrap_or_else(|| panic!("{code:?}"))) + .collect(); + let mut words: Vec = + said.iter().map(|key| i18n::translate(i18n::Language::En, *key, &[])).collect(); + let count = words.len(); + words.sort(); + words.dedup(); + + assert_eq!(words.len(), count); } } diff --git a/crates/ui/src/services/global_keys.rs b/crates/ui/src/services/global_keys.rs index bdd41665b..65b2df001 100644 --- a/crates/ui/src/services/global_keys.rs +++ b/crates/ui/src/services/global_keys.rs @@ -23,12 +23,7 @@ impl Default for GlobalKeys { impl GlobalKeys { pub fn with(system: Box) -> Self { - Self { - system, - taken: Vec::new(), - released: false, - held: Vec::new(), - } + Self { system, taken: Vec::new(), released: false, held: Vec::new() } } /// What the last taking could not have: another application holds it. @@ -196,4 +191,57 @@ mod tests { assert_eq!(fake.sets.lock().unwrap().len(), 2); assert!(errors.notice().is_none(), "it was said when they were set"); } + + #[test] + fn a_key_that_is_free_again_is_held_no_more() { + let fake = Fake::default(); + *fake.held_elsewhere.lock().unwrap() = vec!["Ctrl+Alt+P".to_owned()]; + let mut keys = keys_on(&fake); + let mut errors = ErrorNotifier::default(); + let mut bindings = Bindings::default(); + keys.update(&bindings, false, &mut errors); + + fake.held_elsewhere.lock().unwrap().clear(); + bindings.set(shortcuts::ACTIONS[0], "Ctrl+Alt+K".to_owned()); + keys.update(&bindings, false, &mut errors); + + assert!(keys.held().is_empty()); + assert_eq!(errors.shown().count(), 1, "nothing more to say"); + } + + #[test] + fn a_key_moved_while_a_field_listened_is_taken_when_it_is_done() { + let fake = Fake::default(); + let mut keys = keys_on(&fake); + let mut errors = ErrorNotifier::default(); + let mut bindings = Bindings::default(); + keys.update(&bindings, false, &mut errors); + keys.update(&bindings, true, &mut errors); + + bindings.set(shortcuts::ACTIONS[0], "Ctrl+Alt+K".to_owned()); + keys.update(&bindings, true, &mut errors); + assert_eq!(fake.sets.lock().unwrap().len(), 1); + keys.update(&bindings, false, &mut errors); + assert_eq!(fake.sets.lock().unwrap()[1][0].1, "Ctrl+Alt+K"); + } + + #[test] + fn only_the_keys_of_the_whole_machine_are_taken_and_each_is_described() { + let each: Vec = wanted(&Bindings::default()).into_iter().map(|(key, _)| key).collect(); + + assert_eq!(each, [Global::Palette, Global::Capture, Global::NewNote]); + for language in Language::ALL { + let described = described(language); + assert!(described.iter().map(|(key, _)| *key).eq(each.iter().copied())); + assert!(described.iter().all(|(_, words)| !words.is_empty())); + } + } + + #[test] + fn the_exit_lets_go_of_the_keys() { + let fake = Fake::default(); + keys_on(&fake).release(); + + assert_eq!(*fake.releases.lock().unwrap(), 1); + } } diff --git a/crates/ui/src/services/highlight.rs b/crates/ui/src/services/highlight.rs index 0ac41dc8a..d1c495068 100644 --- a/crates/ui/src/services/highlight.rs +++ b/crates/ui/src/services/highlight.rs @@ -180,11 +180,7 @@ fn parse( continue; } if let Some(lines) = parser.lines(line_of(&request.rope), request.visible.clone()) { - let answer = Answer { - generation: request.generation, - start: request.visible.start, - lines, - }; + let answer = Answer { generation: request.generation, start: request.visible.start, lines }; if answers.send(answer).is_err() { return; } @@ -260,4 +256,72 @@ mod tests { assert!(lines[0].iter().any(|(_, token)| *token == Token::Keyword)); assert!(Colouring::new(&ctx, "Not a language").is_none()); } + + /// Comments and emphasis lean; nothing else does. + #[test] + fn each_class_has_its_colour_and_two_lean() { + let p = &crate::theme::tokens::DARK; + for (token, expected, leans) in [ + (Token::Keyword, p.blue, false), + (Token::String, p.green, false), + (Token::Literal, p.amber_text, false), + (Token::Name, p.purple, false), + (Token::Property, p.text_0, false), + (Token::Strong, p.text_0, false), + (Token::Meta, p.text_1, false), + (Token::Comment, p.text_2, true), + (Token::Deleted, p.red, false), + (Token::Emphasis, p.text_1, true), + ] { + assert_eq!(colour(p, token), (expected, leans), "{token:?}"); + } + } + + #[test] + fn a_newer_window_keeps_the_earliest_edit_it_has_not_seen() { + let request = |generation, invalid_from| Request { + generation, + invalid_from, + rope: text::Rope::new(), + visible: 0..10, + }; + for (older, newer, from) in [ + (Some(3), Some(9), Some(3)), + (Some(9), Some(3), Some(3)), + (Some(3), None, Some(3)), + (None, Some(9), Some(9)), + (None, None, None), + ] { + let merged = merged(&request(1, older), request(2, newer)); + assert_eq!((merged.generation, merged.invalid_from), (2, from)); + } + } + + #[test] + fn an_edit_leaves_the_lines_above_it_as_they_are() { + text::highlight::warm(); + let rope = rope(100); + let mut colouring = Colouring::new(&egui::Context::default(), "JavaScript").unwrap(); + assert!(coloured(&mut colouring, &rope, 0..50)); + + colouring.edited(30); + colouring.edited(40); + let fresh = |line: usize| colouring.fresh.contains(&line); + assert!((0..30).all(fresh) && !(30..50).any(fresh)); + assert_eq!(colouring.invalid_from, Some(30), "from the first one"); + } + + #[test] + fn a_window_known_is_not_asked_again() { + text::highlight::warm(); + let rope = rope(100); + let mut colouring = Colouring::new(&egui::Context::default(), "JavaScript").unwrap(); + assert!(coloured(&mut colouring, &rope, 0..50)); + colouring.asked = None; + + colouring.window(&rope, 10..20); + assert!(colouring.asked.is_none()); + colouring.window(&rope, 60..70); + assert_eq!(colouring.asked, Some((0, 60..70))); + } } diff --git a/crates/ui/src/services/notices.rs b/crates/ui/src/services/notices.rs index af5c86c26..83cd4894c 100644 --- a/crates/ui/src/services/notices.rs +++ b/crates/ui/src/services/notices.rs @@ -48,16 +48,26 @@ mod tests { } #[test] - fn the_latest_is_first_the_oldest_makes_room_and_one_is_dismissed_alone() { + fn the_latest_is_first_and_the_oldest_makes_room() { let mut notices = Notices::default(); for _ in 0..KEPT + 2 { notices.push(Message::new(keys::errors::RETRY)); } + assert_eq!(numbers(¬ices), [6, 5, 4, 3]); - notices.dismiss(5); - assert_eq!(numbers(¬ices), [6, 4, 3]); - notices.dismiss(5); - assert_eq!(numbers(¬ices), [6, 4, 3]); + } + + #[test] + fn one_is_dismissed_by_its_number_alone() { + let mut notices = Notices::default(); + for _ in 0..3 { + notices.push(Message::new(keys::errors::RETRY)); + } + notices.dismiss(2); + assert_eq!(numbers(¬ices), [3, 1]); + + notices.dismiss(2); + assert_eq!(numbers(¬ices), [3, 1]); } #[test] diff --git a/crates/ui/src/services/preferences.rs b/crates/ui/src/services/preferences.rs index 18d997bcb..d9637d20b 100644 --- a/crates/ui/src/services/preferences.rs +++ b/crates/ui/src/services/preferences.rs @@ -2,7 +2,7 @@ //! string. Two of them: the application's, in the profile, and the open library's, in its directory, //! for `devnotes.notes.*`. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::io; use std::path::Path; @@ -40,12 +40,10 @@ impl Preferences { self.0.get(key).and_then(Value::as_str) } - /// How many keys of `other` say something else here. + /// How many keys the two do not say alike, one of them alone having it included. pub fn differences(&self, other: &Self) -> u32 { - let differing = other - .0 - .iter() - .filter(|(key, value)| self.0.get(*key) != Some(*value)); + let keys: BTreeSet<&String> = self.0.keys().chain(other.0.keys()).collect(); + let differing = keys.into_iter().filter(|key| self.0.get(*key) != other.0.get(*key)); u32::try_from(differing.count()).unwrap_or(u32::MAX) } @@ -54,8 +52,7 @@ impl Preferences { } pub fn set(&mut self, key: &str, value: &str) { - self.0 - .insert(key.to_string(), Value::String(value.to_string())); + self.0.insert(key.to_string(), Value::String(value.to_string())); } } @@ -67,11 +64,8 @@ mod tests { fn a_key_this_version_does_not_know_survives_a_write() { let directory = tempfile::tempdir().unwrap(); let file = directory.path().join("preferences.json"); - std::fs::write( - &file, - r#"{ "devnotes.theme": "dark", "devnotes.later": { "kept": [1, 2] } }"#, - ) - .unwrap(); + std::fs::write(&file, r#"{ "devnotes.theme": "dark", "devnotes.later": { "kept": [1, 2] } }"#) + .unwrap(); let mut preferences = Preferences::read(&file); preferences.set("devnotes.theme", "light"); @@ -93,4 +87,48 @@ mod tests { std::fs::write(&file, "{ half").unwrap(); assert_eq!(Preferences::read(&file), Preferences::default()); } + + #[test] + fn only_a_text_is_the_value_of_a_key() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("preferences.json"); + std::fs::write(&file, r#"{ "a": "x", "b": 3, "c": null, "d": true }"#).unwrap(); + let preferences = Preferences::read(&file); + + assert_eq!( + ["a", "b", "c", "d", "e"].map(|key| preferences.get(key)), + [Some("x"), None, None, None, None] + ); + } + + #[test] + fn what_two_files_say_otherwise_is_counted() { + let of = |pairs: &[(&str, &str)]| { + let mut preferences = Preferences::default(); + for (key, value) in pairs { + preferences.set(key, value); + } + preferences + }; + let here = of(&[("a", "1"), ("b", "2")]); + + assert_eq!(here.differences(&here), 0); + assert_eq!(here.differences(&of(&[("a", "1"), ("b", "x")])), 1); + assert_eq!(here.differences(&of(&[("a", "1"), ("b", "2"), ("c", "3")])), 1); + } + + #[test] + fn a_key_removed_is_written_no_more() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("nested").join("preferences.json"); + let mut preferences = Preferences::default(); + preferences.set("a", "1"); + preferences.set("b", "2"); + preferences.remove("a"); + preferences.write(&file).unwrap(); + + let mut expected = Preferences::default(); + expected.set("b", "2"); + assert_eq!(Preferences::read(&file), expected); + } } diff --git a/crates/ui/src/services/samples.rs b/crates/ui/src/services/samples.rs index 10a90e04c..c48dd4e86 100644 --- a/crates/ui/src/services/samples.rs +++ b/crates/ui/src/services/samples.rs @@ -60,10 +60,7 @@ pub fn samples(language: i18n::Language, now: DateTime) -> Samples { text::checklist::BOARD, text::checklist::KIND, ] - .map(|key| ChecklistItem { - text: tr(key), - done: false, - }); + .map(|key| ChecklistItem { text: tr(key), done: false }); // The two Notes open the board, the snippets fill a zone; the list is left loose on // purpose: « no folder » is a state of its own, and the first launch shows it. let notes = vec![ @@ -152,10 +149,7 @@ fn draft(title: String, kind: NoteKind) -> NoteDraft { } fn filed(folder: u32, draft: NoteDraft) -> SampleNote { - SampleNote { - folder: Some(folder), - draft, - } + SampleNote { folder: Some(folder), draft } } /// The end of the local day a week on: midnight would leave a note dated today expired at once. @@ -202,14 +196,8 @@ mod tests { }; let local = at.with_timezone(&Local); - assert_eq!( - local.date_naive(), - now.with_timezone(&Local).date_naive() + Days::new(7) - ); - assert_eq!( - local.time(), - NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap() - ); + assert_eq!(local.date_naive(), now.with_timezone(&Local).date_naive() + Days::new(7)); + assert_eq!(local.time(), NaiveTime::from_hms_milli_opt(23, 59, 59, 999).unwrap()); assert!(list.folder.is_none()); assert_eq!(list.draft.items.len(), 9); } diff --git a/crates/ui/src/services/settings.rs b/crates/ui/src/services/settings.rs index a09594010..b382e06ae 100644 --- a/crates/ui/src/services/settings.rs +++ b/crates/ui/src/services/settings.rs @@ -61,10 +61,7 @@ pub enum CalcDate { } #[derive(Debug, Clone, PartialEq, Eq)] -#[expect( - clippy::struct_excessive_bools, - reason = "each is its own display choice" -)] +#[expect(clippy::struct_excessive_bools, reason = "each is its own display choice")] pub struct Settings { pub locale: LocaleChoice, pub theme: Appearance, @@ -200,9 +197,7 @@ impl Settings { rail_width: preferences .get(RAIL) .and_then(|width| width.parse::().ok()) - .map_or(RAIL_DEFAULT, |width| { - width.clamp(RAIL_WIDTH.0, RAIL_WIDTH.1) - }), + .map_or(RAIL_DEFAULT, |width| width.clamp(RAIL_WIDTH.0, RAIL_WIDTH.1)), rail_shown: preferences.get(RAIL_SHOWN) != Some("false"), editor_fullscreen: preferences.get(EDITOR_FULLSCREEN) == Some("true"), editor_panel_width: preferences @@ -219,8 +214,7 @@ impl Settings { .unwrap_or(380), code_indent: chosen(preferences, CODE_INDENT, &INDENTS).unwrap_or_default(), code_wrap: preferences.get(CODE_WRAP) == Some("true"), - default_note_kind: chosen(preferences, DEFAULT_NOTE_KIND, &NOTE_KINDS) - .unwrap_or_default(), + default_note_kind: chosen(preferences, DEFAULT_NOTE_KIND, &NOTE_KINDS).unwrap_or_default(), start_with_system: preferences.get(START_WITH_SYSTEM) == Some("true"), minimize_to_tray: preferences.get(MINIMIZE_TO_TRAY) == Some("true"), close_to_tray: preferences.get(CLOSE_TO_TRAY) != Some("false"), @@ -228,19 +222,10 @@ impl Settings { automatic_backups: preferences.get(AUTOMATIC_BACKUPS) != Some("false"), copy_confirmation: preferences.get(COPY_CONFIRMATION) != Some("false"), update_notifications: preferences.get(UPDATE_NOTIFICATIONS) != Some("false"), - skipped_update: preferences - .get(SKIPPED_UPDATE) - .unwrap_or_default() - .to_owned(), - calc_decimals: preferences - .get(CALC_DECIMALS) - .and_then(|places| places.parse().ok()), - calc_number_format: preferences - .get(CALC_NUMBER_FORMAT) - .unwrap_or(CALC_LANGUAGE) - .to_owned(), - calc_date_format: chosen(preferences, CALC_DATE_FORMAT, &CALC_DATES) - .unwrap_or_default(), + skipped_update: preferences.get(SKIPPED_UPDATE).unwrap_or_default().to_owned(), + calc_decimals: preferences.get(CALC_DECIMALS).and_then(|places| places.parse().ok()), + calc_number_format: preferences.get(CALC_NUMBER_FORMAT).unwrap_or(CALC_LANGUAGE).to_owned(), + calc_date_format: chosen(preferences, CALC_DATE_FORMAT, &CALC_DATES).unwrap_or_default(), bindings: read_bindings(preferences), } } @@ -263,10 +248,7 @@ impl Settings { preferences.set(HTTP_REQUEST_SHARE, &share.to_string()); preferences.set(CODE_INDENT, name_of(&INDENTS, self.code_indent)); preferences.set(CODE_WRAP, flag(self.code_wrap)); - preferences.set( - DEFAULT_NOTE_KIND, - name_of(&NOTE_KINDS, self.default_note_kind), - ); + preferences.set(DEFAULT_NOTE_KIND, name_of(&NOTE_KINDS, self.default_note_kind)); preferences.set(START_WITH_SYSTEM, flag(self.start_with_system)); preferences.set(MINIMIZE_TO_TRAY, flag(self.minimize_to_tray)); preferences.set(CLOSE_TO_TRAY, flag(self.close_to_tray)); @@ -280,10 +262,7 @@ impl Settings { .map_or_else(|| "auto".to_owned(), |places| places.to_string()); preferences.set(CALC_DECIMALS, &places); preferences.set(CALC_NUMBER_FORMAT, &self.calc_number_format); - preferences.set( - CALC_DATE_FORMAT, - name_of(&CALC_DATES, self.calc_date_format), - ); + preferences.set(CALC_DATE_FORMAT, name_of(&CALC_DATES, self.calc_date_format)); for action in shortcuts::every() { let key = shortcuts::preference_key(action); if self.bindings.is_default(action) { @@ -315,11 +294,7 @@ fn read_share(stored: Option<&str>) -> u16 { if tenths < f64::from(HTTP_SHARE.0) || tenths > f64::from(HTTP_SHARE.1) { return 0; } - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "within HTTP_SHARE" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "within HTTP_SHARE")] let tenths = tenths as u16; tenths } @@ -330,10 +305,7 @@ fn flag(on: bool) -> &'static str { fn chosen(preferences: &Preferences, key: &str, choices: &[(&str, T)]) -> Option { let stored = preferences.get(key)?; - choices - .iter() - .find(|(name, _)| *name == stored) - .map(|(_, value)| *value) + choices.iter().find(|(name, _)| *name == stored).map(|(_, value)| *value) } fn name_of(choices: &[(&'static str, T)], value: T) -> &'static str { @@ -343,25 +315,13 @@ fn name_of(choices: &[(&'static str, T)], value: T) -> &'st .map_or("", |(name, _)| *name) } -const LOCALES: [(&str, LocaleChoice); 3] = [ - ("system", LocaleChoice::System), - ("fr", LocaleChoice::Fr), - ("en", LocaleChoice::En), -]; -const THEMES: [(&str, Appearance); 3] = [ - ("system", Appearance::System), - ("dark", Appearance::Dark), - ("light", Appearance::Light), -]; -const DENSITIES: [(&str, Density); 2] = [ - ("comfortable", Density::Comfortable), - ("compact", Density::Compact), -]; -const AREAS: [(&str, Area); 3] = [ - ("notes", Area::Notes), - ("tools", Area::Tools), - ("http", Area::Http), -]; +const LOCALES: [(&str, LocaleChoice); 3] = + [("system", LocaleChoice::System), ("fr", LocaleChoice::Fr), ("en", LocaleChoice::En)]; +const THEMES: [(&str, Appearance); 3] = + [("system", Appearance::System), ("dark", Appearance::Dark), ("light", Appearance::Light)]; +const DENSITIES: [(&str, Density); 2] = + [("comfortable", Density::Comfortable), ("compact", Density::Compact)]; +const AREAS: [(&str, Area); 3] = [("notes", Area::Notes), ("tools", Area::Tools), ("http", Area::Http)]; const INDENTS: [(&str, IndentChoice); 4] = [ ("language", IndentChoice::Language), ("two-spaces", IndentChoice::TwoSpaces), @@ -374,11 +334,8 @@ const NOTE_KINDS: [(&str, NoteKind); 4] = [ ("checklist", NoteKind::Checklist), ("calc", NoteKind::Calc), ]; -const CALC_DATES: [(&str, CalcDate); 3] = [ - ("numeric", CalcDate::Numeric), - ("short", CalcDate::Short), - ("long", CalcDate::Long), -]; +const CALC_DATES: [(&str, CalcDate); 3] = + [("numeric", CalcDate::Numeric), ("short", CalcDate::Short), ("long", CalcDate::Long)]; /// What the preferences panel edits before « Apply ». Only the theme and the density are seen /// at once, as a preview; the rest waits for the button, and the native side reads the @@ -391,10 +348,7 @@ pub struct SettingsDraft { impl SettingsDraft { pub fn open(applied: Settings) -> Self { - Self { - draft: applied.clone(), - applied, - } + Self { draft: applied.clone(), applied } } pub fn edit(&mut self, change: impl FnOnce(&mut Settings)) { @@ -415,15 +369,7 @@ impl SettingsDraft { /// What the window shows meanwhile: the draft's look over the applied rest. pub fn previewed(&self) -> Settings { - Settings { - theme: self.draft.theme, - density: self.draft.density, - ..self.applied.clone() - } - } - - pub fn is_changed(&self) -> bool { - self.draft != self.applied + Settings { theme: self.draft.theme, density: self.draft.density, ..self.applied.clone() } } /// The settings to adopt; closing without applying is dropping the draft. @@ -523,10 +469,20 @@ mod tests { assert_eq!(draft.previewed().theme, Appearance::Light); assert_eq!(draft.previewed().locale, LocaleChoice::System); - assert!(draft.is_changed()); + assert!(draft.pending() > 0); assert_eq!(draft.pending(), 2); assert_eq!(draft.apply().locale, LocaleChoice::En); - assert!(!draft.is_changed()); + assert_eq!(draft.pending(), 0); + } + + /// A key put back leaves the file: what is no longer there counts too. + #[test] + fn a_key_put_back_to_its_default_waits_for_apply() { + let mut draft = SettingsDraft::open(Settings { bindings: moved_key(), ..Settings::default() }); + assert_eq!(draft.pending(), 0); + + draft.edit(|settings| settings.bindings.reset(shortcuts::ACTIONS[9])); + assert_eq!(draft.pending(), 1); } #[test] @@ -536,4 +492,139 @@ mod tests { assert_eq!(read, Settings::default()); assert!(read.close_to_tray && read.automatic_backups && read.copy_confirmation); } + + fn stored(key: &str, value: &str) -> Settings { + let mut preferences = Preferences::default(); + preferences.set(key, value); + Settings::read(&preferences) + } + + #[test] + fn a_rail_is_brought_back_within_its_bounds() { + for (written, width) in [ + ("159", 160), + ("160", 160), + ("520", 520), + ("521", 520), + ("wide", RAIL_DEFAULT), + ("-3", RAIL_DEFAULT), + ("", RAIL_DEFAULT), + ] { + assert_eq!(stored("devnotes.libraryRailWidth", written).rail_width, width, "{written}"); + } + } + + /// Out of bounds, the request takes the height its content asks. + #[test] + fn a_share_is_read_in_tenths_of_a_percent_within_its_bounds() { + for (written, share) in [ + ("42.3", 423), + ("42.36", 424), + ("5", 50), + ("4.9", 0), + ("95", 950), + ("95.1", 0), + ("0", 0), + ("-10", 0), + ("NaN", 0), + ("half", 0), + ] { + assert_eq!(stored("devnotes.httpRequestShare", written).http_request_share, share, "{written}"); + } + } + + #[test] + fn a_number_that_does_not_read_is_the_default() { + assert_eq!(stored("devnotes.editorPanelWidth", "wide").editor_panel_width, 0); + assert_eq!(stored("devnotes.httpHistoryListWidth", "wide").history_list_width, 380); + for (written, places) in [("auto", None), ("", None), ("2", Some(2)), ("-1", None)] { + assert_eq!(stored("devnotes.calcDecimals", written).calc_decimals, places, "{written}"); + } + } + + /// Every switch, by what turns it: those that are on need a plain `false`, the others a plain + /// `true`. + #[test] + fn a_switch_moves_on_its_plain_word_alone() { + type Read = fn(&Settings) -> bool; + let switches: [(&str, bool, Read); 13] = [ + ("showLibraryRail", true, |s| s.rail_shown), + ("editorFullscreen", false, |s| s.editor_fullscreen), + ("editorHeaderFolded", false, |s| s.editor_header_folded), + ("editorFieldsPanel", true, |s| s.editor_fields_open), + ("editorDetails", true, |s| s.editor_details_open), + ("codeWrap", false, |s| s.code_wrap), + ("startWithSystem", false, |s| s.start_with_system), + ("minimizeToTray", false, |s| s.minimize_to_tray), + ("closeToTray", true, |s| s.close_to_tray), + ("showPinnedFirst", true, |s| s.show_pinned_first), + ("automaticBackups", true, |s| s.automatic_backups), + ("copyConfirmation", true, |s| s.copy_confirmation), + ("updateNotifications", true, |s| s.update_notifications), + ]; + for (name, shipped, read) in switches { + let key = format!("devnotes.{name}"); + let moves = if shipped { "false" } else { "true" }; + assert_eq!(read(&stored(&key, moves)), !shipped, "{name}"); + for other in ["", "1", "0", "TRUE", "False", if shipped { "true" } else { "false" }] { + assert_eq!(read(&stored(&key, other)), shipped, "{name} {other}"); + } + } + } + + #[test] + fn every_choice_reads_back_from_its_word() { + fn round(choices: &[(&'static str, T)]) { + for (word, value) in choices { + let mut preferences = Preferences::default(); + preferences.set("k", name_of(choices, *value)); + assert_eq!(chosen(&preferences, "k", choices), Some(*value)); + assert_eq!(name_of(choices, *value), *word); + } + } + round(&LOCALES); + round(&THEMES); + round(&DENSITIES); + round(&AREAS); + round(&INDENTS); + round(&NOTE_KINDS); + round(&CALC_DATES); + } + + #[test] + fn a_key_put_back_leaves_the_file() { + let mut preferences = Preferences::default(); + Settings { bindings: moved_key(), ..Settings::default() }.write(&mut preferences); + assert!(preferences.get("devnotes.shortcut.canvas.pin").is_some()); + + Settings::default().write(&mut preferences); + assert_eq!(preferences.get("devnotes.shortcut.canvas.pin"), None); + } + + #[test] + fn tab_inserts_the_unit_chosen_or_the_language_s_own() { + use IndentChoice::{FourSpaces, Language, Tab, TwoSpaces}; + + let rust = engine::notes::language::Language::Rs; + assert_eq!([TwoSpaces, FourSpaces, Tab].map(|choice| choice.unit(rust)), [" ", " ", "\t"]); + assert_eq!(Language.unit(rust), crate::notes::language::indent_unit(rust)); + } + + #[test] + fn a_language_chosen_is_that_one() { + assert_eq!(LocaleChoice::Fr.language(), i18n::Language::Fr); + assert_eq!(LocaleChoice::En.language(), i18n::Language::En); + assert_eq!(LocaleChoice::System.language(), i18n::Language::of_system()); + } + + #[test] + fn a_draft_put_back_has_nothing_to_apply() { + let mut draft = SettingsDraft::open(Settings::default()); + draft.edit(|settings| settings.code_wrap = true); + assert_eq!(draft.pending(), 1); + + draft.edit(|settings| settings.code_wrap = false); + assert_eq!(draft.pending(), 0); + assert_eq!(draft.apply(), Settings::default()); + } } diff --git a/crates/ui/src/services/shortcuts.rs b/crates/ui/src/services/shortcuts.rs index 791aa43ca..71e569ff4 100644 --- a/crates/ui/src/services/shortcuts.rs +++ b/crates/ui/src/services/shortcuts.rs @@ -25,18 +25,8 @@ pub struct Rebindable { pub scope: Scope, } -const fn rebindable( - id: &'static str, - label: i18n::Key, - fallback: &'static str, - scope: Scope, -) -> Rebindable { - Rebindable { - id, - label, - fallback, - scope, - } +const fn rebindable(id: &'static str, label: i18n::Key, fallback: &'static str, scope: Scope) -> Rebindable { + Rebindable { id, label, fallback, scope } } pub const PALETTE: &str = "palette"; @@ -46,90 +36,20 @@ pub const RAIL: &str = "areas.rail"; /// In the order the page lists them. pub const ACTIONS: [Rebindable; 14] = [ - rebindable( - PALETTE, - keys::shortcuts::global::PALETTE, - "Ctrl+Alt+P", - Scope::Global, - ), - rebindable( - CAPTURE, - keys::shortcuts::global::CAPTURE, - "Ctrl+Alt+V", - Scope::Global, - ), - rebindable( - NEW_NOTE, - keys::shortcuts::global::NEW_NOTE, - "Ctrl+Alt+N", - Scope::Global, - ), - rebindable( - "canvas.newSnippet", - keys::shortcuts::canvas::NEW_SNIPPET, - "Ctrl+N", - Scope::Canvas, - ), - rebindable( - "canvas.newNote", - keys::shortcuts::canvas::NEW_NOTE, - "Ctrl+Shift+N", - Scope::Canvas, - ), - rebindable( - "canvas.newChecklist", - keys::shortcuts::canvas::NEW_CHECKLIST, - "Ctrl+Shift+L", - Scope::Canvas, - ), - rebindable( - "canvas.newCalc", - keys::shortcuts::canvas::NEW_CALC, - "Ctrl+Shift+M", - Scope::Canvas, - ), - rebindable( - "canvas.newDrawing", - keys::shortcuts::canvas::NEW_DRAWING, - "Ctrl+Shift+D", - Scope::Canvas, - ), - rebindable( - "canvas.copy", - keys::shortcuts::canvas::COPY, - "C", - Scope::Canvas, - ), - rebindable( - "canvas.pin", - keys::shortcuts::canvas::PIN, - "P", - Scope::Canvas, - ), - rebindable( - "canvas.check", - keys::shortcuts::canvas::CHECK, - "X", - Scope::Canvas, - ), - rebindable( - "canvas.align", - keys::shortcuts::canvas::ALIGN, - "A", - Scope::Canvas, - ), - rebindable( - "canvas.trash", - keys::shortcuts::canvas::TRASH, - "Delete", - Scope::Canvas, - ), - rebindable( - "canvas.undo", - keys::shortcuts::canvas::UNDO, - "Ctrl+Z", - Scope::Canvas, - ), + rebindable(PALETTE, keys::shortcuts::global::PALETTE, "Ctrl+Alt+P", Scope::Global), + rebindable(CAPTURE, keys::shortcuts::global::CAPTURE, "Ctrl+Alt+V", Scope::Global), + rebindable(NEW_NOTE, keys::shortcuts::global::NEW_NOTE, "Ctrl+Alt+N", Scope::Global), + rebindable("canvas.newSnippet", keys::shortcuts::canvas::NEW_SNIPPET, "Ctrl+N", Scope::Canvas), + rebindable("canvas.newNote", keys::shortcuts::canvas::NEW_NOTE, "Ctrl+Shift+N", Scope::Canvas), + rebindable("canvas.newChecklist", keys::shortcuts::canvas::NEW_CHECKLIST, "Ctrl+Shift+L", Scope::Canvas), + rebindable("canvas.newCalc", keys::shortcuts::canvas::NEW_CALC, "Ctrl+Shift+M", Scope::Canvas), + rebindable("canvas.newDrawing", keys::shortcuts::canvas::NEW_DRAWING, "Ctrl+Shift+D", Scope::Canvas), + rebindable("canvas.copy", keys::shortcuts::canvas::COPY, "C", Scope::Canvas), + rebindable("canvas.pin", keys::shortcuts::canvas::PIN, "P", Scope::Canvas), + rebindable("canvas.check", keys::shortcuts::canvas::CHECK, "X", Scope::Canvas), + rebindable("canvas.align", keys::shortcuts::canvas::ALIGN, "A", Scope::Canvas), + rebindable("canvas.trash", keys::shortcuts::canvas::TRASH, "Delete", Scope::Canvas), + rebindable("canvas.undo", keys::shortcuts::canvas::UNDO, "Ctrl+Z", Scope::Canvas), ]; /// The rail's, apart from the canvas's: it acts in the three areas. @@ -189,19 +109,6 @@ pub fn key_named(name: &str) -> Option { Key::from_name(name).filter(|key| name_of(*key).is_some()) } -/// The W3C `code` of the position `key` stands at. -pub fn code_of(key: Key) -> Option { - let name = name_of(key)?; - let first = name.chars().next()?; - Some(if name.len() == 1 && first.is_ascii_alphabetic() { - format!("Key{name}") - } else if name.len() == 1 && first.is_ascii_digit() { - format!("Digit{name}") - } else { - name - }) -} - /// `Ctrl+Alt+P`, the modifiers first. `Ctrl` covers ⌘ too. fn written(modifiers: Modifiers, name: &str, scope: Scope) -> String { let mut parts = Vec::with_capacity(4); @@ -303,9 +210,7 @@ pub struct Bindings(BTreeMap<&'static str, String>); impl Bindings { pub fn of(&self, action: Rebindable) -> &str { - self.0 - .get(action.id) - .map_or(action.fallback, String::as_str) + self.0.get(action.id).map_or(action.fallback, String::as_str) } pub fn is_default(&self, action: Rebindable) -> bool { @@ -334,15 +239,9 @@ impl Bindings { pub fn conflicts(&self) -> Vec<(String, Vec)> { let mut claims: BTreeMap> = BTreeMap::new(); for action in every() { - claims - .entry(self.of(action).to_owned()) - .or_default() - .push(action); + claims.entry(self.of(action).to_owned()).or_default().push(action); } - claims - .into_iter() - .filter(|(_, actions)| actions.len() > 1) - .collect() + claims.into_iter().filter(|(_, actions)| actions.len() > 1).collect() } } @@ -383,11 +282,7 @@ mod tests { for name in letters.chain(digits).chain(functions).chain(named) { let key = key_named(&name).unwrap_or_else(|| panic!("{name} has no key")); assert_eq!(name_of(key).as_deref(), Some(name.as_str())); - assert!(code_of(key).is_some(), "{name}"); } - assert_eq!(code_of(Key::A).as_deref(), Some("KeyA")); - assert_eq!(code_of(Key::Num1).as_deref(), Some("Digit1")); - assert_eq!(code_of(Key::Backtick).as_deref(), Some("Backquote")); } /// The key labelled Q on AZERTY is where A stands on QWERTY: the one pressed is the one @@ -398,11 +293,7 @@ mod tests { let azerty = capture(GLOBAL, (Key::Q, Some(Key::A)), modified(), &bindings); - let heard = if platform::shortcuts::BY_POSITION { - "Ctrl+Alt+A" - } else { - "Ctrl+Alt+Q" - }; + let heard = if platform::shortcuts::BY_POSITION { "Ctrl+Alt+A" } else { "Ctrl+Alt+Q" }; assert_eq!(azerty.as_deref(), Ok(heard)); } @@ -412,12 +303,7 @@ mod tests { fn a_mark_with_no_name_here_is_refused_rather_than_named_after_its_place() { let bindings = Bindings::default(); - let colon = capture( - GLOBAL, - (Key::Colon, Some(Key::Period)), - modified(), - &bindings, - ); + let colon = capture(GLOBAL, (Key::Colon, Some(Key::Period)), modified(), &bindings); if platform::shortcuts::BY_POSITION { assert_eq!(colon.as_deref(), Ok("Ctrl+Alt+Period")); @@ -443,10 +329,7 @@ mod tests { capture(GLOBAL, (Key::J, Some(Key::J)), Modifiers::NONE, &bindings), Err(Refused::NeedsModifier) ); - assert_eq!( - capture(PIN, (Key::J, Some(Key::J)), Modifiers::NONE, &bindings).as_deref(), - Ok("J") - ); + assert_eq!(capture(PIN, (Key::J, Some(Key::J)), Modifiers::NONE, &bindings).as_deref(), Ok("J")); } #[test] @@ -454,10 +337,7 @@ mod tests { let bindings = Bindings::default(); for key in [Key::ArrowLeft, Key::Tab, Key::Escape, Key::Space] { - assert_eq!( - capture(PIN, (key, Some(key)), Modifiers::NONE, &bindings), - Err(Refused::Reserved) - ); + assert_eq!(capture(PIN, (key, Some(key)), Modifiers::NONE, &bindings), Err(Refused::Reserved)); } } @@ -467,13 +347,7 @@ mod tests { let refused = capture(CHECK, (Key::C, Some(Key::C)), Modifiers::NONE, &bindings); - assert_eq!( - refused, - Err(Refused::Taken { - accelerator: "C".to_owned(), - by: ACTIONS[8], - }) - ); + assert_eq!(refused, Err(Refused::Taken { accelerator: "C".to_owned(), by: ACTIONS[8] })); } #[test] @@ -515,4 +389,82 @@ mod tests { assert_eq!(preference_key(GLOBAL), "devnotes.paletteShortcut"); assert_eq!(preference_key(PIN), "devnotes.shortcut.canvas.pin"); } + + #[test] + fn a_keystroke_reads_back_as_it_was_written() { + for (written_key, key, modifiers) in [ + ("P", Key::P, Modifiers::NONE), + ("Ctrl+Alt+P", Key::P, modified()), + ("Ctrl+Alt+Shift+F5", Key::F5, modified() | Modifiers::SHIFT), + (" Ctrl + K ", Key::K, Modifiers::COMMAND), + ("Super+Space", Key::Space, Modifiers::MAC_CMD), + ] { + assert_eq!(parse(written_key), Some((key, modifiers)), "{written_key}"); + } + for unreadable in ["", "Ctrl", "Ctrl+", "Hyper+P", "Ctrl+Nothing", "P+Ctrl", "Ctrl++"] { + assert_eq!(parse(unreadable), None, "{unreadable}"); + } + } + + #[test] + fn modifiers_are_written_in_one_order_and_super_on_a_global_key_alone() { + let all = Modifiers::ALT | Modifiers::SHIFT | Modifiers::CTRL | Modifiers::MAC_CMD; + + assert_eq!(written(all, "P", Scope::Global), "Ctrl+Alt+Shift+Super+P"); + assert_eq!(written(all, "P", Scope::Canvas), "Ctrl+Alt+Shift+P"); + assert_eq!(written(Modifiers::COMMAND, "P", Scope::Areas), "Ctrl+P"); + assert_eq!(written(Modifiers::NONE, "P", Scope::Canvas), "P"); + } + + /// Its own key pressed again is not taken by another. + #[test] + fn an_action_keeps_the_key_it_has() { + let bindings = Bindings::default(); + + assert_eq!(capture(PIN, (Key::P, None), Modifiers::NONE, &bindings).as_deref(), Ok("P")); + } + + #[test] + fn a_key_moved_away_is_free_for_another() { + let mut bindings = Bindings::default(); + bindings.set(PIN, "J".to_owned()); + + assert_eq!(capture(CHECK, (Key::P, None), Modifiers::NONE, &bindings).as_deref(), Ok("P")); + assert!(matches!( + capture(CHECK, (Key::J, None), Modifiers::NONE, &bindings), + Err(Refused::Taken { by, .. }) if by == PIN + )); + } + + /// The navigation's keys are a global key's like any other. + #[test] + fn a_global_key_may_be_one_the_navigation_keeps() { + let bindings = Bindings::default(); + + assert_eq!( + capture(GLOBAL, (Key::ArrowUp, Some(Key::ArrowUp)), modified(), &bindings).as_deref(), + Ok("Ctrl+Alt+ArrowUp") + ); + } + + #[test] + fn a_stored_key_that_does_not_read_answers_on_its_default() { + let mut bindings = Bindings::default(); + bindings.set(PIN, "Hyper+P".to_owned()); + + assert_eq!(bindings.of(PIN), "Hyper+P"); + assert_eq!(bindings.keystroke(PIN), Some((Key::P, Modifiers::NONE))); + bindings.reset(PIN); + assert!(bindings.is_default(PIN)); + } + + #[test] + fn a_key_with_no_name_is_told_from_one_that_starts_like_a_function_key() { + assert_eq!(name_of(Key::F), Some("F".to_owned())); + assert_eq!(name_of(Key::F12), Some("F12".to_owned())); + for key in [Key::Escape, Key::Plus, Key::Colon] { + assert_eq!(name_of(key), None, "{key:?}"); + } + assert_eq!(key_named("Escape"), None, "it could not be written back"); + } } diff --git a/crates/ui/src/services/status.rs b/crates/ui/src/services/status.rs index a8fe8ee5a..195150672 100644 --- a/crates/ui/src/services/status.rs +++ b/crates/ui/src/services/status.rs @@ -47,4 +47,17 @@ mod tests { assert_ne!(status.latest().unwrap().0, first); assert_eq!(status.shown().count(), 2); } + + #[test] + fn the_last_report_is_the_one_not_dismissed() { + let mut status = StatusNotifier::default(); + status.report(Message::new(keys::errors::RETRY)); + status.report(Message::new(keys::errors::DISMISS)); + let (last, _) = status.latest().unwrap(); + + status.dismiss(last); + assert_eq!(status.latest().unwrap().1.key, keys::errors::RETRY); + status.dismiss(status.latest().unwrap().0); + assert!(status.latest().is_none()); + } } diff --git a/crates/ui/src/services/time.rs b/crates/ui/src/services/time.rs index e2eafcad6..f3a52a9f0 100644 --- a/crates/ui/src/services/time.rs +++ b/crates/ui/src/services/time.rs @@ -101,10 +101,7 @@ mod tests { clock.advance(wait); let (label, wait) = relative(at, &clock); - assert_eq!( - label, - Message::new(i18n::keys::time::MINUTES_AGO).with("count", 1.0) - ); + assert_eq!(label, Message::new(i18n::keys::time::MINUTES_AGO).with("count", 1.0)); assert_eq!(wait, Duration::from_mins(1)); } @@ -115,13 +112,29 @@ mod tests { let (label, wait) = relative(at, &clock); - assert_eq!( - label, - Message::new(i18n::keys::time::HOURS_AGO).with("count", 3.0) - ); + assert_eq!(label, Message::new(i18n::keys::time::HOURS_AGO).with("count", 3.0)); // 3 h rounds to 4 h from 3 h 29 min 30 s on. assert_eq!(wait, Duration::from_secs(29 * 60 + 30)); } + + #[test] + fn a_label_of_days_is_drawn_again_within_a_day() { + let clock = FakeClock::at("2026-07-25T09:00:00Z"); + let at: DateTime = "2026-07-15T09:00:00Z".parse().unwrap(); + + let (label, wait) = relative(at, &clock); + assert_eq!(label, Message::new(i18n::keys::time::DAYS_AGO).with("count", 10.0)); + assert!(wait <= Duration::from_hours(24) && wait > Duration::from_hours(11), "{wait:?}"); + } + + /// The clock of another machine, a little ahead. + #[test] + fn what_is_dated_in_the_future_is_now() { + let clock = FakeClock::at(AT); + let at: DateTime = "2026-07-25T09:00:10Z".parse().unwrap(); + + assert_eq!(relative(at, &clock).0.key, i18n::keys::time::JUST_NOW); + } } #[cfg(test)] @@ -149,11 +162,7 @@ mod halves { for seconds in (0..90 * 24 * 3600).step_by(1_337) { let at = now - TimeDelta::seconds(seconds); let label = i18n::time::relative(at, now); - assert_eq!( - until_change(&label, at, now), - walked(&label, at, now), - "{seconds} s ago" - ); + assert_eq!(until_change(&label, at, now), walked(&label, at, now), "{seconds} s ago"); } } } diff --git a/crates/ui/src/services/updates.rs b/crates/ui/src/services/updates.rs index 76bcaffa3..d92ededa7 100644 --- a/crates/ui/src/services/updates.rs +++ b/crates/ui/src/services/updates.rs @@ -103,9 +103,7 @@ impl UpdateState { } pub fn pending(&self) -> Option<&AvailableUpdate> { - self.update - .as_ref() - .filter(|_| self.status != Status::Installed) + self.update.as_ref().filter(|_| self.status != Status::Installed) } /// The offer said on the unlock card and left unanswered: the menu keeps it, no dialog opens. @@ -160,9 +158,7 @@ impl UpdateState { let updater = Arc::clone(&self.updater); let percent = Arc::clone(&self.percent); self.installing = - Some(backend.compute(move |_| { - Ok(updater.download(&|at| percent.store(at, Ordering::Relaxed))) - })); + Some(backend.compute(move |_| Ok(updater.download(&|at| percent.store(at, Ordering::Relaxed))))); } /// `true` once, when the application is to leave for the installer. @@ -232,11 +228,7 @@ impl UpdateState { match answer.unwrap_or_else(|_| Err("the check stopped".to_owned())) { Ok(Some(update)) => { let hushed = silent && is_silenced(&update, settings); - self.status = if hushed { - Status::Idle - } else { - Status::Available - }; + self.status = if hushed { Status::Idle } else { Status::Available }; self.notes = update.notes.as_deref().map(|notes| ChangelogRelease { version: update.version.clone(), date: None, @@ -432,11 +424,7 @@ mod tests { let mut bench = bench(fake); bench.check(true); - assert_eq!( - bench.updates.check_state(), - CheckState::Idle, - "the menu says nothing" - ); + assert_eq!(bench.updates.check_state(), CheckState::Idle, "the menu says nothing"); assert!(bench.errors.notice().is_none()); bench.check(false); @@ -452,10 +440,7 @@ mod tests { bench.updates.install(&bench.backend); assert!(bench.updates.is_busy()); - assert!( - !bench.updates.dismiss(true, &mut bench.settings), - "too late" - ); + assert!(!bench.updates.dismiss(true, &mut bench.settings), "too late"); bench.settle(); assert_eq!(bench.updates.status(), Status::Installed); @@ -512,4 +497,98 @@ mod tests { assert!(bench.errors.notice().is_some()); assert!(!*fake.relaunched.lock().unwrap()); } + + /// « Later » closes the prompt; the menu shows it again without a new check. + #[test] + fn an_offer_put_off_is_shown_again_from_the_menu() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + assert!(!bench.updates.dismiss(false, &mut bench.settings), "nothing to save"); + assert_eq!(bench.settings.skipped_update, ""); + assert!(bench.updates.offered().is_none() && bench.updates.pending().is_some()); + + let asked = bench.backend.launched(); + bench.updates.reopen(); + assert!(bench.updates.offered().is_some()); + assert_eq!(bench.backend.launched(), asked); + } + + #[test] + fn with_nothing_found_there_is_nothing_to_show_again_nor_to_install() { + let mut bench = bench(Arc::new(FakeUpdater::default())); + bench.check(true); + + bench.updates.reopen(); + bench.updates.install(&bench.backend); + assert_eq!(bench.updates.status(), Status::Idle); + } + + #[test] + fn an_offer_said_on_the_unlock_card_opens_no_prompt_after_it() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + + bench.updates.put_away(); + assert_eq!(bench.updates.status(), Status::Idle); + assert!(bench.updates.has_pending()); + + bench.updates.reopen(); + bench.updates.install(&bench.backend); + bench.updates.put_away(); + assert_eq!(bench.updates.status(), Status::Installing, "too late"); + } + + #[test] + fn what_a_check_found_is_forgotten_with_the_menu_and_one_under_way_is_not() { + let mut bench = bench(Arc::new(FakeUpdater::default())); + bench.check(false); + bench.updates.forget_check(); + assert_eq!(bench.updates.check_state(), CheckState::Idle); + + bench.updates.check(&bench.backend, false); + bench.updates.forget_check(); + assert_eq!(bench.updates.check_state(), CheckState::Checking); + } + + #[test] + fn one_check_at_a_time_and_none_over_an_offer() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + let before = bench.backend.launched(); + bench.updates.check(&bench.backend, true); + bench.updates.check(&bench.backend, true); + assert_eq!(bench.backend.launched(), before + 1); + bench.settle(); + + bench.updates.check(&bench.backend, false); + assert_eq!(bench.backend.launched(), before + 1); + } + + #[test] + fn no_percent_is_known_before_the_server_says_a_size() { + let mut bench = bench(FakeUpdater::offering("0.26.0")); + bench.check(true); + assert_eq!(bench.updates.progress(), None); + + bench.updates.install(&bench.backend); + bench.settle(); + assert_eq!(bench.updates.progress(), Some(50)); + } + + #[test] + fn a_failed_install_says_what_to_do_and_can_be_tried_again() { + let fake = FakeUpdater::offering("0.26.0"); + let mut bench = bench(Arc::clone(&fake)); + bench.check(true); + *fake.fails.lock().unwrap() = true; + bench.updates.install(&bench.backend); + bench.settle(); + let said = bench.errors.notice().unwrap().text(i18n::Language::En); + assert!(said.contains(METADATA.name), "{said}"); + + *fake.fails.lock().unwrap() = false; + bench.updates.install(&bench.backend); + assert_eq!(bench.updates.progress(), None, "from the start"); + bench.settle(); + assert_eq!(bench.updates.status(), Status::Installed); + } } diff --git a/crates/ui/src/state/apply_http.rs b/crates/ui/src/state/apply_http.rs index b4fcc4099..9d68c4674 100644 --- a/crates/ui/src/state/apply_http.rs +++ b/crates/ui/src/state/apply_http.rs @@ -5,12 +5,7 @@ use crate::api; use crate::backend::Backend; impl AppState { - pub(super) fn apply_http( - &mut self, - action: crate::http::Action, - ctx: &egui::Context, - backend: &Backend, - ) { + pub(super) fn apply_http(&mut self, action: crate::http::Action, ctx: &egui::Context, backend: &Backend) { use crate::http::Action as Http; let now = ctx.input(|input| input.time); match action { @@ -44,9 +39,8 @@ impl AppState { Http::AddExtraction { key, rule } => { let variable = rule.variable.clone(); self.http.add_extraction(&key, rule); - self.status.report( - i18n::Message::new(i18n::keys::http::extract::ADDED).with("variable", variable), - ); + self.status + .report(i18n::Message::new(i18n::keys::http::extract::ADDED).with("variable", variable)); } Http::ChooseEnvironment(id) => self.http.choose_environment(id), Http::Environments(asked) => self.http.ask_environments(backend, asked, now), @@ -58,9 +52,7 @@ impl AppState { Http::ToggleConsole => self.http.toggle_console(), Http::ClearConsole(key) => self.http.clear_console(&key), Http::SaveResponseFile { send_id, name } => { - self.http - .kept_mut() - .save_file(backend, &self.dialog, send_id, name); + self.http.kept_mut().save_file(backend, &self.dialog, send_id, name); } Http::AskResponseNote(asked) => { self.http.kept_mut().ask_response_note(backend, *asked); @@ -70,8 +62,7 @@ impl AppState { Http::CancelNote => self.http.kept_mut().cancel_note(), Http::OpenScript { key, stop } => self.http.open_script(backend, key, &stop), Http::OpenLevel { origin, phase } => { - self.http - .open_settings_of(backend, &origin.id, (phase, None)); + self.http.open_settings_of(backend, &origin.id, (phase, None)); } Http::ScriptFocusTaken => self.http.script_focus_taken(), Http::SendMessage { key, text } => self.http.send_message(backend, &key, text), @@ -115,8 +106,7 @@ impl AppState { pub(super) fn update_http(&mut self, ctx: &egui::Context, backend: &Backend, time: f64) { self.http.update((ctx, backend), time, &mut self.errors); let tz_offset = notes_query::tz_offset_minutes(self.clock.now()); - self.http - .update_history((ctx, backend), (time, tz_offset), &mut self.errors); + self.http.update_history((ctx, backend), (time, tz_offset), &mut self.errors); self.report_kept(); if let Some(count) = self.http.take_history_cleared() { let cleared = i18n::Message::new(i18n::keys::http::history::CLEARED); @@ -142,10 +132,7 @@ impl AppState { pub(super) fn remember_http(&mut self, backend: &Backend) { if self.http.remember(&mut self.library_preferences) { - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } } } diff --git a/crates/ui/src/state/apply_notes.rs b/crates/ui/src/state/apply_notes.rs index 3c7afe8a7..29f333876 100644 --- a/crates/ui/src/state/apply_notes.rs +++ b/crates/ui/src/state/apply_notes.rs @@ -1,8 +1,8 @@ //! What the notes ask: the canvas and the board, folders, the editor and its overlays. use super::{ - AppState, EditorNext, PREVIEW_LINES_KEY, attachments, board, drawing_pictures, editor, - placeholder_fill, put_away, + AppState, EditorNext, PREVIEW_LINES_KEY, attachments, board, drawing_pictures, editor, placeholder_fill, + put_away, }; use crate::api; use crate::backend::Backend; @@ -21,10 +21,7 @@ impl AppState { if root_id.is_some_and(|root| !self.folders.has_children(root)) { return None; } - Some(board::Place { - space_id: space_id.to_owned(), - root_id: root_id.map(str::to_owned), - }) + Some(board::Place { space_id: space_id.to_owned(), root_id: root_id.map(str::to_owned) }) } /// On the board on screen: a gesture's result is staged and written behind the debounce. @@ -40,25 +37,17 @@ impl AppState { }; let now = ctx.input(|input| input.time); match gesture { - BoardGesture::DropCard { - note_id, - folder, - at, - } => self.board.drop_card( - backend, - &place, - (note_id, folder), - (at, now), - self.preview_lines, - ), + BoardGesture::DropCard { note_id, folder, at } => { + self.board + .drop_card(backend, &place, (note_id, folder), (at, now), self.preview_lines); + } BoardGesture::MoveZone { folder_id, frame } => { self.board.move_zone(&place, folder_id, frame, now); } BoardGesture::DrawZone(frame) => self.board.propose_zone(frame), BoardGesture::Band(ids) => self.selection.check_all(ids), BoardGesture::FileOnRail { note_id, folder } => { - self.notes - .file(backend, (vec![note_id], folder), self.preview_lines); + self.notes.file(backend, (vec![note_id], folder), self.preview_lines); } BoardGesture::SelectFolder(id) => { let held: Vec = self @@ -77,17 +66,13 @@ impl AppState { /// The board on screen put back in order; nothing while the list shows. pub(super) fn tidy(&mut self, backend: &Backend, scope: engine::folders::board::BoardScope) { if let Some(place) = self.board_place() { - self.board - .arrange(backend, &place, scope, self.preview_lines); + self.board.arrange(backend, &place, scope, self.preview_lines); } } /// The last write put back; an arrangement taken back pans the ground back to where it was. pub(super) fn revert_last(&mut self, backend: &Backend) { - if matches!( - self.undo.last(), - Some(api::undo::Reversible::Arrangement { .. }) - ) { + if matches!(self.undo.last(), Some(api::undo::Reversible::Arrangement { .. })) { self.board.restored(); } self.undo.revert(backend, self.preview_lines); @@ -123,9 +108,7 @@ impl AppState { } let lineage = Lineage::of(self.folders.list()); let allowed = if crossing { - lineage - .check_arrival(parent.as_deref(), lineage.height(&id).max(1)) - .is_ok() + lineage.check_arrival(parent.as_deref(), lineage.height(&id).max(1)).is_ok() } else { lineage.check_move(&id, parent.as_deref()).is_ok() }; @@ -144,8 +127,7 @@ impl AppState { .map(|other| other.name.clone()), None => None, }; - self.folders - .move_folder(backend, id, (space, parent), (name, into)); + self.folders.move_folder(backend, id, (space, parent), (name, into)); } /// The rail's keyboard twin of a drag: up a level, or into the sibling above it. @@ -160,24 +142,17 @@ impl AppState { self.status.report(refused(refused::AT_TOP)); return; }; - self.folders - .find(parent) - .and_then(|parent| parent.parent_id.clone()) + self.folders.find(parent).and_then(|parent| parent.parent_id.clone()) } else { let mut siblings: Vec<_> = self .folders .list() .iter() - .filter(|other| { - other.space_id == folder.space_id && other.parent_id == folder.parent_id - }) + .filter(|other| other.space_id == folder.space_id && other.parent_id == folder.parent_id) .collect(); siblings.sort_by_key(|other| api::folders::sort_key(&other.name)); let at = siblings.iter().position(|other| other.id == folder.id); - let Some(above) = at - .and_then(|at| at.checked_sub(1)) - .map(|above| siblings[above]) - else { + let Some(above) = at.and_then(|at| at.checked_sub(1)).map(|above| siblings[above]) else { self.status.report(refused(refused::NO_FOLDER_ABOVE)); return; }; @@ -211,10 +186,7 @@ impl AppState { return; }; mode.write(&mut self.library_preferences, space_id); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } /// The bodies kept beside the note open — none for a draft or a todo list — and a body put @@ -226,10 +198,7 @@ impl AppState { .and_then(|open| open.note().map(|note| (open.id(), note.kind))) .and_then(|(id, kind)| id.filter(|_| kind != engine::notes::kind::NoteKind::Checklist)); self.revisions.follow(kept); - if let Some(id) = self - .revisions - .update(backend, &mut self.revision, &mut self.errors) - { + if let Some(id) = self.revisions.update(backend, &mut self.revision, &mut self.errors) { self.editor.reseed_when_read(&id); } } @@ -245,9 +214,7 @@ impl AppState { return; } self.drawing_choices.want(self.revision); - let answered = self - .drawing_choices - .update(|_| api::notes::list_drawings(backend)); + let answered = self.drawing_choices.update(|_| api::notes::list_drawings(backend)); if answered && let Some(error) = self.drawing_choices.error() { log::warn!("The drawings were not listed: {error:?}"); } @@ -272,10 +239,7 @@ impl AppState { pub(super) fn remember_place(&mut self, backend: &Backend) { self.spaces.remember(&mut self.library_preferences); self.folders.remember(&mut self.library_preferences); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } /// The spaces and the folders: chosen, made, renamed, deleted. @@ -301,11 +265,9 @@ impl AppState { Notes::DeleteSpace { id, refuge, held } => { self.spaces.delete_space(backend, id, refuge, held); } - Notes::CreateFolder { - space_id, - parent_id, - name, - } => self.folders.create(backend, space_id, parent_id, &name), + Notes::CreateFolder { space_id, parent_id, name } => { + self.folders.create(backend, space_id, parent_id, &name); + } Notes::RenameFolder { id, name } => self.folders.rename(backend, id, &name), Notes::RecolourFolder { id, colour } => self.folders.recolour(backend, id, colour), Notes::CountFolder(id) => self.folders.count(id), @@ -345,8 +307,7 @@ impl AppState { } } Notes::Trash(asked) => { - self.trash - .apply(asked, backend, ctx.input(|input| input.time)); + self.trash.apply(asked, backend, ctx.input(|input| input.time)); } _ => {} } @@ -398,10 +359,7 @@ impl AppState { Notes::Arrange(arrangement) => { self.notes_query.arrange(arrangement); arrangement.write(&mut self.library_preferences); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } Notes::OpenNote(id) => self.open_in_editor(EditorNext::Note(id)), Notes::Editor(editing) => self.apply_editing(editing, ctx, backend), @@ -469,27 +427,18 @@ impl AppState { let today = self.clock.now().with_timezone(&chrono::Local).date_naive(); self.calc.ask(backend, session, text, today); } - Editing::Pictures { - session, - content, - palette, - missing, - } => self - .editor - .picture(backend, session, (content, palette), missing), + Editing::Pictures { session, content, palette, missing } => { + self.editor.picture(backend, session, (content, palette), missing); + } Editing::Pin(pinned) => { - if !self - .editor - .change_draft(backend, |note| note.pinned = pinned) + if !self.editor.change_draft(backend, |note| note.pinned = pinned) && let Some(id) = id { self.notes.pin(backend, vec![id], pinned); } } Editing::Prioritise(priority) => { - if !self - .editor - .change_draft(backend, |note| note.priority = priority) + if !self.editor.change_draft(backend, |note| note.priority = priority) && let Some(id) = id { self.notes.prioritise(backend, vec![id], priority); @@ -507,20 +456,14 @@ impl AppState { } Editing::File(folder) => { let into = folder.clone(); - if !self - .editor - .change_draft(backend, |note| note.folder_id = into) + if !self.editor.change_draft(backend, |note| note.folder_id = into) && let Some(id) = id { let to = folder.map_or(Destination::NoFolder, Destination::Folder); self.move_notes(vec![id], to, backend); } } - Editing::Convert { - session, - into, - edit, - } => { + Editing::Convert { session, into, edit } => { self.editor.save(backend, session, edit); match id { Some(id) => self.notes.convert(backend, id, into), @@ -557,11 +500,7 @@ impl AppState { } /// A display preference of the editor, kept from note to note. - pub(super) fn set_editor_display( - &mut self, - display: &crate::notes::Editing, - backend: &Backend, - ) { + pub(super) fn set_editor_display(&mut self, display: &crate::notes::Editing, backend: &Backend) { use crate::notes::Editing; match *display { Editing::Fullscreen(on) => self.settings.editor_fullscreen = on, @@ -574,8 +513,7 @@ impl AppState { pub(super) fn ask_attachment(&mut self, asked: attachments::Asked, backend: &Backend) { let moment = self.clock.now().format("capture-%Y-%m-%d-%H-%M-%S"); - self.attachments - .ask(asked, backend, &self.dialog, moment.to_string()); + self.attachments.ask(asked, backend, &self.dialog, moment.to_string()); } pub(super) fn apply_fields( @@ -591,11 +529,9 @@ impl AppState { self.fill.keep(backend, id.to_owned(), values); } } - Fields::Preview { - session, - content, - values, - } => self.fill.ask_preview(backend, session, content, values), + Fields::Preview { session, content, values } => { + self.fill.ask_preview(backend, session, content, values); + } Fields::Copy { content, values } => self.fill.copy(backend, content, values), Fields::CopyRaw(text) => { let note = self.editor.opened().and_then(|open| open.note()); @@ -614,15 +550,11 @@ impl AppState { /// while it shows — a card the search dims there is still on screen and still selectable. pub fn on_screen(&self) -> Vec { if self.board_place().is_some() { - return self - .board - .cards() - .map(|entry| entry.note.id.clone()) - .collect(); + return self.board.cards().map(|entry| entry.note.id.clone()).collect(); } - self.notes_query.view().map_or_else(Vec::new, |view| { - view.cards().map(|card| card.id.clone()).collect() - }) + self.notes_query + .view() + .map_or_else(Vec::new, |view| view.cards().map(|card| card.id.clone()).collect()) } pub(super) fn pinned_on_screen(&self, id: &str) -> Option { @@ -634,9 +566,7 @@ impl AppState { .map(|entry| entry.note.pinned); } let view = self.notes_query.view()?; - view.cards() - .find(|card| card.id == id) - .map(|card| card.pinned) + view.cards().find(|card| card.id == id).map(|card| card.pinned) } fn move_notes(&mut self, ids: Vec, to: Destination, backend: &Backend) { @@ -694,17 +624,9 @@ impl AppState { } else { return; }; - let columns = if board { - 1 - } else { - self.notes_view.canvas.columns - }; - let to = crate::notes::canvas::grid::neighbour( - §ions, - columns, - focused.as_deref(), - direction, - ); + let columns = if board { 1 } else { self.notes_view.canvas.columns }; + let to = + crate::notes::canvas::grid::neighbour(§ions, columns, focused.as_deref(), direction); if let Some(to) = to { self.notes_view.canvas.request = Some(to.to_owned()); ctx.request_repaint(); @@ -785,8 +707,7 @@ impl AppState { note: engine::notes::model::DisplayNote, ) { if note.kind == engine::notes::kind::NoteKind::Drawing { - self.status - .report(i18n::Message::new(i18n::keys::notes::DRAWING_NOT_COPIED)); + self.status.report(i18n::Message::new(i18n::keys::notes::DRAWING_NOT_COPIED)); return; } if !note.placeholders.is_empty() { @@ -798,10 +719,7 @@ impl AppState { self.calc.copy(backend, note, today); return; } - let text = note - .copy_text - .clone() - .unwrap_or_else(|| note.content.clone()); + let text = note.copy_text.clone().unwrap_or_else(|| note.content.clone()); self.copy_out(ctx, backend, text, placeholder_fill::copied_note(¬e)); } @@ -817,7 +735,7 @@ impl AppState { ) { ctx.copy_text(text); let from_palette = self.palette.copied(); - let from_elsewhere = from_palette && self.palette.from_elsewhere(); + let from_elsewhere = from_palette && self.palette.is_from_elsewhere(); if from_palette { self.palette.close(); } @@ -921,13 +839,8 @@ impl AppState { return; }; let language = crate::api::notes::detect_language(&content); - let kind = if language == Language::Txt { - NoteKind::Note - } else { - NoteKind::Snippet - }; - self.editor - .draft_filled(backend, (kind, space, folder), content, language); + let kind = if language == Language::Txt { NoteKind::Note } else { NoteKind::Snippet }; + self.editor.draft_filled(backend, (kind, space, folder), content, language); } /// Where a new note goes: the space and folder shown, or the first space for « all »; said @@ -939,8 +852,7 @@ impl AppState { .map(str::to_owned) .or_else(|| self.spaces.spaces().first().map(|space| space.id.clone())); let Some(space) = space else { - self.errors - .notify(i18n::Message::new(i18n::keys::errors::SPACE_REQUIRED)); + self.errors.notify(i18n::Message::new(i18n::keys::errors::SPACE_REQUIRED)); return None; }; Some((space, self.active_folder().map(str::to_owned))) @@ -961,12 +873,8 @@ impl AppState { /// pixels, so their height must be the library's too. pub(super) fn set_preview_lines(&mut self, lines: PreviewLines, backend: &Backend) { self.preview_lines = lines; - self.library_preferences - .set(PREVIEW_LINES_KEY, lines.as_str()); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + self.library_preferences.set(PREVIEW_LINES_KEY, lines.as_str()); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } pub(super) fn set_prettier( @@ -975,42 +883,31 @@ impl AppState { backend: &Backend, ) { self.prettier = settings; - self.library_preferences - .set(crate::notes::prettier::KEY, &settings.written()); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + self.library_preferences.set(crate::notes::prettier::KEY, &settings.written()); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); } /// Formatted first when the library asks for it: the body is held back and written once, /// formatted or, refused, as it was typed. A draft never written is saved as it is. - pub(super) fn save_formatted( - &mut self, - backend: &Backend, - session: u64, - mut edit: editor::Edit, - ) { + pub(super) fn save_formatted(&mut self, backend: &Backend, session: u64, mut edit: editor::Edit) { let note = self.editor.opened().and_then(editor::Opened::note); - let asked = note - .filter(|_| self.prettier.format_on_save) - .and_then(|note| { - let parser = crate::notes::language::formatter(note.language)?; - let Some(editor::Body::Content(text)) = &edit.body else { - return None; + let asked = note.filter(|_| self.prettier.format_on_save).and_then(|note| { + let parser = crate::notes::language::formatter(note.language)?; + let Some(editor::Body::Content(text)) = &edit.body else { + return None; + }; + let changed = *text != note.content && !note.id.is_empty(); + changed.then(|| { + let indent = self.settings.code_indent.unit(note.language); + let request = text::format::Request { + text: text.clone(), + cursor: 0, + parser, + options: self.prettier.options(indent), }; - let changed = *text != note.content && !note.id.is_empty(); - changed.then(|| { - let indent = self.settings.code_indent.unit(note.language); - let request = text::format::Request { - text: text.clone(), - cursor: 0, - parser, - options: self.prettier.options(indent), - }; - (note.id.clone(), request) - }) - }); + (note.id.clone(), request) + }) + }); if let Some((id, request)) = asked { edit.body = None; self.formatting.save(backend, session, id, request); diff --git a/crates/ui/src/state/apply_window.rs b/crates/ui/src/state/apply_window.rs index dd69878da..dc8437290 100644 --- a/crates/ui/src/state/apply_window.rs +++ b/crates/ui/src/state/apply_window.rs @@ -21,8 +21,7 @@ impl AppState { Menu::ExportAll => self.transfer.export(backend, ExportScope::Library), Menu::ExportSpace => { if let Some(space_id) = self.spaces.active_space().map(str::to_owned) { - self.transfer - .export(backend, ExportScope::Space { space_id }); + self.transfer.export(backend, ExportScope::Space { space_id }); } } Menu::ExportSelection => { @@ -46,8 +45,7 @@ impl AppState { Menu::OpenLibraries => { self.libraries.load(backend); let opener = self.titlebar_view.file_anchor; - self.dialogs - .open(Layer::Settings, crate::titlebar::libraries::id(), opener); + self.dialogs.open(Layer::Settings, crate::titlebar::libraries::id(), opener); } Menu::Libraries(asked) => self.apply_libraries(asked, ctx, backend), Menu::OpenPreferences => { @@ -55,8 +53,7 @@ impl AppState { self.security.load_variables(backend); self.backups.load(backend); let opener = self.titlebar_view.file_anchor; - self.dialogs - .open(Layer::Settings, crate::titlebar::preferences::id(), opener); + self.dialogs.open(Layer::Settings, crate::titlebar::preferences::id(), opener); } Menu::Preferences(asked) => self.apply_preferences(asked, ctx, backend), Menu::OpenHelp(panel) => { @@ -65,8 +62,7 @@ impl AppState { } self.titlebar_view.show_help(panel); let opener = self.titlebar_view.about_anchor(); - self.dialogs - .open(Layer::App, crate::titlebar::about_menu::id(), opener); + self.dialogs.open(Layer::App, crate::titlebar::about_menu::id(), opener); } Menu::CloseHelp => { self.titlebar_view.close_help(); @@ -81,22 +77,14 @@ impl AppState { } } - pub(super) fn apply_update( - &mut self, - asked: crate::banners::update_prompt::Ask, - backend: &Backend, - ) { + pub(super) fn apply_update(&mut self, asked: crate::banners::update_prompt::Ask, backend: &Backend) { use crate::banners::update_prompt::Ask; match asked { Ask::Check => self.updates.check(backend, false), Ask::Reopen => self.updates.reopen(), Ask::ForgetCheck => self.updates.forget_check(), Ask::Install => { - self.ask_switch( - libraries::Goal::Install, - http::leave::Reason::Update, - backend, - ); + self.ask_switch(libraries::Goal::Install, http::leave::Reason::Update, backend); } Ask::Later { skip } => { if self.updates.dismiss(skip, &mut self.settings) { @@ -150,8 +138,7 @@ impl AppState { Ask::KeepPassphrase => { self.titlebar_view.take_phrases(); self.security.clear_refusal(); - self.dialogs - .close(ctx, crate::titlebar::preferences::change_id()); + self.dialogs.close(ctx, crate::titlebar::preferences::change_id()); } } } @@ -167,10 +154,7 @@ impl AppState { if let Some(lines) = self.titlebar_view.adopt_preview_lines(self.preview_lines) { self.set_preview_lines(lines, backend); } - if let Some(rows) = self - .titlebar_view - .adopt_variables(self.security.variables()) - { + if let Some(rows) = self.titlebar_view.adopt_variables(self.security.variables()) { self.security.save_variables(backend, rows); self.revision.bump(); } @@ -228,8 +212,7 @@ impl AppState { match goal { libraries::Goal::Open(id) => self.gate.leave_for(api::libraries::open(backend, id)), libraries::Goal::Create(name) => { - self.gate - .leave_for(api::libraries::create_and_open(backend, name)); + self.gate.leave_for(api::libraries::create_and_open(backend, name)); } libraries::Goal::Restore(id) => { self.gate.leave_for_copy(api::backups::restore(backend, id)); @@ -315,8 +298,7 @@ impl AppState { Chosen::Create(title) => { if let Some(place) = self.new_place() { let kind = engine::notes::kind::NoteKind::Snippet; - self.editor - .draft_titled(backend, (kind, place.0, place.1), title); + self.editor.draft_titled(backend, (kind, place.0, place.1), title); } } } diff --git a/crates/ui/src/state/attachments.rs b/crates/ui/src/state/attachments.rs index 5e51068c2..3f4c7688e 100644 --- a/crates/ui/src/state/attachments.rs +++ b/crates/ui/src/state/attachments.rs @@ -139,14 +139,11 @@ impl AttachmentsState { match asked { Asked::Pick => { let dialog = Arc::clone(dialog); - self.picking - .push(backend.compute(move |_| Ok(dialog.open()))); + self.picking.push(backend.compute(move |_| Ok(dialog.open()))); } Asked::Dropped(paths) => self.queue.extend(paths.into_iter().map(ToAttach::File)), Asked::Pasted(image) => self.queue.push_back(ToAttach::Image(pasted_name, image)), - Asked::Open(id) => self - .opening - .push(api::attachments::decrypted_copy(backend, id)), + Asked::Open(id) => self.opening.push(api::attachments::decrypted_copy(backend, id)), Asked::Save(id) => self.save(backend, dialog, id), Asked::Remove(id) => { let removal = api::attachments::delete(backend, id.clone()); @@ -175,10 +172,7 @@ impl AttachmentsState { return; } let reading = api::attachments::read(backend, id.clone()); - self.preview = Some(Preview { - id, - image: Image::Reading(reading), - }); + self.preview = Some(Preview { id, image: Image::Reading(reading) }); } /// Once a frame. `note` is the note open, by id; another one clears the image shown: the @@ -227,9 +221,7 @@ impl AttachmentsState { self.reading = None; match answer { Ok(list) => self.list = list, - Err(error) => reports - .errors - .report(keys::errors::ATTACHMENTS_LOAD_FAILED, &error), + Err(error) => reports.errors.report(keys::errors::ATTACHMENTS_LOAD_FAILED, &error), } } @@ -272,8 +264,7 @@ impl AttachmentsState { Ok(added) => { self.load(backend); reports.revision.bump(); - let said = - Message::new(keys::attachments::ADDED).with("name", added.file_name.as_str()); + let said = Message::new(keys::attachments::ADDED).with("name", added.file_name.as_str()); reports.status.report(said); if is_shown(&added) { self.toggle_preview(backend, added.id); @@ -291,9 +282,7 @@ impl AttachmentsState { }; match answer { Ok(()) => removed.push(std::mem::take(id)), - Err(error) => reports - .errors - .report(keys::errors::ATTACHMENT_DELETE_FAILED, &error), + Err(error) => reports.errors.report(keys::errors::ATTACHMENT_DELETE_FAILED, &error), } false }); @@ -319,9 +308,7 @@ impl AttachmentsState { self.saving.push(Saving::Writing(path, writing)); } Some(Ok(None)) => {} - Some(Err(error)) => reports - .errors - .report(keys::errors::ATTACHMENT_SAVE_FAILED, &error), + Some(Err(error)) => reports.errors.report(keys::errors::ATTACHMENT_SAVE_FAILED, &error), }, Saving::Writing(path, mut writing) => match writing.poll() { None => self.saving.push(Saving::Writing(path, writing)), @@ -329,9 +316,7 @@ impl AttachmentsState { let said = Message::new(keys::attachments::SAVED).with("path", path); reports.status.report(said); } - Some(Err(error)) => reports - .errors - .report(keys::errors::ATTACHMENT_SAVE_FAILED, &error), + Some(Err(error)) => reports.errors.report(keys::errors::ATTACHMENT_SAVE_FAILED, &error), }, } } @@ -345,14 +330,10 @@ impl AttachmentsState { match answer { Ok(path) => { if opener.open(&path).is_err() { - reports - .errors - .notify(Message::new(keys::errors::ATTACHMENT_OPEN_FAILED)); + reports.errors.notify(Message::new(keys::errors::ATTACHMENT_OPEN_FAILED)); } } - Err(error) => reports - .errors - .report(keys::errors::ATTACHMENT_OPEN_FAILED, &error), + Err(error) => reports.errors.report(keys::errors::ATTACHMENT_OPEN_FAILED, &error), } false }); @@ -370,9 +351,7 @@ impl AttachmentsState { preview.image = Image::Decoding(decoding); } Some(Err(error)) => { - reports - .errors - .report(keys::errors::ATTACHMENT_READ_FAILED, &error); + reports.errors.report(keys::errors::ATTACHMENT_READ_FAILED, &error); self.preview = None; } }, @@ -404,10 +383,7 @@ fn picture(mime: &str, bytes: &[u8]) -> Option { return decode_svg(bytes); } let image = image::load_from_memory(bytes).ok()?.into_rgba8(); - let size = [ - usize::try_from(image.width()).ok()?, - usize::try_from(image.height()).ok()?, - ]; + let size = [usize::try_from(image.width()).ok()?, usize::try_from(image.height()).ok()?]; Some(ColorImage::from_rgba_unmultiplied(size, image.as_raw())) } @@ -420,15 +396,8 @@ fn decode_svg(bytes: &[u8]) -> Option { let scale = (LARGEST_SIDE / declared.width().max(declared.height())).min(1.0); let size = declared.scale_by(scale)?.to_int_size(); let mut pixmap = resvg::tiny_skia::Pixmap::new(size.width(), size.height())?; - resvg::render( - &tree, - resvg::tiny_skia::Transform::from_scale(scale, scale), - &mut pixmap.as_mut(), - ); - let size = [ - usize::try_from(pixmap.width()).ok()?, - usize::try_from(pixmap.height()).ok()?, - ]; + resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut()); + let size = [usize::try_from(pixmap.width()).ok()?, usize::try_from(pixmap.height()).ok()?]; Some(ColorImage::from_rgba_premultiplied(size, pixmap.data())) } @@ -447,7 +416,8 @@ mod tests { use super::*; - const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + const PNG: &str = + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; fn attachment(mime: &str) -> Attachment { Attachment { diff --git a/crates/ui/src/state/backups.rs b/crates/ui/src/state/backups.rs index 625fc6e63..47b7d3522 100644 --- a/crates/ui/src/state/backups.rs +++ b/crates/ui/src/state/backups.rs @@ -36,10 +36,7 @@ impl BackupsState { /// Proposes only. A copy with no key file opens for nobody and is never offered. pub fn ask(&mut self, id: String) { - let openable = self - .copies - .iter() - .any(|copy| copy.id == id && copy.openable); + let openable = self.copies.iter().any(|copy| copy.id == id && copy.openable); if openable { self.pending = Some(id); } @@ -69,12 +66,7 @@ mod tests { use crate::testing; fn copy(id: &str, openable: bool) -> Backup { - Backup { - id: id.to_owned(), - taken_at: Utc::now(), - bytes: 1024, - openable, - } + Backup { id: id.to_owned(), taken_at: Utc::now(), bytes: 1024, openable } } #[test] diff --git a/crates/ui/src/state/board.rs b/crates/ui/src/state/board.rs index 0badcabfc..96a1a8983 100644 --- a/crates/ui/src/state/board.rs +++ b/crates/ui/src/state/board.rs @@ -9,8 +9,8 @@ use std::time::Duration; use chrono::{DateTime, Local, NaiveDate, Utc}; use engine::error::AppError; use engine::folders::board::{ - BoardArrangement, BoardFrame, BoardNote, BoardPoint, BoardQuery, BoardScope, BoardView, - BoardZone, CardPlacement, PreviewLines, ZonePlacement, + BoardArrangement, BoardFrame, BoardNote, BoardPoint, BoardQuery, BoardScope, BoardView, BoardZone, + CardPlacement, PreviewLines, ZonePlacement, }; use engine::folders::model::Folder; use i18n::{Message, keys}; @@ -131,9 +131,7 @@ impl BoardState { day: now.with_timezone(&Local).date_naive(), revision, }); - let changed = self - .cell - .update(|params| api::board::view(backend, query(params, now))); + let changed = self.cell.update(|params| api::board::view(backend, query(params, now))); if changed && let Some(view) = self.cell.value() { release(&mut self.staged, view); let held = membership(view); @@ -165,9 +163,7 @@ impl BoardState { /// Where the card sits once the drops have had their say: a zone, or `None` for the ground. pub fn sitting_in<'a>(&'a self, note_id: &str, in_view: Option<&'a str>) -> Option<&'a str> { - self.filing - .get(note_id) - .map_or(in_view, |folder| folder.as_deref()) + self.filing.get(note_id).map_or(in_view, |folder| folder.as_deref()) } /// A band drawn on the ground, held until it is named. @@ -191,18 +187,9 @@ impl BoardState { if name.is_empty() { return; } - let pending = api::folders::create( - backend, - place.space_id.clone(), - place.root_id.clone(), - name.to_owned(), - ); - self.making = Some(Making { - root_id: place.root_id.clone(), - frame, - name: name.to_owned(), - pending, - }); + let pending = + api::folders::create(backend, place.space_id.clone(), place.root_id.clone(), name.to_owned()); + self.making = Some(Making { root_id: place.root_id.clone(), frame, name: name.to_owned(), pending }); } /// Once a frame, shown or not: the staged layout written once its time comes, the answers @@ -247,11 +234,7 @@ impl BoardState { self.staged = Staged::default(); self.arrangements += 1; revision.bump(); - Some(Reversible::Arrangement { - root_id, - previous: done.previous, - moved: done.moved, - }) + Some(Reversible::Arrangement { root_id, previous: done.previous, moved: done.moved }) } Err(error) => { errors.report(keys::errors::BOARD_ARRANGE_FAILED, &error); @@ -262,58 +245,39 @@ impl BoardState { fn adopt_drops(&mut self, revision: &mut Revision, errors: &mut ErrorNotifier) { let filing = &mut self.filing; - self.filings - .retain_mut(|(note_id, pending)| match pending.poll() { - None => true, - Some(Ok(_)) => { - revision.bump(); - false - } - Some(Err(error)) => { - filing.remove(note_id.as_str()); - errors.report(keys::errors::FILE_FAILED, &error); - false - } - }); + self.filings.retain_mut(|(note_id, pending)| match pending.poll() { + None => true, + Some(Ok(_)) => { + revision.bump(); + false + } + Some(Err(error)) => { + filing.remove(note_id.as_str()); + errors.report(keys::errors::FILE_FAILED, &error); + false + } + }); } /// The folder made, its frame written straight through: a frame staged for a folder the /// next view has only just heard of would be let go of. - fn adopt_made( - &mut self, - backend: &Backend, - revision: &mut Revision, - errors: &mut ErrorNotifier, - ) { + fn adopt_made(&mut self, backend: &Backend, revision: &mut Revision, errors: &mut ErrorNotifier) { let Some(making) = &mut self.making else { return; }; let Some(answer) = making.pending.poll() else { return; }; - let Making { - root_id, - frame, - name, - .. - } = self.making.take().expect("polled just above"); + let Making { root_id, frame, name, .. } = self.making.take().expect("polled just above"); match answer { Ok(folder) => { - let zone = ZonePlacement { - folder_id: folder.id, - frame, - }; - self.saving.push(api::board::save_layout( - backend, - root_id, - vec![zone], - Vec::new(), - )); + let zone = ZonePlacement { folder_id: folder.id, frame }; + self.saving + .push(api::board::save_layout(backend, root_id, vec![zone], Vec::new())); revision.bump(); } Err(error) => { - let failed = - Message::new(keys::errors::FOLDER_CREATE_FAILED).with("name", name.as_str()); + let failed = Message::new(keys::errors::FOLDER_CREATE_FAILED).with("name", name.as_str()); errors.report_message(failed, &error); } } @@ -331,30 +295,16 @@ impl BoardState { fn stage(&mut self, place: &Place, now: f64) -> &mut Staged { if self.staged.root_id != place.root_id { - self.staged = Staged { - root_id: place.root_id.clone(), - ..Staged::default() - }; + self.staged = Staged { root_id: place.root_id.clone(), ..Staged::default() }; } self.staged.due = Some(now + f64::from(crate::theme::motion::LAYOUT_SAVE)); &mut self.staged } /// The board on screen put back in order, as far as `scope` allows. - pub fn arrange( - &mut self, - backend: &Backend, - place: &Place, - scope: BoardScope, - lines: PreviewLines, - ) { - let pending = api::board::arrange( - backend, - place.space_id.clone(), - place.root_id.clone(), - scope, - lines, - ); + pub fn arrange(&mut self, backend: &Backend, place: &Place, scope: BoardScope, lines: PreviewLines) { + let pending = + api::board::arrange(backend, place.space_id.clone(), place.root_id.clone(), scope, lines); self.arranging = Some((place.root_id.clone(), pending)); } @@ -371,20 +321,12 @@ impl BoardState { /// The zone's frame as it is now: a move staged lies over the view's. pub fn frame(&self, zone: &BoardZone) -> BoardFrame { - self.staged - .frames - .get(&zone.folder.id) - .copied() - .unwrap_or(zone.frame) + self.staged.frames.get(&zone.folder.id).copied().unwrap_or(zone.frame) } /// Where a loose card sits now, a move staged over the view's. pub fn place(&self, entry: &BoardNote) -> Option { - self.staged - .places - .get(&entry.note.id) - .copied() - .or(entry.position) + self.staged.places.get(&entry.note.id).copied().or(entry.position) } pub fn view(&self) -> Option<&BoardView> { @@ -398,41 +340,29 @@ impl BoardState { /// Every card the board draws, dimmed ones included, zone by zone and then the ground: the /// order the arrows walk and a `Shift`-click ranges over. pub fn cards(&self) -> impl Iterator { - self.view().into_iter().flat_map(|view| { - view.zones - .iter() - .flat_map(|zone| &zone.notes) - .chain(&view.loose) - }) + self.view() + .into_iter() + .flat_map(|view| view.zones.iter().flat_map(|zone| &zone.notes).chain(&view.loose)) } /// How many notes the criteria leave lit; `None` while nothing dims anything. pub fn matched(&self) -> Option { - self.view() - .filter(|view| view.is_filtering) - .map(|view| view.matched) + self.view().filter(|view| view.is_filtering).map(|view| view.matched) } } /// A place the view agrees with is dropped; one it says nothing about is kept — a card dropped a /// moment ago is exactly what the overlay is for. fn release(staged: &mut Staged, view: &BoardView) { - let frames: HashMap<&str, BoardFrame> = view - .zones - .iter() - .map(|zone| (zone.folder.id.as_str(), zone.frame)) - .collect(); - staged - .frames - .retain(|id, frame| frames.get(id.as_str()) != Some(frame)); + let frames: HashMap<&str, BoardFrame> = + view.zones.iter().map(|zone| (zone.folder.id.as_str(), zone.frame)).collect(); + staged.frames.retain(|id, frame| frames.get(id.as_str()) != Some(frame)); let places: HashMap<&str, BoardPoint> = view .loose .iter() .filter_map(|entry| Some((entry.note.id.as_str(), entry.position?))) .collect(); - staged - .places - .retain(|id, at| places.get(id.as_str()) != Some(at)); + staged.places.retain(|id, at| places.get(id.as_str()) != Some(at)); } /// Every card of the view, by the zone it is drawn in, `None` for the ground. @@ -444,11 +374,7 @@ fn membership(view: &BoardView) -> HashMap<&str, Option<&str>> { .iter() .map(|entry| (entry.note.id.as_str(), Some(zone.folder.id.as_str()))) }) - .chain( - view.loose - .iter() - .map(|entry| (entry.note.id.as_str(), None)), - ) + .chain(view.loose.iter().map(|entry| (entry.note.id.as_str(), None))) .collect() } @@ -456,28 +382,18 @@ fn save(backend: &Backend, staged: &Staged) -> Pending<()> { let zones = staged .frames .iter() - .map(|(folder_id, frame)| ZonePlacement { - folder_id: folder_id.clone(), - frame: *frame, - }) + .map(|(folder_id, frame)| ZonePlacement { folder_id: folder_id.clone(), frame: *frame }) .collect(); let cards = staged .places .iter() - .map(|(note_id, position)| CardPlacement { - note_id: note_id.clone(), - position: *position, - }) + .map(|(note_id, position)| CardPlacement { note_id: note_id.clone(), position: *position }) .collect(); api::board::save_layout(backend, staged.root_id.clone(), zones, cards) } fn query(params: Params, now: DateTime) -> BoardQuery { - let Criteria { - search, - filter, - facets, - } = params.criteria; + let Criteria { search, filter, facets } = params.criteria; BoardQuery { space_id: params.place.space_id, root_id: params.place.root_id, @@ -523,10 +439,7 @@ mod tests { engine::folders::create_folder(engine, &draft) }) .unwrap(); - let place = Place { - space_id: note.space_id.clone(), - root_id: None, - }; + let place = Place { space_id: note.space_id.clone(), root_id: None }; (backend, profile, place, folder.id) } @@ -547,14 +460,8 @@ mod tests { let (backend, _profile) = testing::unlocked(); let kept = testing::note(&backend, "psql prod"); testing::note(&backend, "curl health"); - let place = Place { - space_id: kept.space_id.clone(), - root_id: None, - }; - let criteria = Criteria { - search: "psql".into(), - ..Criteria::default() - }; + let place = Place { space_id: kept.space_id.clone(), root_id: None }; + let criteria = Criteria { search: "psql".into(), ..Criteria::default() }; let mut state = BoardState::default(); for _ in 0..2 { state.update( @@ -581,12 +488,7 @@ mod tests { let mut state = BoardState::default(); read(&mut state, &backend, &place, revision); let card = state.view().unwrap().loose[0].note.id.clone(); - let moved = BoardFrame { - x: 400, - y: 300, - width: 300, - height: 260, - }; + let moved = BoardFrame { x: 400, y: 300, width: 300, height: 260 }; let at = BoardPoint { x: 40, y: 600 }; let mut frame = |state: &mut BoardState, revision: &mut Revision, time: f64| { testing::frame(&ctx, time, |_| {}); @@ -599,11 +501,7 @@ mod tests { frame(&mut state, &mut revision, 0.1); state.move_card(&place, card.clone(), at, 0.2); frame(&mut state, &mut revision, 0.5); - assert_eq!( - revision, - Revision::default(), - "nothing written while the hand moves" - ); + assert_eq!(revision, Revision::default(), "nothing written while the hand moves"); assert_eq!(state.frame(&state.view().unwrap().zones[0]), moved); frame(&mut state, &mut revision, 0.7); @@ -629,28 +527,17 @@ mod tests { engine::db::run_here(backend.engine(), { let folder = folder.clone(); move |engine| { - let zone = ZonePlacement { - folder_id: folder, - frame: far, - }; + let zone = ZonePlacement { folder_id: folder, frame: far }; engine::folders::save_board_layout(engine, None, &[zone], &Vec::new()) } }) .unwrap(); - state.arrange( - &backend, - &place, - BoardScope::Everything, - PreviewLines::default(), - ); + state.arrange(&backend, &place, BoardScope::Everything, PreviewLines::default()); backend.settle(); let done = state.write(&ctx, &backend, &mut revision, &mut errors); - let Some(Reversible::Arrangement { - previous, moved, .. - }) = done - else { + let Some(Reversible::Arrangement { previous, moved, .. }) = done else { panic!("an arrangement answered"); }; assert_eq!(moved, 1); diff --git a/crates/ui/src/state/drawing_pictures.rs b/crates/ui/src/state/drawing_pictures.rs index 4273eb556..7d28b553a 100644 --- a/crates/ui/src/state/drawing_pictures.rs +++ b/crates/ui/src/state/drawing_pictures.rs @@ -89,19 +89,12 @@ impl Default for Thumbnails { impl Thumbnails { /// The large pictures, which a Note embeds by id: its stamp is the id alone. pub fn large() -> Self { - Self { - reader: api::notes::drawing_picture, - taken: |pictures| pictures.picture, - ..Self::default() - } + Self { reader: api::notes::drawing_picture, taken: |pictures| pictures.picture, ..Self::default() } } /// An embed's stamp: the id is all a Note holds; a drawing saved again drops it. pub fn embedded(id: &str) -> Stamp { - Stamp { - id: id.to_owned(), - updated_at: DateTime::UNIX_EPOCH, - } + Stamp { id: id.to_owned(), updated_at: DateTime::UNIX_EPOCH } } pub fn get(&self, stamp: &Stamp) -> Thumbnail<'_> { @@ -142,8 +135,7 @@ impl Thumbnails { if entry.is_done() { continue; } - if let Some(next) = advance(ctx, backend, stamp, entry, (&mut self.writes, self.taken)) - { + if let Some(next) = advance(ctx, backend, stamp, entry, (&mut self.writes, self.taken)) { *entry = next; } if entry.is_done() { @@ -182,11 +174,7 @@ fn advance( Ok(note) if note.kind == NoteKind::Drawing => { let palette = crate::notes::picture_palette(crate::theme::palette(ctx)); let scene = note.content.clone(); - Entry::Taking(api::notes::picture_drawing( - backend, - scene, - Arc::new(palette), - )) + Entry::Taking(api::notes::picture_drawing(backend, scene, Arc::new(palette))) } Ok(_) => Entry::Missing, Err(error) => failed(error), @@ -194,10 +182,7 @@ fn advance( Entry::Taking(pending) => match pending.poll()? { Ok(pictures) if pictures.thumbnail.is_empty() => Entry::Empty, Ok(pictures) => { - let patch = NotePatch { - pictures: Some(pictures.clone()), - ..NotePatch::default() - }; + let patch = NotePatch { pictures: Some(pictures.clone()), ..NotePatch::default() }; writes.push(api::notes::update(backend, stamp.id.clone(), patch)); decoding(taken(pictures)) } @@ -228,10 +213,7 @@ fn decode(uri: &str) -> Option { let mut reader = decoder.read_info().ok()?; let mut pixels = vec![0; reader.output_buffer_size()?]; let frame = reader.next_frame(&mut pixels).ok()?; - let size = [ - usize::try_from(frame.width).ok()?, - usize::try_from(frame.height).ok()?, - ]; + let size = [usize::try_from(frame.width).ok()?, usize::try_from(frame.height).ok()?]; let pixels = &pixels[..frame.buffer_size()]; match frame.color_type { png::ColorType::Rgba => Some(ColorImage::from_rgba_unmultiplied(size, pixels)), @@ -252,9 +234,7 @@ mod tests { encoder.set_color(png::ColorType::Rgba); encoder.set_depth(png::BitDepth::Eight); let mut writer = encoder.write_header().unwrap(); - writer - .write_image_data(&[255, 0, 0, 255, 0, 0, 0, 0]) - .unwrap(); + writer.write_image_data(&[255, 0, 0, 255, 0, 0, 0, 0]).unwrap(); } format!("{PNG}{}", BASE64.encode(bytes)) } diff --git a/crates/ui/src/state/editor.rs b/crates/ui/src/state/editor.rs index 775d3fe65..2ddee7b7a 100644 --- a/crates/ui/src/state/editor.rs +++ b/crates/ui/src/state/editor.rs @@ -39,14 +39,7 @@ pub struct Edit { impl Edit { fn merge(&mut self, later: Edit) { - let Edit { - title, - source, - body, - tags, - lifecycle, - language, - } = later; + let Edit { title, source, body, tags, lifecycle, language } = later; self.title = title.or(self.title.take()); self.source = source.or(self.source.take()); self.body = body.or(self.body.take()); @@ -70,9 +63,7 @@ impl Edit { source: self.source.filter(|source| *source != note.source), body, tags: self.tags.filter(|tags| *tags != note.tags), - lifecycle: self - .lifecycle - .filter(|lifecycle| *lifecycle != note.lifecycle), + lifecycle: self.lifecycle.filter(|lifecycle| *lifecycle != note.lifecycle), language: self.language.filter(|language| *language != note.language), } } @@ -160,10 +151,7 @@ struct Picturing { } enum PictureStep { - Checking { - has: Pending>, - scene: (String, Arc), - }, + Checking { has: Pending>, scene: (String, Arc) }, Taking(Pending), Taken(DrawingPictures), } @@ -240,10 +228,7 @@ impl EditorState { title: String, ) { self.draft(kind, space, folder); - let edit = Edit { - title: Some(title), - ..Edit::default() - }; + let edit = Edit { title: Some(title), ..Edit::default() }; self.save(backend, self.sessions, edit); } @@ -256,11 +241,7 @@ impl EditorState { language: Language, ) { self.draft(kind, space, folder); - let edit = Edit { - body: Some(Body::Content(content)), - language: Some(language), - ..Edit::default() - }; + let edit = Edit { body: Some(Body::Content(content)), language: Some(language), ..Edit::default() }; self.save(backend, self.sessions, edit); } @@ -302,11 +283,7 @@ impl EditorState { if edit.is_empty() { return; } - if let Some(creating) = self - .creating - .iter_mut() - .find(|creating| creating.session == session) - { + if let Some(creating) = self.creating.iter_mut().find(|creating| creating.session == session) { creating.waiting.merge(edit); return; } @@ -326,26 +303,17 @@ impl EditorState { }; let edit = edit.changed_from(¬e.note); if !edit.is_empty() { - self.writes - .push(api::notes::update(backend, id, edit.into_patch())); + self.writes.push(api::notes::update(backend, id, edit.into_patch())); } } /// A body formatted on save: into the opening if it is still open, by id once it is closed. pub fn save_body(&mut self, backend: &Backend, session: u64, id: String, body: String) { - let edit = Edit { - body: Some(Body::Content(body)), - ..Edit::default() - }; - if self - .open - .as_ref() - .is_some_and(|open| open.session == session) - { + let edit = Edit { body: Some(Body::Content(body)), ..Edit::default() }; + if self.open.as_ref().is_some_and(|open| open.session == session) { self.save(backend, session, edit); } else { - self.writes - .push(api::notes::update(backend, id, edit.into_patch())); + self.writes.push(api::notes::update(backend, id, edit.into_patch())); } } @@ -377,10 +345,7 @@ impl EditorState { fn advance_pictures(&mut self, backend: &Backend, errors: &mut ErrorNotifier) { let mut writes = Vec::new(); self.picturing.retain_mut(|entry| { - let step = std::mem::replace( - &mut entry.step, - PictureStep::Taken(DrawingPictures::default()), - ); + let step = std::mem::replace(&mut entry.step, PictureStep::Taken(DrawingPictures::default())); entry.step = match step { PictureStep::Checking { mut has, scene } => match has.poll() { None => PictureStep::Checking { has, scene }, @@ -406,10 +371,7 @@ impl EditorState { true }); for (id, pictures) in writes { - let patch = NotePatch { - pictures: Some(pictures), - ..NotePatch::default() - }; + let patch = NotePatch { pictures: Some(pictures), ..NotePatch::default() }; let writing = api::notes::update(backend, id.clone(), patch); self.pictured.push((id, writing)); } @@ -446,11 +408,7 @@ impl EditorState { let writing = self.creating.iter().any(|it| it.session == session); if let (Some(draft), false) = (&open.draft, writing) { let pending = api::notes::create(backend, new_note(&draft.note)); - self.creating.push(Creating { - session, - pending, - waiting: Edit::default(), - }); + self.creating.push(Creating { session, pending, waiting: Edit::default() }); } } @@ -476,17 +434,11 @@ impl EditorState { return; }; // One creation per draft: what changes while it is written stays on screen only. - let writing = self - .creating - .iter() - .any(|creating| creating.session == open.session); + let writing = self.creating.iter().any(|creating| creating.session == open.session); if worth_keeping(¬e) && !writing { let pending = api::notes::create(backend, new_note(¬e)); - self.creating.push(Creating { - session: open.session, - pending, - waiting: Edit::default(), - }); + self.creating + .push(Creating { session: open.session, pending, waiting: Edit::default() }); } open.draft = Some(api::notes::decorate(note)); } @@ -496,9 +448,7 @@ impl EditorState { && let Some(id) = &open.id { open.read.want((id.clone(), revision)); - let read = open - .read - .update(|(id, _)| api::notes::get(backend, id.clone())); + let read = open.read.update(|(id, _)| api::notes::get(backend, id.clone())); if read && std::mem::take(&mut open.reseed) { // A session number of its own, past every one given: `sessions` follows below. open.session = self.sessions + 1; @@ -518,36 +468,23 @@ impl EditorState { } /// The writes that answered; each one moves the revision. - pub fn adopt( - &mut self, - backend: &Backend, - revision: &mut Revision, - errors: &mut ErrorNotifier, - ) { + pub fn adopt(&mut self, backend: &Backend, revision: &mut Revision, errors: &mut ErrorNotifier) { let mut created = Vec::new(); - self.creating - .retain_mut(|creating| match creating.pending.poll() { - None => true, - Some(answer) => { - created.push(( - creating.session, - std::mem::take(&mut creating.waiting), - answer, - )); - false - } - }); + self.creating.retain_mut(|creating| match creating.pending.poll() { + None => true, + Some(answer) => { + created.push((creating.session, std::mem::take(&mut creating.waiting), answer)); + false + } + }); for (session, waiting, answer) in created { match answer { Ok(note) => { revision.bump(); let waiting = waiting.changed_from(¬e.note); if !waiting.is_empty() { - self.writes.push(api::notes::update( - backend, - note.id.clone(), - waiting.into_patch(), - )); + self.writes + .push(api::notes::update(backend, note.id.clone(), waiting.into_patch())); } for entry in &mut self.picturing { if entry.session == session { @@ -566,18 +503,17 @@ impl EditorState { } self.advance_pictures(backend, errors); let redrawn = &mut self.redrawn; - self.pictured - .retain_mut(|(id, pending)| match pending.poll() { - None => true, - Some(Ok(_)) => { - redrawn.push(std::mem::take(id)); - false - } - Some(Err(error)) => { - errors.report(keys::errors::NOTE_SAVE_FAILED, &error); - false - } - }); + self.pictured.retain_mut(|(id, pending)| match pending.poll() { + None => true, + Some(Ok(_)) => { + redrawn.push(std::mem::take(id)); + false + } + Some(Err(error)) => { + errors.report(keys::errors::NOTE_SAVE_FAILED, &error); + false + } + }); self.writes.retain_mut(|pending| match pending.poll() { None => true, Some(Ok(_)) => { @@ -655,26 +591,13 @@ mod tests { let changed = edit.changed_from(¬e); - assert_eq!( - changed, - Edit { - source: Some("Ops".into()), - ..Edit::default() - } - ); + assert_eq!(changed, Edit { source: Some("Ops".into()), ..Edit::default() }); } #[test] fn a_later_field_wins_and_an_earlier_one_stays() { - let mut first = Edit { - title: Some("a".into()), - source: Some("Ops".into()), - ..Edit::default() - }; - first.merge(Edit { - title: Some("b".into()), - ..Edit::default() - }); + let mut first = Edit { title: Some("a".into()), source: Some("Ops".into()), ..Edit::default() }; + first.merge(Edit { title: Some("b".into()), ..Edit::default() }); assert_eq!(first.title.as_deref(), Some("b")); assert_eq!(first.source.as_deref(), Some("Ops")); diff --git a/crates/ui/src/state/explored.rs b/crates/ui/src/state/explored.rs index 97b423ed3..cac1fd779 100644 --- a/crates/ui/src/state/explored.rs +++ b/crates/ui/src/state/explored.rs @@ -18,8 +18,7 @@ impl ExploredState { } pub fn update(&mut self, backend: &Backend) { - self.cell - .update(|(_, query)| api::json::explore(backend, query)); + self.cell.update(|(_, query)| api::json::explore(backend, query)); } /// The opening `session`'s view as last answered, and the text it was made of: its spans diff --git a/crates/ui/src/state/folders.rs b/crates/ui/src/state/folders.rs index 9988f5ea6..ecf65fb53 100644 --- a/crates/ui/src/state/folders.rs +++ b/crates/ui/src/state/folders.rs @@ -73,10 +73,7 @@ impl FoldersState { } pub fn remember(&self, preferences: &mut Preferences) { - preferences.set( - ACTIVE_FOLDER_KEY, - self.chosen.as_deref().unwrap_or_default(), - ); + preferences.set(ACTIVE_FOLDER_KEY, self.chosen.as_deref().unwrap_or_default()); } /// Once a frame, with the library open. @@ -92,22 +89,13 @@ impl FoldersState { self.writes.retain_mut(|writing| { let answer = match &mut writing.write { Write::Folder(pending) => pending.poll().map(|answer| answer.map(|_| None)), - Write::Deleted { - pending, - folder, - parent, - held, - } => pending.poll().map(|answer| { + Write::Deleted { pending, folder, parent, held } => pending.poll().map(|answer| { answer.map(|notes| { said.push(deleted(*held, notes)); Some((folder.clone(), parent.clone())) }) }), - Write::Moved { - pending, - name, - into, - } => pending.poll().map(|answer| { + Write::Moved { pending, name, into } => pending.poll().map(|answer| { answer.map(|was| { answered.done.push(Reversible::FolderMove { was, @@ -151,8 +139,7 @@ impl FoldersState { } if let Some(id) = &self.counted { self.contents.want((id.clone(), *revision)); - self.contents - .update(|(id, _)| api::folders::contents(backend, id)); + self.contents.update(|(id, _)| api::folders::contents(backend, id)); } answered } @@ -180,9 +167,7 @@ impl FoldersState { /// Whether `id` holds folders: its board is then a board, and not a flat grid. pub fn has_children(&self, id: &str) -> bool { - self.list() - .iter() - .any(|folder| folder.parent_id.as_deref() == Some(id)) + self.list().iter().any(|folder| folder.parent_id.as_deref() == Some(id)) } /// Opened, in its own space: answers that space, which the caller shows. @@ -210,13 +195,7 @@ impl FoldersState { self.naming = false; } - pub fn create( - &mut self, - backend: &Backend, - space_id: String, - parent_id: Option, - name: &str, - ) { + pub fn create(&mut self, backend: &Backend, space_id: String, parent_id: Option, name: &str) { let Some(name) = trimmed(name) else { return }; let failed = Message::new(keys::errors::FOLDER_CREATE_FAILED).with("name", name.as_str()); let pending = api::folders::create(backend, space_id, parent_id, name); @@ -225,18 +204,12 @@ impl FoldersState { pub fn rename(&mut self, backend: &Backend, id: String, name: &str) { let Some(name) = trimmed(name) else { return }; - let unchanged = self - .list() - .iter() - .any(|folder| folder.id == id && folder.name == name); + let unchanged = self.list().iter().any(|folder| folder.id == id && folder.name == name); if unchanged { return; } let failed = Message::new(keys::errors::FOLDER_RENAME_FAILED).with("name", name.as_str()); - self.push( - Write::Folder(api::folders::rename(backend, id, name)), - failed, - ); + self.push(Write::Folder(api::folders::rename(backend, id, name)), failed); } pub fn recolour(&mut self, backend: &Backend, id: String, colour: FolderColour) { @@ -266,9 +239,7 @@ impl FoldersState { } pub fn contents(&self, id: &str) -> Option<&FolderContents> { - (self.counted.as_deref() == Some(id)) - .then(|| self.contents.value()) - .flatten() + (self.counted.as_deref() == Some(id)).then(|| self.contents.value()).flatten() } /// Under `parent_id` of `space_id`, or at its top for `None`, with everything it holds; @@ -282,11 +253,8 @@ impl FoldersState { (name, into): (String, Option), ) { let failed = Message::new(keys::errors::FOLDER_MOVE_FAILED); - let write = Write::Moved { - pending: api::folders::move_to(backend, id, (space_id, parent_id)), - name, - into, - }; + let write = + Write::Moved { pending: api::folders::move_to(backend, id, (space_id, parent_id)), name, into }; self.push(write, failed); } diff --git a/crates/ui/src/state/formatting.rs b/crates/ui/src/state/formatting.rs index 011229d09..b92095135 100644 --- a/crates/ui/src/state/formatting.rs +++ b/crates/ui/src/state/formatting.rs @@ -43,15 +43,11 @@ impl FormattingState { } pub fn busy(&self, session: u64) -> bool { - self.asked - .as_ref() - .is_some_and(|(asked, _)| *asked == session) + self.asked.as_ref().is_some_and(|(asked, _)| *asked == session) } pub fn answered(&self, session: u64) -> Option<&Answered> { - self.answered - .as_ref() - .filter(|each| each.session == session) + self.answered.as_ref().filter(|each| each.session == session) } /// A body to format before it is written, by `id` if the editor is closed by then. @@ -79,27 +75,15 @@ impl FormattingState { None => self.saving.push(saving), Some(answer) => { let body = match answer { - Ok(Answer::Formatted { - text, - cursor, - changed_lines, - }) => { - let answer = Answer::Formatted { - text: text.clone(), - cursor, - changed_lines, - }; + Ok(Answer::Formatted { text, cursor, changed_lines }) => { + let answer = Answer::Formatted { text: text.clone(), cursor, changed_lines }; self.answer(saving.session, answer, true); text } // Refused or unchanged, the body is written as it was typed. _ => saving.typed, }; - saved.push(Saved { - session: saving.session, - id: saving.id, - body, - }); + saved.push(Saved { session: saving.session, id: saving.id, body }); } } } @@ -108,12 +92,7 @@ impl FormattingState { fn answer(&mut self, session: u64, answer: Answer, quiet: bool) { self.seq += 1; - self.answered = Some(Answered { - session, - seq: self.seq, - answer, - quiet, - }); + self.answered = Some(Answered { session, seq: self.seq, answer, quiet }); } } diff --git a/crates/ui/src/state/held.rs b/crates/ui/src/state/held.rs new file mode 100644 index 000000000..42ca6665a --- /dev/null +++ b/crates/ui/src/state/held.rs @@ -0,0 +1,85 @@ +//! The state over a real core, without a window: an action applied, and everything it asked of +//! the core adopted. + +use crate::action::Action; +use crate::backend::Backend; +use crate::notes; +use crate::services::preferences::Preferences; +use crate::state::AppState; +use crate::testing; + +pub(crate) struct Held { + pub(crate) state: AppState, + pub(crate) backend: Backend, + pub(crate) ctx: egui::Context, + pub(crate) profile: tempfile::TempDir, +} + +/// An open library, whatever was written through `backend` before. +pub(crate) fn held((backend, profile): (Backend, tempfile::TempDir)) -> Held { + let mut state = AppState::new(Preferences::default(), true); + state.language = i18n::Language::En; + state.gate.ask(&backend); + let mut held = Held { state, backend, ctx: egui::Context::default(), profile }; + held.settle(); + held +} + +impl Held { + pub(crate) fn apply(&mut self, action: Action) { + self.state.apply(action, &self.ctx, &self.backend); + self.settle(); + } + + pub(crate) fn notes(&mut self, action: notes::Action) { + self.apply(Action::Notes(action)); + } + + pub(crate) fn key(&mut self, key: notes::canvas::shortcuts::CanvasKey) { + self.notes(notes::Action::Canvas(key)); + } + + /// Until nothing more is asked of the core: an answer may ask it again. + pub(crate) fn settle(&mut self) { + loop { + self.backend.settle(); + let launched = self.backend.launched(); + let state = &mut self.state; + state.gate.update(&self.backend, &mut state.status, &mut state.errors); + state.update_library(&self.ctx, &self.backend); + if self.backend.launched() == launched { + return; + } + } + } + + /// The last thing that failed, in words. + pub(crate) fn failed(&self) -> Option { + Some(self.state.errors.notice()?.text(i18n::Language::En)) + } + + /// The last thing that was done, in words. + pub(crate) fn done(&self) -> Option { + Some(self.state.status.latest()?.1.text(i18n::Language::En)) + } + + /// The titles of the cards shown, in their order. + pub(crate) fn shown(&self) -> Vec { + let view = self.state.notes_query.view(); + view.into_iter() + .flat_map(engine::notes::view::NotesView::cards) + .map(|card| card.title.clone()) + .collect() + } + + pub(crate) fn note(&self, id: &str) -> engine::notes::model::DisplayNote { + let id = id.to_owned(); + engine::db::run_here(self.backend.engine(), move |engine| engine::notes::get_note(engine, &id)) + .unwrap() + } + + /// The library closed under the window: whatever is asked next, the core refuses. + pub(crate) fn close_library(&self) { + testing::close_library(&self.backend); + } +} diff --git a/crates/ui/src/state/http/area_tests.rs b/crates/ui/src/state/http/area_tests.rs new file mode 100644 index 000000000..9d694a97e --- /dev/null +++ b/crates/ui/src/state/http/area_tests.rs @@ -0,0 +1,875 @@ +//! The HTTP area's state as the actions change it, without a window. + +use std::sync::Arc; + +use engine::folders::model::FolderColour; +use engine::http::environments::Variable; +use engine::http::model::{HttpItem, HttpItemKind, HttpMethod, HttpRequest, RequestBody, RequestKind}; +use platform::dialog::{Fixed, NoDialog}; + +use super::bodies::{BodiesLeft, BodyKind, FileFor, body_of_kind, with_file}; +use super::environments::{Asked as Env, Target}; +use super::history::Asked as Hist; +use super::moves::KeyMove; +use super::runner::{Asked as Run, Phase, Target as RunTarget}; +use super::sockets::{Phase as SocketPhase, Sockets}; +use super::tabs::{DraftEdit, SaveTarget, ToCreate}; +use super::{Page, cookies, leave, tree}; +use crate::action::Action; +use crate::http::Action as Http; +use crate::http::tests as http; +use crate::state::held::{Held, held}; +use crate::testing; + +const GET: (RequestKind, HttpMethod) = (RequestKind::Http, HttpMethod::Get); + +/// `API[Auth[Login] Users]`. +struct Area { + held: Held, + login: HttpRequest, + users: HttpRequest, + auth: String, + api: String, +} + +fn area() -> Area { + let (backend, profile) = testing::unlocked(); + let api = http::collection(&backend, "API"); + let auth = http::folder(&backend, &api, "Auth"); + let login = http::request(&backend, (&api, Some(&auth)), "Login", GET); + let users = http::request(&backend, (&api, None), "Users", GET); + let mut held = held((backend, profile)); + held.state.settings.area = crate::state::Area::Http; + held.settle(); + Area { held, login, users, auth: auth.id, api: api.id } +} + +impl Area { + fn ask(&mut self, action: Http) { + self.held.apply(Action::Http(action)); + } + + fn env(&mut self, asked: Env) { + self.ask(Http::Environments(asked)); + } + + /// A request open in its tab: the tab's key. + fn open(&mut self, id: &str) -> String { + self.ask(Http::OpenRequest(id.to_owned())); + self.held.state.http.tabs().active_key().unwrap().to_owned() + } + + fn edit(&mut self, key: &str, edit: DraftEdit) { + self.ask(Http::Edit { key: key.to_owned(), edit }); + } + + /// The environment of that name, made. + fn environment(&mut self, name: &str) -> String { + self.env(Env::Create(name.to_owned())); + let made = self.held.state.http.environments().all().iter().find(|set| set.name == name); + made.unwrap().id.clone() + } + + fn sent(&mut self, path: &str) -> String { + let port = testing::serve(); + let key = self.open(&self.users.id.clone()); + self.edit(&key, DraftEdit::Url(format!("http://127.0.0.1:{port}{path}"))); + self.ask(Http::Send(Some(key.clone()))); + key + } +} + +fn item(kind: HttpItemKind, id: &str) -> HttpItem { + HttpItem { kind, id: id.to_owned() } +} + +fn row(name: &str, value: &str) -> Variable { + Variable { name: name.to_owned(), value: value.to_owned(), ..Variable::default() } +} + +// Environments + +#[test] +fn an_environment_is_made_shown_renamed_recoloured_and_protected() { + let mut area = area(); + let id = area.environment("Prod"); + assert_eq!(area.held.state.http.environments().target(), &Target::Environment(id.clone())); + + area.env(Env::Rename { id: id.clone(), name: "Production".to_owned() }); + area.env(Env::Recolour { id: id.clone(), colour: FolderColour::Purple }); + area.env(Env::Protect { id: id.clone(), protect: true }); + let set = area.held.state.http.environments().shown().unwrap(); + assert_eq!((set.name.as_str(), set.colour, set.protected), ("Production", FolderColour::Purple, true)); +} + +#[test] +fn the_rows_typed_are_written_in_the_set_they_were_typed_in() { + let mut area = area(); + let id = area.environment("Prod"); + area.env(Env::Rows(vec![row("host", "prod.example.com")])); + area.env(Env::Select(Target::Globals)); + area.env(Env::Rows(vec![row("token", "abc")])); + area.env(Env::Select(Target::Environment(id))); + + let environments = area.held.state.http.environments(); + assert_eq!(environments.shown().unwrap().variables[0].value, "prod.example.com"); + assert_eq!(environments.globals()[0].value, "abc"); +} + +#[test] +fn an_environment_deleted_is_shown_and_used_no_more() { + let mut area = area(); + let id = area.environment("Prod"); + area.ask(Http::ChooseEnvironment(Some(id.clone()))); + area.env(Env::Rows(vec![row("host", "typed")])); + area.env(Env::Delete(id)); + + let environments = area.held.state.http.environments(); + assert!(environments.all().is_empty()); + assert_eq!((environments.active_id(), environments.target()), (None, &Target::Globals)); + assert_eq!(area.held.failed(), None, "what was typed in it is written nowhere"); +} + +#[test] +fn a_copy_of_an_environment_keeps_its_rows() { + let mut area = area(); + let id = area.environment("Prod"); + area.env(Env::Rows(vec![row("host", "prod")])); + area.env(Env::Select(Target::Globals)); + area.env(Env::Duplicate { id, name: "Staging".to_owned() }); + + let copy = area.held.state.http.environments().shown().unwrap(); + assert_eq!((copy.name.as_str(), copy.variables[0].value.as_str()), ("Staging", "prod")); +} + +/// Where the send would look first: the environment chosen, or the globals without one. +#[test] +fn a_name_nothing_sets_gets_a_row_where_the_send_looks() { + let mut area = area(); + area.ask(Http::Define("host".to_owned())); + assert_eq!(area.held.state.http.environments().target(), &Target::Globals); + let names = |area: &Area| -> Vec { + area.held + .state + .http + .environments() + .rows() + .iter() + .map(|row| row.name.clone()) + .collect() + }; + assert_eq!(names(&area), ["host"]); + area.ask(Http::Define("host".to_owned())); + assert_eq!(names(&area), ["host"], "already there"); + + let id = area.environment("Prod"); + area.ask(Http::ChooseEnvironment(Some(id.clone()))); + area.ask(Http::Define("token".to_owned())); + assert_eq!(area.held.state.http.environments().target(), &Target::Environment(id)); + assert_eq!(names(&area), ["token"]); +} + +/// Without waiting for the keys to rest: a send right after reads what was typed. +#[test] +fn the_rows_typed_are_written_as_the_page_is_left() { + let mut area = area(); + area.ask(Http::ShowPage(Page::Environments)); + area.env(Env::Rows(vec![row("token", "abc")])); + assert!(area.held.state.http.environments().globals().is_empty()); + + area.ask(Http::ShowPage(Page::Requests)); + assert_eq!(area.held.state.http.environments().globals()[0].value, "abc"); +} + +// Tabs + +/// The row it just got would be out of sight. +#[test] +fn a_request_saved_in_a_folded_collection_unfolds_it() { + let mut area = area(); + area.ask(Http::Toggle(area.api.clone())); + area.ask(Http::NewRequest(RequestKind::Http)); + let key = area.held.state.http.tabs().active_key().unwrap().to_owned(); + let target = SaveTarget { + collection_id: area.api.clone(), + folder_id: None, + name: "Health".to_owned(), + create: ToCreate::Nothing, + }; + area.ask(Http::SaveTo { key, target }); + + let shown: Vec<&str> = area.held.state.http.rows().iter().map(|row| row.name.as_str()).collect(); + assert!(shown.contains(&"Health"), "{shown:?}"); +} + +/// Both requests open, with changes. +fn modified() -> Area { + let mut area = area(); + for id in [area.users.id.clone(), area.login.id.clone()] { + let key = area.open(&id); + area.edit(&key, DraftEdit::Method(HttpMethod::Put)); + } + assert!(!area.held.state.http.ask_leave(leave::Reason::Quit)); + area +} + +#[test] +fn every_request_is_saved_before_the_window_goes() { + let mut area = modified(); + // The core's queue held: frames go by while the first request is written. + let (go, held) = std::sync::mpsc::channel::<()>(); + let _busy = area.held.backend.db(move |_| { + let _ = held.recv(); + Ok(()) + }); + let save = Action::Http(Http::Leave(leave::Asked::SaveAll)); + area.held.state.apply(save, &area.held.ctx, &area.held.backend); + for _ in 0..3 { + area.held.state.update_library(&area.held.ctx, &area.held.backend); + } + assert_eq!(area.held.state.http.modified().count(), 2); + go.send(()).unwrap(); + area.held.settle(); + + assert_eq!(area.held.state.http.modified().count(), 0); + assert!(area.held.state.http.leave().is_released()); +} + +#[test] +fn a_question_cancelled_saves_nothing_more() { + let mut area = modified(); + for asked in [leave::Asked::SaveAll, leave::Asked::Cancel] { + area.held + .state + .apply(Action::Http(Http::Leave(asked)), &area.held.ctx, &area.held.backend); + } + area.held.settle(); + + assert_eq!(area.held.state.http.modified().count(), 2); + assert!(!area.held.state.http.leave().is_released()); +} + +#[test] +fn what_is_typed_in_a_request_is_written_once_saved() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Name("People".to_owned())); + area.edit(&key, DraftEdit::Method(HttpMethod::Post)); + assert!(area.held.state.http.tabs().active().unwrap().is_dirty()); + + area.ask(Http::SaveActive); + assert!(!area.held.state.http.tabs().active().unwrap().is_dirty()); + let found = tree::find_request(area.held.state.http.tree(), &area.users.id).unwrap(); + assert_eq!((found.name.as_str(), found.method), ("People", HttpMethod::Post)); +} + +#[test] +fn a_modified_tab_asks_before_it_closes_and_a_clean_one_does_not() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.ask(Http::AskClose(key)); + assert!(area.held.state.http.tabs().tabs().is_empty()); + + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Method(HttpMethod::Put)); + area.ask(Http::AskClose(key.clone())); + assert!(area.held.state.http.tabs().closing().is_some()); + area.ask(Http::CancelClose); + assert_eq!(area.held.state.http.tabs().tabs().len(), 1); + area.ask(Http::SaveAndClose(key)); + assert!(area.held.state.http.tabs().tabs().is_empty()); + let found = tree::find_request(area.held.state.http.tree(), &area.users.id).unwrap(); + assert_eq!(found.method, HttpMethod::Put); +} + +#[test] +fn a_tab_is_moved_one_place_at_a_time_and_stays_within_the_strip() { + let mut area = area(); + let first = area.open(&area.users.id.clone()); + let second = area.open(&area.login.id.clone()); + let order = |area: &Area| -> Vec { + area.held.state.http.tabs().tabs().iter().map(|tab| tab.key.clone()).collect() + }; + for (key, right, expected) in [ + (&first, true, [&second, &first]), + (&first, true, [&second, &first]), + (&first, false, [&first, &second]), + (&first, false, [&first, &second]), + ] { + area.ask(Http::NudgeTab { key: key.clone(), right }); + assert_eq!(order(&area), expected.map(Clone::clone)); + } +} + +#[test] +fn what_is_asked_of_a_tab_that_is_gone_does_nothing() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + let gone = || "gone".to_owned(); + for action in [ + Http::NudgeTab { key: gone(), right: true }, + Http::MoveTab { key: gone(), gap: 0 }, + Http::AskClose(gone()), + Http::Close(gone()), + Http::Save(gone()), + Http::SaveAndClose(gone()), + Http::ChooseBody { key: gone(), kind: BodyKind::Json }, + Http::Send(Some(gone())), + Http::SendAnyway(gone()), + Http::SendFile(gone(), "a.txt".to_owned()), + Http::CancelSend(gone()), + Http::ClearResponse(gone()), + Http::SendMessage { key: gone(), text: "a".to_owned() }, + Http::ClearSocketLog(gone()), + Http::Activate(gone()), + ] { + area.ask(action); + } + + assert_eq!(area.held.state.http.tabs().active_key(), Some(key.as_str())); + assert!(!area.held.state.http.tabs().active().unwrap().is_dirty()); + assert_eq!(area.held.failed(), None); +} + +#[test] +fn a_request_deleted_elsewhere_cannot_be_opened_and_says_so() { + let mut area = area(); + area.ask(Http::OpenRequest("gone".to_owned())); + + assert!(area.held.state.http.tabs().tabs().is_empty()); + assert!(area.held.failed().is_some()); +} + +// Bodies + +#[test] +fn a_file_chosen_goes_where_it_was_asked_for() { + let path = || "a.png".to_owned(); + assert_eq!( + with_file(&RequestBody::Binary { path: String::new() }, FileFor::Body, path()), + Some(RequestBody::Binary { path: path() }) + ); + let parts = RequestBody::Multipart { parts: Vec::new() }; + let Some(RequestBody::Multipart { parts: filled }) = with_file(&parts, FileFor::Part(0), path()) else { + panic!("a part"); + }; + assert!(filled.len() == 1 && filled[0].file && filled[0].value == "a.png"); + for (body, target) in [ + (&parts, FileFor::Part(1)), + (&parts, FileFor::Body), + (&RequestBody::None, FileFor::Body), + (&RequestBody::Text { text: String::new() }, FileFor::Part(0)), + ] { + assert_eq!(with_file(body, target, path()), None, "{target:?}"); + } +} + +#[test] +fn each_kind_of_body_starts_empty_and_is_read_back_as_its_kind() { + for kind in BodyKind::ALL { + assert_eq!(BodyKind::of(&body_of_kind(kind, &BodiesLeft::new())), kind); + } +} + +#[test] +fn a_file_is_picked_for_a_body_and_a_dialog_cancelled_leaves_it() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.ask(Http::ChooseBody { key: key.clone(), kind: BodyKind::Binary }); + let pick = || Http::PickFile { key: key.clone(), target: FileFor::Body }; + area.held.state.dialog = Arc::new(NoDialog); + area.ask(pick()); + area.held.state.dialog = Arc::new(Fixed("plan.bin".into())); + let body = |area: &Area| area.held.state.http.tabs().active().unwrap().draft.document.body.clone(); + assert_eq!(body(&area), RequestBody::Binary { path: String::new() }); + + area.ask(pick()); + assert_eq!(body(&area), RequestBody::Binary { path: "plan.bin".to_owned() }); +} + +/// The tab closed while the dialog was open. +#[test] +fn a_file_picked_for_a_tab_closed_since_goes_nowhere() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.held.state.dialog = Arc::new(Fixed("plan.bin".into())); + let pick = Http::PickFile { key: key.clone(), target: FileFor::Body }; + area.held.state.apply(Action::Http(pick), &area.held.ctx, &area.held.backend); + area.ask(Http::Close(key)); + + assert!(area.held.state.http.tabs().tabs().is_empty()); + assert_eq!(area.held.failed(), None); +} + +// Moves with the keys + +#[test] +fn a_move_with_nowhere_to_go_says_why() { + use i18n::keys::http::rail::moved::refused; + let mut area = area(); + let folder = item(HttpItemKind::Folder, &area.auth); + let collection = item(HttpItemKind::Collection, &area.api); + let users = item(HttpItemKind::Request, &area.users.id); + for (moved, key, said) in [ + (&folder, KeyMove::Up, refused::FIRST), + (&users, KeyMove::Down, refused::LAST), + (&folder, KeyMove::Out, refused::AT_ROOT), + (&collection, KeyMove::In, refused::COLLECTION), + ] { + area.ask(Http::KeyMove { item: moved.clone(), name: "it".to_owned(), key }); + assert_eq!(area.held.state.http.said().unwrap().1.key, said, "{key:?}"); + } +} + +#[test] +fn a_container_is_found_by_its_id_at_any_depth() { + let area = area(); + let tree = area.held.state.http.tree(); + + let auth = tree::container_of(tree, &area.auth).unwrap(); + assert_eq!((auth.name.as_str(), auth.collection_id.as_str()), ("Auth", area.api.as_str())); + assert_eq!(tree::container_of(tree, &area.api).unwrap().name, "API"); + for id in [area.users.id.as_str(), "gone"] { + assert!(tree::container_of(tree, id).is_none(), "{id}"); + } +} + +// Answers + +#[test] +fn an_answer_is_saved_to_a_file_and_a_dialog_cancelled_saves_none() { + let mut area = area(); + let key = area.sent("/json"); + let sent = area.held.state.http.sends().of(&key).unwrap(); + let id = sent.id.clone(); + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("answer.json"); + let save = || Http::SaveResponseFile { send_id: id.clone(), name: "answer.json".to_owned() }; + area.held.state.dialog = Arc::new(NoDialog); + area.ask(save()); + assert_eq!(area.held.done(), None); + + area.held.state.dialog = Arc::new(Fixed(file.clone())); + area.ask(save()); + assert!(std::fs::read_to_string(&file).unwrap().contains("Ada")); + assert!(area.held.done().unwrap().contains("answer.json")); +} + +#[test] +fn an_answer_that_cannot_be_written_there_says_so() { + let mut area = area(); + let key = area.sent("/json"); + let send_id = area.held.state.http.sends().of(&key).unwrap().id.clone(); + let directory = tempfile::tempdir().unwrap(); + area.held.state.dialog = Arc::new(Fixed(directory.path().join("gone").join("answer.json"))); + area.ask(Http::SaveResponseFile { send_id, name: "answer.json".to_owned() }); + + assert!(area.held.failed().is_some()); + assert_eq!(area.held.done(), None); +} + +#[test] +fn a_text_kept_as_a_note_is_among_the_notes_at_once() { + let mut area = area(); + let space = crate::notes::bench::space(&area.held.backend, "Home"); + let asked = super::kept::NoteAsked { + title: "curl".to_owned(), + language: engine::notes::language::Language::Sh, + content: "curl https://example.com".to_owned(), + what: i18n::keys::http::code::COPIED, + tags: String::new(), + source: String::new(), + warning: None, + }; + area.ask(Http::AskNote(Box::new(asked))); + let placement = super::kept::Placement { + title: "curl".to_owned(), + space_id: space.id, + folder_id: None, + tags: vec!["http".to_owned()], + place: "Home".to_owned(), + }; + area.ask(Http::SaveNote(placement)); + + assert_eq!(area.held.shown(), ["curl"]); + assert!(area.held.done().unwrap().contains("Home")); +} + +/// Each file is a yes of its own, and a send asked anew has none. +#[test] +fn the_files_agreed_to_go_with_the_send_they_were_agreed_to_for() { + let mut area = area(); + let key = area.sent("/json"); + let files = |area: &Area| area.held.state.http.sends().of(&key).unwrap().consent.files.clone(); + for path in ["a.txt", "b.txt"] { + area.ask(Http::SendFile(key.clone(), path.to_owned())); + } + assert_eq!(files(&area), ["a.txt", "b.txt"]); + + area.ask(Http::Send(Some(key.clone()))); + assert!(files(&area).is_empty()); +} + +#[test] +fn an_answer_let_go_cannot_be_saved_and_says_so() { + let mut area = area(); + let directory = tempfile::tempdir().unwrap(); + area.held.state.dialog = Arc::new(Fixed(directory.path().join("answer.json"))); + area.ask(Http::SaveResponseFile { send_id: "gone".to_owned(), name: "a".to_owned() }); + + assert_eq!(area.held.state.status.latest().unwrap().1.key, i18n::keys::http::response::SAVE_FAILED); +} + +#[test] +fn an_answer_copied_is_on_the_clipboard_and_said() { + let mut area = area(); + area.ask(Http::Copy("text".to_owned())); + + assert_eq!(area.held.state.status.latest().unwrap().1.key, i18n::keys::settings::COPIED); +} + +// The history + +#[test] +fn an_entry_deleted_is_selected_no_more_and_comes_back_by_undo() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + let entry = area.held.state.http.history().days()[0].items[0].id.clone(); + area.ask(Http::History(Hist::Select(entry.clone()))); + assert_eq!(area.held.state.http.history().selected(), Some(entry.as_str())); + area.ask(Http::History(Hist::Delete(entry))); + assert!(area.held.state.http.history().days().is_empty()); + assert_eq!(area.held.state.http.history().selected(), None); + + area.ask(Http::History(Hist::Undo)); + assert_eq!(area.held.state.http.history().days().len(), 1); +} + +#[test] +fn an_undo_put_away_is_offered_no_more() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + let entry = area.held.state.http.history().days()[0].items[0].id.clone(); + area.ask(Http::History(Hist::Delete(entry))); + assert!(area.held.state.http.history().removed().is_some()); + + area.ask(Http::History(Hist::DismissUndo)); + assert!(area.held.state.http.history().removed().is_none()); + area.ask(Http::History(Hist::Undo)); + assert!(area.held.state.http.history().days().is_empty()); +} + +#[test] +fn the_history_is_emptied_once_its_count_was_agreed_to() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::ShowPage(super::Page::History)); + area.ask(Http::History(Hist::AskClear)); + assert_eq!(area.held.state.http.history().confirming(), Some(1)); + area.ask(Http::History(Hist::CancelClear)); + assert_eq!(area.held.state.http.history().days().len(), 1); + + area.ask(Http::History(Hist::AskClear)); + area.ask(Http::History(Hist::Clear)); + assert!(area.held.state.http.history().days().is_empty()); + assert!(area.held.done().is_some()); +} + +// The cookies + +#[test] +fn the_cookies_of_a_domain_go_together_and_the_jar_once_agreed_to() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::Cookies(cookies::Asked::Open)); + let domains = |area: &Area| area.held.state.http.cookies().domains().map_or(0, <[_]>::len); + assert_eq!(domains(&area), 1); + area.ask(Http::Cookies(cookies::Asked::RemoveDomain("127.0.0.1".to_owned()))); + assert_eq!(domains(&area), 0); + + area.ask(Http::Cookies(cookies::Asked::AskClear)); + assert_eq!(area.held.state.http.cookies().confirming(), Some(0)); + area.ask(Http::Cookies(cookies::Asked::CancelClear)); + assert_eq!(area.held.state.http.cookies().confirming(), None); + area.ask(Http::Cookies(cookies::Asked::Close)); + assert!(!area.held.state.http.cookies().is_open()); +} + +// The runner + +fn collection_run(area: &mut Area) { + let target = RunTarget { item: item(HttpItemKind::Collection, &area.api), name: "API".to_owned() }; + area.ask(Http::Runner(Run::Open(target))); +} + +#[test] +fn a_run_is_set_up_and_keeps_its_options() { + let mut area = area(); + collection_run(&mut area); + for asked in [ + Run::Iterations(3), + Run::Delay(250), + Run::StopOnFailure(true), + Run::KeepVariables(true), + Run::KeepResponses(true), + ] { + area.ask(Http::Runner(asked)); + } + + let runner = area.held.state.http.runner(); + assert_eq!((runner.runs(), runner.delay_ms()), (3, 250)); + assert!(runner.stop_on_failure() && runner.keep_variables() && runner.keep_responses()); +} + +/// Kept with the collection, whatever was opened in between. +#[test] +fn a_collection_opened_again_has_the_requests_left_out_of_its_run() { + let mut area = area(); + collection_run(&mut area); + area.ask(Http::Runner(Run::Toggle(0))); + let folder = RunTarget { item: item(HttpItemKind::Folder, &area.auth), name: "Auth".to_owned() }; + area.ask(Http::Runner(Run::Open(folder))); + assert_eq!(area.held.state.http.runner().enabled_count(), 1); + + collection_run(&mut area); + let enabled: Vec = area.held.state.http.runner().rows().iter().map(|row| row.enabled).collect(); + assert_eq!(enabled, [false, true]); +} + +#[test] +fn a_run_that_only_reads_asks_nothing_under_a_protected_environment() { + let mut area = area(); + area.sent("/json"); + area.ask(Http::SaveActive); + let id = area.environment("Prod"); + area.env(Env::Protect { id: id.clone(), protect: true }); + area.ask(Http::ChooseEnvironment(Some(id))); + collection_run(&mut area); + let login = area.held.state.http.runner().rows().iter().position(|row| row.name == "Login"); + area.ask(Http::Runner(Run::Toggle(login.unwrap()))); + + area.ask(Http::Runner(Run::Start)); + assert_eq!(area.held.state.http.runner().phase(), Phase::Done); +} + +#[test] +fn a_run_of_nothing_never_starts() { + let mut area = area(); + collection_run(&mut area); + let rows = area.held.state.http.runner().rows().len(); + assert_eq!(rows, 2); + for at in 0..rows { + area.ask(Http::Runner(Run::Toggle(at))); + } + assert_eq!(area.held.state.http.runner().enabled_count(), 0); + + area.ask(Http::Runner(Run::Start)); + assert!(!area.held.state.http.runner().is_running()); + assert_eq!(area.held.state.http.runner().phase(), Phase::Idle); +} + +#[test] +fn a_data_file_not_chosen_leaves_the_run_without_one() { + let mut area = area(); + collection_run(&mut area); + area.held.state.dialog = Arc::new(NoDialog); + area.ask(Http::Runner(Run::ChooseData)); + assert!(area.held.state.http.runner().data().is_none()); + + area.held.state.dialog = Arc::new(Fixed("no-such-file.csv".into())); + area.ask(Http::Runner(Run::ChooseData)); + assert!(area.held.state.http.runner().data().is_none()); + assert!(area.held.failed().is_some()); +} + +// What the core refuses + +#[test] +fn what_is_refused_in_the_area_is_said() { + type Asks = fn(&mut Area); + let gestures: [(&str, Asks); 11] = [ + ("open", |a| a.ask(Http::OpenRequest(a.login.id.clone()))), + ("ask a deletion", |a| { + a.ask(Http::AskDelete(item(HttpItemKind::Collection, &a.api))); + }), + ("settings", |a| { + let container = tree::container_of(a.held.state.http.tree(), &a.auth).unwrap(); + a.ask(Http::OpenSettings(container)); + }), + ("move", |a| { + let moved = item(HttpItemKind::Request, &a.users.id); + a.ask(Http::KeyMove { item: moved, name: "Users".to_owned(), key: KeyMove::Up }); + }), + ("create an environment", |a| { + a.env(Env::Create("Prod".to_owned())); + }), + ("rename an environment", |a| { + a.env(Env::Rename { id: "a".to_owned(), name: "b".to_owned() }); + }), + ("the cookies", |a| { + a.ask(Http::Cookies(cookies::Asked::Open)); + }), + ("the history", |a| { + a.ask(Http::ShowPage(super::Page::History)); + }), + ("empty the history", |a| { + a.ask(Http::History(Hist::AskClear)); + }), + ("delete from the history", |a| { + a.ask(Http::History(Hist::Delete("a".to_owned()))); + }), + ("a run", collection_run), + ]; + for (name, asks) in gestures { + let mut area = area(); + assert_eq!(area.held.failed(), None, "{name}: before"); + area.held.close_library(); + asks(&mut area); + assert!(area.held.failed().is_some(), "{name} is refused and nothing says it"); + } +} + +#[test] +fn a_request_that_cannot_be_written_says_so_and_stays_modified() { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + area.edit(&key, DraftEdit::Method(HttpMethod::Delete)); + area.held.close_library(); + area.ask(Http::SaveAndClose(key)); + + assert!(area.held.failed().is_some()); + assert!(area.held.state.http.tabs().active().unwrap().is_dirty()); +} + +// The sockets + +/// A tab's socket, on its way to an address nothing answers. +fn connecting() -> (Area, Sockets, String) { + let mut area = area(); + let key = area.open(&area.users.id.clone()); + let tab = area.held.state.http.tabs().tab(&key).unwrap().clone(); + let mut sockets = Sockets::default(); + sockets.connect(&area.held.backend, &tab, None); + (area, sockets, key) +} + +fn event( + sockets: &Sockets, + key: &str, + event: engine::http::websocket::SocketEvent, +) -> engine::http::websocket::WebsocketEvent { + engine::http::websocket::WebsocketEvent { + id: sockets.of(key).unwrap().socket_id().to_owned(), + at: chrono::Utc::now(), + event, + } +} + +/// The shortcut connects and never cuts. +#[test] +fn a_live_socket_is_closed_by_its_button_alone() { + let (backend, profile) = testing::unlocked(); + let api = http::collection(&backend, "API"); + let socket = http::request(&backend, (&api, None), "Socket", (RequestKind::Websocket, HttpMethod::Get)); + let mut held = held((backend, profile)); + held.state.settings.area = crate::state::Area::Http; + held.apply(Action::Http(Http::OpenRequest(socket.id))); + let key = held.state.http.tabs().active_key().unwrap().to_owned(); + // Accepted by the system and never answered: the socket stays on its way. + let silent = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let url = format!("ws://{}/", silent.local_addr().unwrap()); + held.apply(Action::Http(Http::Edit { key: key.clone(), edit: DraftEdit::Url(url) })); + + for (asked, phase) in [ + (Some(key.clone()), SocketPhase::Connecting), + (None, SocketPhase::Connecting), + (Some(key.clone()), SocketPhase::Closing), + ] { + held.state.apply(Action::Http(Http::Send(asked)), &held.ctx, &held.backend); + assert_eq!(held.state.http.sockets().of(&key).unwrap().phase, phase); + } +} + +#[test] +fn a_socket_follows_its_events_to_its_end() { + use engine::http::websocket::SocketEvent; + let (_area, mut sockets, key) = connecting(); + assert!(sockets.is_live(&key) && !sockets.is_open(&key)); + + let opened = + event(&sockets, &key, SocketEvent::Opened { url: String::new(), protocol: Some("chat".to_owned()) }); + sockets.receive(opened); + assert!(sockets.is_open(&key)); + assert_eq!(sockets.of(&key).unwrap().protocol.as_deref(), Some("chat")); + + let failed = event( + &sockets, + &key, + SocketEvent::Failed { + code: engine::error::ErrorCode::HttpNetwork, + params: std::collections::BTreeMap::new(), + detail: "reset".to_owned(), + }, + ); + sockets.receive(failed); + let state = sockets.of(&key).unwrap(); + assert_eq!(state.phase, SocketPhase::Closed); + assert_eq!(state.notice.as_ref().unwrap().code, engine::error::ErrorCode::HttpNetwork); + assert!(!sockets.is_live(&key)); +} + +#[test] +fn an_event_of_another_connection_changes_nothing() { + use engine::http::websocket::SocketEvent; + let (_area, mut sockets, key) = connecting(); + let mut other = event(&sockets, &key, SocketEvent::Opened { url: String::new(), protocol: None }); + "another".clone_into(&mut other.id); + sockets.receive(other); + + assert!(!sockets.is_open(&key)); +} + +#[test] +fn one_socket_a_tab_while_it_lives_and_its_log_kept_for_the_next() { + use engine::http::websocket::SocketEvent; + let (area, mut sockets, key) = connecting(); + let tab = area.held.state.http.tabs().tab(&key).unwrap().clone(); + let first = sockets.of(&key).unwrap().socket_id().to_owned(); + sockets.connect(&area.held.backend, &tab, None); + assert_eq!(sockets.of(&key).unwrap().socket_id(), first); + + let closed = event(&sockets, &key, SocketEvent::Closed { code: Some(1000), reason: String::new() }); + sockets.receive(closed); + let logged = sockets.of(&key).unwrap().log.len(); + assert!(logged > 0); + sockets.connect(&area.held.backend, &tab, None); + assert_ne!(sockets.of(&key).unwrap().socket_id(), first); + assert_eq!(sockets.of(&key).unwrap().log.len(), logged); + sockets.clear_log(&key); + assert!(sockets.of(&key).unwrap().log.is_empty()); +} + +#[test] +fn a_socket_closed_by_the_person_is_closing_until_it_is_closed() { + let (area, mut sockets, key) = connecting(); + sockets.close(&area.held.backend, &key); + assert_eq!(sockets.of(&key).unwrap().phase, SocketPhase::Closing); + let before = area.held.backend.launched(); + sockets.close(&area.held.backend, &key); + sockets.send(&area.held.backend, &key, "late".to_owned()); + assert_eq!(area.held.backend.launched(), before, "nothing more is asked of it"); +} + +#[test] +fn a_tab_saved_keeps_its_socket_and_a_tab_closed_lets_it_go() { + let (area, mut sockets, key) = connecting(); + sockets.rekey(&key, "saved"); + assert!(sockets.of(&key).is_none() && sockets.is_live("saved")); + sockets.rekey("gone", "elsewhere"); + assert!(sockets.of("elsewhere").is_none()); + + sockets.forget(&area.held.backend, "saved"); + assert_eq!(sockets.keys().count(), 0); +} diff --git a/crates/ui/src/state/http/bodies.rs b/crates/ui/src/state/http/bodies.rs index ff58f6e61..975a94d63 100644 --- a/crates/ui/src/state/http/bodies.rs +++ b/crates/ui/src/state/http/bodies.rs @@ -18,14 +18,8 @@ pub enum BodyKind { } impl BodyKind { - pub const ALL: [Self; 6] = [ - Self::None, - Self::Json, - Self::Text, - Self::Form, - Self::Multipart, - Self::Binary, - ]; + pub const ALL: [Self; 6] = + [Self::None, Self::Json, Self::Text, Self::Form, Self::Multipart, Self::Binary]; pub fn of(body: &RequestBody) -> Self { match body { @@ -88,17 +82,11 @@ pub fn body_of_kind(kind: BodyKind, left: &BodiesLeft) -> RequestBody { } match kind { BodyKind::None => RequestBody::None, - BodyKind::Json => RequestBody::Json { - text: String::new(), - }, - BodyKind::Text => RequestBody::Text { - text: String::new(), - }, + BodyKind::Json => RequestBody::Json { text: String::new() }, + BodyKind::Text => RequestBody::Text { text: String::new() }, BodyKind::Form => RequestBody::Form { fields: Vec::new() }, BodyKind::Multipart => RequestBody::Multipart { parts: Vec::new() }, - BodyKind::Binary => RequestBody::Binary { - path: String::new(), - }, + BodyKind::Binary => RequestBody::Binary { path: String::new() }, } } @@ -110,23 +98,10 @@ mod tests { fn a_body_left_comes_back_as_it_was() { let mut left = BodiesLeft::new(); - set_aside( - &mut left, - RequestBody::Json { - text: "{\"a\":1}".to_owned(), - }, - ); + set_aside(&mut left, RequestBody::Json { text: "{\"a\":1}".to_owned() }); - assert_eq!( - body_of_kind(BodyKind::Text, &left), - RequestBody::Text { - text: "{\"a\":1}".to_owned() - } - ); - assert_eq!( - body_of_kind(BodyKind::Form, &left), - RequestBody::Form { fields: Vec::new() } - ); + assert_eq!(body_of_kind(BodyKind::Text, &left), RequestBody::Text { text: "{\"a\":1}".to_owned() }); + assert_eq!(body_of_kind(BodyKind::Form, &left), RequestBody::Form { fields: Vec::new() }); assert_eq!(body_of_kind(BodyKind::None, &left), RequestBody::None); } } diff --git a/crates/ui/src/state/http/code.rs b/crates/ui/src/state/http/code.rs index 60c18f167..0baa71360 100644 --- a/crates/ui/src/state/http/code.rs +++ b/crates/ui/src/state/http/code.rs @@ -48,12 +48,7 @@ struct Question { } fn fresh_options() -> CodeOptions { - CodeOptions { - resolve_variables: true, - include_secrets: false, - multiline: true, - follow_redirects: false, - } + CodeOptions { resolve_variables: true, include_secrets: false, multiline: true, follow_redirects: false } } #[derive(Default)] diff --git a/crates/ui/src/state/http/console.rs b/crates/ui/src/state/http/console.rs index 6a96a0d3e..b79e4083e 100644 --- a/crates/ui/src/state/http/console.rs +++ b/crates/ui/src/state/http/console.rs @@ -72,3 +72,36 @@ impl Console { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn said(text: usize) -> ConsoleEvent { + ConsoleEvent { + id: "send".to_owned(), + at: chrono::DateTime::UNIX_EPOCH, + request: text.to_string(), + iteration: None, + line: ConsoleLine::Log { + level: engine::http::scripts::model::LogLevel::default(), + text: String::new(), + by: None, + }, + } + } + + #[test] + fn a_tab_keeps_its_last_lines_and_drops_the_oldest_past_them() { + let mut console = Console::default(); + for rank in 0..LINES_KEPT { + console.take("tab", said(rank)); + } + assert_eq!(console.lines_of("tab").count(), LINES_KEPT); + assert_eq!(console.lines_of("tab").next().unwrap().request, "0"); + + console.take("tab", said(LINES_KEPT)); + assert_eq!(console.lines_of("tab").count(), LINES_KEPT); + assert_eq!(console.lines_of("tab").next().unwrap().request, "1"); + } +} diff --git a/crates/ui/src/state/http/containers.rs b/crates/ui/src/state/http/containers.rs index f04c33c73..6f0847871 100644 --- a/crates/ui/src/state/http/containers.rs +++ b/crates/ui/src/state/http/containers.rs @@ -23,10 +23,7 @@ pub struct Container { impl Container { pub fn of(row: &RailRow) -> Self { Self { - item: HttpItem { - kind: row.kind, - id: row.id.clone(), - }, + item: HttpItem { kind: row.kind, id: row.id.clone() }, name: row.name.clone(), collection_id: row.collection_id.clone(), folder_id: row.folder_id.clone(), diff --git a/crates/ui/src/state/http/cookies.rs b/crates/ui/src/state/http/cookies.rs index 15bd3793d..e9e933476 100644 --- a/crates/ui/src/state/http/cookies.rs +++ b/crates/ui/src/state/http/cookies.rs @@ -90,8 +90,7 @@ impl CookieJar { } Asked::Remove(id) => self.removing.push(api::http::delete_cookie(backend, id)), Asked::RemoveDomain(domain) => { - self.removing - .push(api::http::delete_cookie_domain(backend, domain)); + self.removing.push(api::http::delete_cookie_domain(backend, domain)); } } } diff --git a/crates/ui/src/state/http/environments.rs b/crates/ui/src/state/http/environments.rs index 856eca6ee..ffa484e52 100644 --- a/crates/ui/src/state/http/environments.rs +++ b/crates/ui/src/state/http/environments.rs @@ -3,9 +3,7 @@ //! typed until they are written, once the keys rest; every other write is read back. use engine::folders::model::FolderColour; -use engine::http::environments::{ - Environment, EnvironmentPatch, HttpEnvironments, Variable, VariableKind, -}; +use engine::http::environments::{Environment, EnvironmentPatch, HttpEnvironments, Variable, VariableKind}; use i18n::keys; use crate::api; @@ -83,10 +81,7 @@ pub struct Environments { impl Environments { pub fn restore(&mut self, preferences: &Preferences) { - self.active = preferences - .get(ACTIVE_KEY) - .filter(|id| !id.is_empty()) - .map(str::to_owned); + self.active = preferences.get(ACTIVE_KEY).filter(|id| !id.is_empty()).map(str::to_owned); } pub fn remember(&self, preferences: &mut Preferences) { @@ -156,10 +151,7 @@ impl Environments { let write = match &typed.target { Target::Globals => api::http::save_globals(backend, rows), Target::Environment(id) => { - let patch = EnvironmentPatch { - variables: Some(rows), - ..EnvironmentPatch::default() - }; + let patch = EnvironmentPatch { variables: Some(rows), ..EnvironmentPatch::default() }; api::http::save_environment(backend, id.clone(), patch) } }; @@ -167,8 +159,7 @@ impl Environments { } pub fn ask(&mut self, backend: &Backend, asked: Asked, now: f64) { - let patch = - |patch: EnvironmentPatch, id: String| api::http::save_environment(backend, id, patch); + let patch = |patch: EnvironmentPatch, id: String| api::http::save_environment(backend, id, patch); match asked { Asked::Select(target) => { self.flush(backend); @@ -179,24 +170,15 @@ impl Environments { self.writes.push(write); } Asked::Rename { id, name } => { - let change = EnvironmentPatch { - name: Some(name), - ..EnvironmentPatch::default() - }; + let change = EnvironmentPatch { name: Some(name), ..EnvironmentPatch::default() }; self.writes.push(patch(change, id)); } Asked::Recolour { id, colour } => { - let change = EnvironmentPatch { - colour: Some(colour), - ..EnvironmentPatch::default() - }; + let change = EnvironmentPatch { colour: Some(colour), ..EnvironmentPatch::default() }; self.writes.push(patch(change, id)); } Asked::Protect { id, protect } => { - let change = EnvironmentPatch { - protected: Some(protect), - ..EnvironmentPatch::default() - }; + let change = EnvironmentPatch { protected: Some(protect), ..EnvironmentPatch::default() }; self.writes.push(patch(change, id)); } Asked::Duplicate { id, name } => { @@ -207,23 +189,14 @@ impl Environments { Asked::Delete(id) => self.delete(backend, id), Asked::Use(id) => self.choose(Some(id)), Asked::Rows(rows) => { - self.typed = Some(Typed { - target: self.target.clone(), - rows, - at: now, - writing: false, - }); + self.typed = Some(Typed { target: self.target.clone(), rows, at: now, writing: false }); } } } fn delete(&mut self, backend: &Backend, id: String) { let gone = Target::Environment(id.clone()); - if self - .typed - .as_ref() - .is_some_and(|typed| typed.target == gone) - { + if self.typed.as_ref().is_some_and(|typed| typed.target == gone) { self.typed = None; } if self.target == gone { @@ -239,31 +212,23 @@ impl Environments { /// value to type. pub fn define(&mut self, backend: &Backend, name: String, now: f64) { self.flush(backend); - self.target = self.active().map_or(Target::Globals, |active| { - Target::Environment(active.id.clone()) - }); + self.target = self + .active() + .map_or(Target::Globals, |active| Target::Environment(active.id.clone())); if self.rows().iter().any(|row| row.name == name) { return; } let mut rows = self.rows().to_vec(); - rows.push(Variable { - name, - kind: VariableKind::Text, - ..Variable::default() - }); + rows.push(Variable { name, kind: VariableKind::Text, ..Variable::default() }); self.ask(backend, Asked::Rows(rows), now); } pub fn all(&self) -> &[Environment] { - self.sets - .value() - .map_or(&[], |sets| sets.environments.as_slice()) + self.sets.value().map_or(&[], |sets| sets.environments.as_slice()) } pub fn globals(&self) -> &[Variable] { - self.sets - .value() - .map_or(&[], |sets| sets.globals.as_slice()) + self.sets.value().map_or(&[], |sets| sets.globals.as_slice()) } pub fn is_loaded(&self) -> bool { @@ -298,15 +263,10 @@ impl Environments { /// What the page's table shows: the rows as typed, until they are read back. pub fn rows(&self) -> &[Variable] { - if let Some(typed) = self - .typed - .as_ref() - .filter(|typed| typed.target == self.target) - { + if let Some(typed) = self.typed.as_ref().filter(|typed| typed.target == self.target) { return &typed.rows; } - self.shown() - .map_or_else(|| self.globals(), |shown| shown.variables.as_slice()) + self.shown().map_or_else(|| self.globals(), |shown| shown.variables.as_slice()) } pub fn asking(&self) -> Option<&str> { diff --git a/crates/ui/src/state/http/history.rs b/crates/ui/src/state/http/history.rs index 54827b68e..e3c8dc96e 100644 --- a/crates/ui/src/state/http/history.rs +++ b/crates/ui/src/state/http/history.rs @@ -29,14 +29,8 @@ pub enum Asked { /// Back in the request it came from, or a draft of its own. pub enum Reopened { - Onto { - request_id: String, - draft: HistoryDraft, - }, - Draft { - name: String, - draft: HistoryDraft, - }, + Onto { request_id: String, draft: HistoryDraft }, + Draft { name: String, draft: HistoryDraft }, } enum Reopening { @@ -56,10 +50,7 @@ enum Reopening { /// A draft is named after the send and its time. fn named(draft: HistoryDraft, sent_at: DateTime) -> Reopened { let time = sent_at.with_timezone(&chrono::Local).format("%H:%M"); - Reopened::Draft { - name: format!("{} · {time}", draft.name), - draft, - } + Reopened::Draft { name: format!("{} · {time}", draft.name), draft } } #[derive(Default)] @@ -109,9 +100,7 @@ impl History { } if let Some(id) = &self.selected { self.entry.want(id.clone()); - if self - .entry - .update(|id| api::http::history_entry(backend, id)) + if self.entry.update(|id| api::http::history_entry(backend, id)) && let Some(error) = self.entry.error() { errors.report(keys::http::history::FAILED, error); @@ -175,21 +164,11 @@ impl History { } } - fn adopt_reopening( - &mut self, - backend: &Backend, - errors: &mut ErrorNotifier, - ) -> Option { + fn adopt_reopening(&mut self, backend: &Backend, errors: &mut ErrorNotifier) -> Option { match self.reopening.as_mut()? { - Reopening::Onto { - request_id, - entry_id, - sent_at, - pending, - } => { + Reopening::Onto { request_id, entry_id, sent_at, pending } => { let answer = pending.poll()?; - let (request_id, entry_id, sent_at) = - (request_id.clone(), entry_id.clone(), *sent_at); + let (request_id, entry_id, sent_at) = (request_id.clone(), entry_id.clone(), *sent_at); self.reopening = None; match answer { Ok(Some(draft)) => return Some(Reopened::Onto { request_id, draft }), @@ -255,10 +234,7 @@ impl History { pub fn reopen_draft(&mut self, backend: &Backend, id: String, sent_at: DateTime) { self.replacing = None; - self.reopening = Some(Reopening::Draft { - sent_at, - pending: api::http::history_draft(backend, id), - }); + self.reopening = Some(Reopening::Draft { sent_at, pending: api::http::history_draft(backend, id) }); } pub fn days(&self) -> &[HistoryDay] { diff --git a/crates/ui/src/state/http/leave.rs b/crates/ui/src/state/http/leave.rs index e54ca4850..262d617e1 100644 --- a/crates/ui/src/state/http/leave.rs +++ b/crates/ui/src/state/http/leave.rs @@ -101,3 +101,38 @@ impl Leave { passed } } + +#[cfg(test)] +mod tests { + use super::*; + + fn released(reason: Reason) -> Leave { + let mut leave = Leave::default(); + leave.ask(reason); + leave.release(); + leave + } + + #[test] + fn a_question_before_quitting_lets_the_window_close_once_and_nothing_else() { + let mut leave = released(Reason::Quit); + + assert!(!leave.take_switch()); + assert!(leave.take_close()); + assert!(!leave.take_close()); + assert!(leave.is_released(), "the window goes: nothing is asked again"); + } + + /// The window stays: the next thing to leave the requests asks again. + #[test] + fn a_question_before_anything_else_lets_that_through_once_and_never_closes_the_window() { + for reason in [Reason::Switch, Reason::Restore, Reason::Update] { + let mut leave = released(reason); + + assert!(!leave.take_close(), "{reason:?}"); + assert!(leave.take_switch(), "{reason:?}"); + assert!(!leave.take_switch(), "{reason:?}"); + assert!(!leave.is_released(), "{reason:?}"); + } + } +} diff --git a/crates/ui/src/state/http/mod.rs b/crates/ui/src/state/http/mod.rs index 5210b7113..5fe05760e 100644 --- a/crates/ui/src/state/http/mod.rs +++ b/crates/ui/src/state/http/mod.rs @@ -2,6 +2,8 @@ //! the tree read again: the core renumbers what a move or a copy touched, and the interface never //! guesses the result. +#[cfg(test)] +mod area_tests; pub mod bodies; pub mod code; pub mod console; @@ -24,8 +26,7 @@ use engine::http::BodyAnswer; use engine::http::VariablesRequest; use engine::http::graphql::{GraphqlAnswer, GraphqlDocument}; use engine::http::model::{ - Extraction, HttpContents, HttpItem, HttpMethod, HttpTree, RequestBody, RequestDocument, - RequestKind, + Extraction, HttpContents, HttpItem, HttpMethod, HttpTree, RequestBody, RequestDocument, RequestKind, }; use engine::http::scripts::model::{ScriptKind, ScriptLevel}; use engine::http::send::ImpliedHeader; @@ -127,15 +128,10 @@ fn session_of(send_id: &str) -> u64 { fn decoded(url: &str) -> Option { use base64::Engine as _; let (_, data) = url.split_once(";base64,")?; - let bytes = base64::engine::general_purpose::STANDARD - .decode(data) - .ok()?; + let bytes = base64::engine::general_purpose::STANDARD.decode(data).ok()?; let picture = image::load_from_memory(&bytes).ok()?.into_rgba8(); let size = [picture.width() as usize, picture.height() as usize]; - Some(egui::ColorImage::from_rgba_unmultiplied( - size, - picture.as_raw(), - )) + Some(egui::ColorImage::from_rgba_unmultiplied(size, picture.as_raw())) } /// A part of a draft the core rewrites: what it held when asked, so that typing meanwhile wins. @@ -300,10 +296,7 @@ impl HttpState { ctx.send_viewport_cmd(egui::ViewportCommand::Close); } let empty = HttpTree::default(); - let read = ( - self.tree.value().unwrap_or(&empty), - self.tree.answered().copied(), - ); + let read = (self.tree.value().unwrap_or(&empty), self.tree.answered().copied()); if self.runner.update(backend, read, errors) { self.revision.bump(); } @@ -337,8 +330,7 @@ impl HttpState { } } } - self.environments - .update((ctx, backend), (self.revision, now), errors); + self.environments.update((ctx, backend), (self.revision, now), errors); self.tree.want(self.revision); if self.tree.update(|_| api::http::tree(backend)) { if let Some(error) = self.tree.error() { @@ -347,17 +339,12 @@ impl HttpState { self.lay_out(); self.land(now); if self.tree.value().is_some() { - self.tabs - .follow(self.tree.value().unwrap_or(&HttpTree::default())); + self.tabs.follow(self.tree.value().unwrap_or(&HttpTree::default())); self.unremembered = true; } } self.ask_editor(backend); - if self - .mark - .as_ref() - .is_some_and(|mark| now - mark.since > MARK_SECONDS) - { + if self.mark.as_ref().is_some_and(|mark| now - mark.since > MARK_SECONDS) { self.mark = None; } } @@ -399,9 +386,8 @@ impl HttpState { }; if let Some(place) = &tab.place { self.inherited.want((place.clone(), self.revision)); - self.inherited.update(|(place, _)| { - api::http::inherited(backend, place.collection_id, place.folder_id) - }); + self.inherited + .update(|(place, _)| api::http::inherited(backend, place.collection_id, place.folder_id)); } // Copied only when they changed: a body of megabytes, copied four times a frame, cost // milliseconds of every frame while its request was open. @@ -414,14 +400,10 @@ impl HttpState { } self.body .update(|(body, method)| api::http::describe_body(backend, body, method)); - if !self - .graphql - .wants(|graphql| *graphql == draft.document.graphql) - { + if !self.graphql.wants(|graphql| *graphql == draft.document.graphql) { self.graphql.want(draft.document.graphql.clone()); } - self.graphql - .update(|document| api::http::describe_graphql(backend, document)); + self.graphql.update(|document| api::http::describe_graphql(backend, document)); let environment = self.environments.active_id(); let asked = self.implied.wants(|question| { question.kind == draft.kind @@ -442,9 +424,9 @@ impl HttpState { self.used.want(question); } self.implied.update(|question| { - let place = question.place.map_or((None, None), |place| { - (Some(place.collection_id), place.folder_id) - }); + let place = question + .place + .map_or((None, None), |place| (Some(place.collection_id), place.folder_id)); api::http::implied_headers(backend, (question.kind, question.document), place) }); self.used.update(|question| { @@ -475,10 +457,7 @@ impl HttpState { } pub fn ask_environments(&mut self, backend: &Backend, asked: environments::Asked, now: f64) { - let remembered = matches!( - asked, - environments::Asked::Use(_) | environments::Asked::Delete(_) - ); + let remembered = matches!(asked, environments::Asked::Use(_) | environments::Asked::Delete(_)); self.environments.ask(backend, asked, now); self.unremembered |= remembered; } @@ -528,13 +507,11 @@ impl HttpState { self.history_cleared = cleared; match reopened { Some(history::Reopened::Onto { request_id, draft }) => { - self.tabs - .open_with(backend, request_id, draft.method, draft.document); + self.tabs.open_with(backend, request_id, draft.method, draft.document); self.page = Page::Requests; } Some(history::Reopened::Draft { name, draft }) => { - self.tabs - .open_draft(name, draft.kind, draft.method, draft.document); + self.tabs.open_draft(name, draft.kind, draft.method, draft.document); self.page = Page::Requests; } None => {} @@ -571,8 +548,7 @@ impl HttpState { .and_then(|id| tree::find_request(self.tree(), id)) .map(|held| (held.id.clone(), held.name.clone())); let Some((request_id, name)) = held else { - self.history - .reopen_draft(backend, entry.item.id.clone(), entry.item.sent_at); + self.history.reopen_draft(backend, entry.item.id.clone(), entry.item.sent_at); return; }; let dirty = self.tabs.tab(&request_id).is_some_and(tabs::Tab::is_dirty); @@ -746,20 +722,14 @@ impl HttpState { stop: &engine::http::scripts::model::ScriptStop, ) { let phase = stop.script.unwrap_or_default(); - let held = stop - .level - .is_some_and(|level| level != ScriptLevel::Request); + let held = stop.level.is_some_and(|level| level != ScriptLevel::Request); if held && let Some(owner) = &stop.owner && self.open_settings_of(backend, owner, (phase, stop.line)) { return; } - self.script_focus = Some(ScriptFocus { - key, - phase, - line: stop.line, - }); + self.script_focus = Some(ScriptFocus { key, phase, line: stop.line }); } /// `false` when the tree no longer holds it. @@ -827,11 +797,7 @@ impl HttpState { } pub fn toggle_page(&mut self, backend: &Backend, page: Page) { - let next = if self.page == page { - Page::Requests - } else { - page - }; + let next = if self.page == page { Page::Requests } else { page }; self.show_page(backend, next); } @@ -849,10 +815,7 @@ impl HttpState { if tab.draft.kind == RequestKind::Websocket { self.sockets.connect(backend, tab, environment); } else { - let consent = send::Consent { - protected: true, - files: Vec::new(), - }; + let consent = send::Consent { protected: true, files: Vec::new() }; self.sends.send(backend, tab, (now, environment), consent); } } @@ -885,20 +848,13 @@ impl HttpState { }; let before = part_of(&tab.draft, part).to_owned(); let pending = match part { - Rewritten::Body | Rewritten::Variables => { - api::http::prettier(backend, before.clone(), true) - } + Rewritten::Body | Rewritten::Variables => api::http::prettier(backend, before.clone(), true), Rewritten::Query => api::http::prettier(backend, before.clone(), false), Rewritten::Missing => { api::http::add_graphql_variables(backend, tab.draft.document.graphql.clone()) } }; - self.rewriting.push(Rewriting { - key: key.to_owned(), - part, - before, - pending, - }); + self.rewriting.push(Rewriting { key: key.to_owned(), part, before, pending }); } /// Off the frame: the dialog blocks until answered. @@ -910,11 +866,8 @@ impl HttpState { target: bodies::FileFor, ) { let dialog = std::sync::Arc::clone(dialog); - self.picking.push(Picking { - key, - target, - pending: backend.compute(move |_| Ok(dialog.open())), - }); + self.picking + .push(Picking { key, target, pending: backend.compute(move |_| Ok(dialog.open())) }); } fn adopt_files(&mut self, errors: &mut ErrorNotifier) { @@ -936,8 +889,7 @@ impl HttpState { }; let path = path.to_string_lossy().into_owned(); if let Some(body) = bodies::with_file(&tab.draft.document.body, target, path) { - self.tabs - .edit(&key, |draft| draft.apply(tabs::DraftEdit::Body(body))); + self.tabs.edit(&key, |draft| draft.apply(tabs::DraftEdit::Body(body))); } } } @@ -949,12 +901,9 @@ impl HttpState { return true; }; match answer { - Ok(Some(text)) => done.push(( - rewriting.key.clone(), - rewriting.part, - rewriting.before.clone(), - text, - )), + Ok(Some(text)) => { + done.push((rewriting.key.clone(), rewriting.part, rewriting.before.clone(), text)); + } Ok(None) => {} Err(error) => errors.report(keys::http::FAILED, &error), } @@ -1008,11 +957,7 @@ impl HttpState { let Some(landed) = moves::landing(self.tree(), &landing.item, landing.key) else { return; }; - self.mark = Some(Mark { - id: landing.item.id.clone(), - parent_id: landed.parent_id, - since: now, - }); + self.mark = Some(Mark { id: landing.item.id.clone(), parent_id: landed.parent_id, since: now }); let key = match landed.at { Where::Into => moved::INTO, Where::Root => moved::ROOT, @@ -1031,9 +976,7 @@ impl HttpState { } pub fn tree(&self) -> &HttpTree { - static EMPTY: HttpTree = HttpTree { - collections: Vec::new(), - }; + static EMPTY: HttpTree = HttpTree { collections: Vec::new() }; self.tree.value().unwrap_or(&EMPTY) } @@ -1079,8 +1022,7 @@ impl HttpState { pub fn ask_image(&mut self, backend: &Backend, send_id: &str) { if !self.images.contains_key(send_id) { let pending = api::http::response_image(backend, send_id.to_owned()); - self.images - .insert(send_id.to_owned(), Image::Asked(pending)); + self.images.insert(send_id.to_owned(), Image::Asked(pending)); } } @@ -1108,11 +1050,7 @@ impl HttpState { continue; }; let texture = answer.ok().flatten().map(|picture| { - ctx.load_texture( - format!("http-image-{id}"), - picture, - egui::TextureOptions::LINEAR, - ) + ctx.load_texture(format!("http-image-{id}"), picture, egui::TextureOptions::LINEAR) }); *image = Image::Shown(texture); } @@ -1138,10 +1076,7 @@ impl HttpState { } return; } - let protected = self - .environments - .active() - .is_some_and(|active| active.protected); + let protected = self.environments.active().is_some_and(|active| active.protected); if protected && api::http::asks_before_sending(tab.draft.kind, tab.draft.method) { let key = tab.key.clone(); self.environments.ask_before(&key); @@ -1152,8 +1087,7 @@ impl HttpState { if tab.draft.kind == RequestKind::Websocket { self.sockets.connect(backend, tab, environment); } else { - self.sends - .send(backend, tab, (now, environment), send::Consent::default()); + self.sends.send(backend, tab, (now, environment), send::Consent::default()); } } @@ -1162,11 +1096,7 @@ impl HttpState { let Some(tab) = self.tabs.tab(key) else { return; }; - let mut consent = self - .sends - .of(key) - .map(|sent| sent.consent.clone()) - .unwrap_or_default(); + let mut consent = self.sends.of(key).map(|sent| sent.consent.clone()).unwrap_or_default(); consent.files.push(path); let environment = self.environments.active_id().map(str::to_owned); self.sends.send(backend, tab, (now, environment), consent); @@ -1233,10 +1163,7 @@ impl HttpState { return false; } let ids: Vec<&String> = self.collapsed.iter().collect(); - preferences.set( - COLLAPSED_KEY, - &serde_json::to_string(&ids).unwrap_or_default(), - ); + preferences.set(COLLAPSED_KEY, &serde_json::to_string(&ids).unwrap_or_default()); self.tabs.remember(preferences); self.environments.remember(preferences); true @@ -1245,20 +1172,11 @@ impl HttpState { pub fn write(&mut self, backend: &Backend, write: Write) { let pending = match write { Write::CreateCollection(name) => api::http::create_collection(backend, name), - Write::CreateFolder { - collection_id, - folder_id, - name, - } => { + Write::CreateFolder { collection_id, folder_id, name } => { self.unfold(folder_id.as_deref().unwrap_or(&collection_id)); api::http::create_folder(backend, collection_id, folder_id, name) } - Write::CreateRequest { - collection_id, - folder_id, - name, - kind, - } => { + Write::CreateRequest { collection_id, folder_id, name, kind } => { self.unfold(folder_id.as_deref().unwrap_or(&collection_id)); api::http::create_request(backend, (collection_id, folder_id), name, kind) } @@ -1270,10 +1188,7 @@ impl HttpState { } Write::Move(railmove) => self.apply_move(backend, railmove), }; - self.writes.push(Writing { - pending, - landing: None, - }); + self.writes.push(Writing { pending, landing: None }); } fn apply_move(&mut self, backend: &Backend, railmove: RailMove) -> Pending { @@ -1304,20 +1219,14 @@ impl HttpState { return; }; let pending = self.apply_move(backend, railmove); - self.writes.push(Writing { - pending, - landing: Some(Landing { item, key, name }), - }); + self.writes + .push(Writing { pending, landing: Some(Landing { item, key, name }) }); } /// The question comes once Rust has counted what goes with it. pub fn ask_delete(&mut self, backend: &Backend, item: HttpItem) { let pending = api::http::contents(backend, item.clone()); - self.deleting = Some(Deleting { - item, - pending: Some(pending), - contents: None, - }); + self.deleting = Some(Deleting { item, pending: Some(pending), contents: None }); } pub fn cancel_delete(&mut self) { diff --git a/crates/ui/src/state/http/moves.rs b/crates/ui/src/state/http/moves.rs index db7af9140..f4e0fe044 100644 --- a/crates/ui/src/state/http/moves.rs +++ b/crates/ui/src/state/http/moves.rs @@ -75,13 +75,9 @@ impl Index { let mut index = Self::default(); for node in &tree.collections { let id = &node.collection.id; - index.located.insert( - id.clone(), - Located { - collection_id: id.clone(), - folder_id: None, - }, - ); + index + .located + .insert(id.clone(), Located { collection_id: id.clone(), folder_id: None }); index.names.insert(id.clone(), node.collection.name.clone()); index.walk(&node.children, id, None); } @@ -92,19 +88,12 @@ impl Index { let mut items = Vec::new(); for node in nodes { let (item, name) = match node { - HttpNode::Folder { folder, .. } => { - (item(HttpItemKind::Folder, &folder.id), &folder.name) - } - HttpNode::Request { request } => { - (item(HttpItemKind::Request, &request.id), &request.name) - } + HttpNode::Folder { folder, .. } => (item(HttpItemKind::Folder, &folder.id), &folder.name), + HttpNode::Request { request } => (item(HttpItemKind::Request, &request.id), &request.name), }; self.located.insert( item.id.clone(), - Located { - collection_id: collection_id.to_owned(), - folder_id: folder_id.map(str::to_owned), - }, + Located { collection_id: collection_id.to_owned(), folder_id: folder_id.map(str::to_owned) }, ); self.names.insert(item.id.clone(), name.clone()); if let HttpNode::Folder { folder, children } = node { @@ -112,8 +101,7 @@ impl Index { } items.push(item); } - self.children - .insert(folder_id.unwrap_or(collection_id).to_owned(), items); + self.children.insert(folder_id.unwrap_or(collection_id).to_owned(), items); } fn children_of(&self, parent: &str) -> &[HttpItem] { @@ -136,17 +124,11 @@ impl Index { } fn item(kind: HttpItemKind, id: &str) -> HttpItem { - HttpItem { - kind, - id: id.to_owned(), - } + HttpItem { kind, id: id.to_owned() } } fn collection_order(tree: &HttpTree) -> Vec<&str> { - tree.collections - .iter() - .map(|node| node.collection.id.as_str()) - .collect() + tree.collections.iter().map(|node| node.collection.id.as_str()).collect() } fn rank(at: usize) -> u32 { @@ -162,10 +144,7 @@ pub fn key_move(tree: &HttpTree, moved: &HttpItem, key: KeyMove) -> Option at + 1, KeyMove::In | KeyMove::Out => return None, }; - return (to < order.len()).then(|| RailMove::Reorder { - id: moved.id.clone(), - index: rank(to), - }); + return (to < order.len()).then(|| RailMove::Reorder { id: moved.id.clone(), index: rank(to) }); } let index = Index::of(tree); let here = index.located.get(&moved.id)?; @@ -182,9 +161,7 @@ pub fn key_move(tree: &HttpTree, moved: &HttpItem, key: KeyMove) -> Option Some(placed(here.folder_id.as_deref(), at.checked_sub(1)?)), - KeyMove::Down => { - (at + 1 < siblings.len()).then(|| placed(here.folder_id.as_deref(), at + 1)) - } + KeyMove::Down => (at + 1 < siblings.len()).then(|| placed(here.folder_id.as_deref(), at + 1)), KeyMove::In => { let above = siblings.get(at.checked_sub(1)?)?; (above.kind == HttpItemKind::Folder) @@ -193,8 +170,7 @@ pub fn key_move(tree: &HttpTree, moved: &HttpItem, key: KeyMove) -> Option { let folder_id = here.folder_id.as_deref()?; let folder = index.located.get(folder_id)?; - let around = - index.children_of(folder.folder_id.as_deref().unwrap_or(&folder.collection_id)); + let around = index.children_of(folder.folder_id.as_deref().unwrap_or(&folder.collection_id)); let at = around.iter().position(|sibling| sibling.id == folder_id)?; Some(placed(folder.folder_id.as_deref(), at + 1)) } @@ -207,24 +183,14 @@ pub fn landing(tree: &HttpTree, moved: &HttpItem, key: KeyMove) -> Option = match &parent_id { None => collection_order(tree), - Some(parent) => index - .children_of(parent) - .iter() - .map(|sibling| sibling.id.as_str()) - .collect(), + Some(parent) => index.children_of(parent).iter().map(|sibling| sibling.id.as_str()).collect(), }; let at = around.iter().position(|id| *id == moved.id)?; - let name = |at: Option| { - at.and_then(|at| around.get(at)) - .and_then(|id| index.names.get(*id)) - }; + let name = |at: Option| at.and_then(|at| around.get(at)).and_then(|id| index.names.get(*id)); // Up and down are read against the row that was passed: it is the one the eye was on. let passed = match key { KeyMove::Up => name(Some(at + 1)).map(|other| (Where::Before, other)), @@ -232,19 +198,11 @@ pub fn landing(tree: &HttpTree, moved: &HttpItem, key: KeyMove) -> Option None, }; if let Some((at, other)) = passed { - return Some(Landing { - parent_id, - at, - other: other.clone(), - }); + return Some(Landing { parent_id, at, other: other.clone() }); } let parent = parent_id?; Some(Landing { - at: if here.folder_id.is_none() { - Where::Root - } else { - Where::Into - }, + at: if here.folder_id.is_none() { Where::Root } else { Where::Into }, other: index.names.get(&parent).cloned().unwrap_or_default(), parent_id: Some(parent), }) @@ -263,12 +221,7 @@ pub fn refusal(moved: &HttpItem, key: KeyMove) -> Refusal { /// Where a drop on `target` sends `dragged`, or `None` when it would change nothing or cannot /// be: a folder into itself, a collection among anything but collections. -pub fn drop_move( - tree: &HttpTree, - dragged: &HttpItem, - target: &HttpItem, - zone: DropZone, -) -> Option { +pub fn drop_move(tree: &HttpTree, dragged: &HttpItem, target: &HttpItem, zone: DropZone) -> Option { if dragged == target { return None; } @@ -278,14 +231,9 @@ pub fn drop_move( } let all = collection_order(tree); let others: Vec<&str> = all.iter().copied().filter(|id| *id != dragged.id).collect(); - let at = - others.iter().position(|id| *id == target.id)? + usize::from(zone != DropZone::Before); - return (all.iter().position(|id| *id == dragged.id) != Some(at)).then(|| { - RailMove::Reorder { - id: dragged.id.clone(), - index: rank(at), - } - }); + let at = others.iter().position(|id| *id == target.id)? + usize::from(zone != DropZone::Before); + return (all.iter().position(|id| *id == dragged.id) != Some(at)) + .then(|| RailMove::Reorder { id: dragged.id.clone(), index: rank(at) }); } let index = Index::of(tree); let from = index.located.get(&dragged.id)?; @@ -318,11 +266,7 @@ pub fn drop_move( && siblings.iter().position(|other| other == dragged) == Some(at); (!unchanged).then(|| RailMove::Move { item: dragged.clone(), - place: HttpPlace { - collection_id, - folder_id, - index: rank(at), - }, + place: HttpPlace { collection_id, folder_id, index: rank(at) }, }) } @@ -362,18 +306,11 @@ mod tests { item(HttpItemKind::Folder, id) } - #[expect( - clippy::unnecessary_wraps, - reason = "what key_move and drop_move answer" - )] + #[expect(clippy::unnecessary_wraps, reason = "what key_move and drop_move answer")] fn placed(moved: HttpItem, folder: Option<&str>, index: u32) -> Option { Some(RailMove::Move { item: moved, - place: HttpPlace { - collection_id: "API".to_owned(), - folder_id: folder.map(str::to_owned), - index, - }, + place: HttpPlace { collection_id: "API".to_owned(), folder_id: folder.map(str::to_owned), index }, }) } @@ -383,16 +320,10 @@ mod tests { let une = request_item("Une"); let seule = request_item("Seule"); - assert_eq!( - key_move(&tree, &une, KeyMove::Up), - placed(une.clone(), Some("Factures"), 0) - ); + assert_eq!(key_move(&tree, &une, KeyMove::Up), placed(une.clone(), Some("Factures"), 0)); assert_eq!(key_move(&tree, &une, KeyMove::Down), None); assert_eq!(key_move(&tree, &une, KeyMove::Out), placed(une, None, 2)); - assert_eq!( - key_move(&tree, &seule, KeyMove::In), - placed(seule.clone(), Some("Factures"), 2) - ); + assert_eq!(key_move(&tree, &seule, KeyMove::In), placed(seule.clone(), Some("Factures"), 2)); assert_eq!(key_move(&tree, &seule, KeyMove::Out), None); } @@ -403,10 +334,7 @@ mod tests { assert_eq!( key_move(&tree, &api, KeyMove::Down), - Some(RailMove::Reorder { - id: "API".to_owned(), - index: 1 - }) + Some(RailMove::Reorder { id: "API".to_owned(), index: 1 }) ); assert_eq!(key_move(&tree, &api, KeyMove::Up), None); assert_eq!(key_move(&tree, &api, KeyMove::In), None); @@ -433,10 +361,7 @@ mod tests { assert_eq!((down.at, down.other.as_str()), (Where::After, "Lister")); let into = landing(&tree, &request_item("Login"), KeyMove::In).unwrap(); assert_eq!(into.at, Where::Into); - assert_eq!( - (into.parent_id.as_deref(), into.other.as_str()), - (Some("Auth"), "Auth") - ); + assert_eq!((into.parent_id.as_deref(), into.other.as_str()), (Some("Auth"), "Auth")); let root = landing(&tree, &request_item("Seule"), KeyMove::Out).unwrap(); assert_eq!((root.at, root.other.as_str()), (Where::Root, "API")); assert_eq!(landing(&tree, &request_item("Gone"), KeyMove::Up), None); @@ -455,10 +380,7 @@ mod tests { drop_move(&tree, &seule, &folder_item("Auth"), DropZone::Inside), placed(seule.clone(), Some("Auth"), 1) ); - assert_eq!( - drop_move(&tree, &seule, &folder_item("Auth"), DropZone::After), - placed(seule, None, 1) - ); + assert_eq!(drop_move(&tree, &seule, &folder_item("Auth"), DropZone::After), placed(seule, None, 1)); } #[test] @@ -466,31 +388,14 @@ mod tests { let tree = sample(); let factures = folder_item("Factures"); - assert_eq!( - drop_move(&tree, &factures, &factures, DropZone::Inside), - None - ); - assert_eq!( - drop_move(&tree, &factures, &folder_item("Auth"), DropZone::After), - None - ); - assert_eq!( - drop_move(&tree, &factures, &request_item("Une"), DropZone::After), - None - ); + assert_eq!(drop_move(&tree, &factures, &factures, DropZone::Inside), None); + assert_eq!(drop_move(&tree, &factures, &folder_item("Auth"), DropZone::After), None); + assert_eq!(drop_move(&tree, &factures, &request_item("Une"), DropZone::After), None); let api = item(HttpItemKind::Collection, "API"); assert_eq!(drop_move(&tree, &api, &factures, DropZone::Before), None); assert_eq!( - drop_move( - &tree, - &api, - &item(HttpItemKind::Collection, "Autre"), - DropZone::After - ), - Some(RailMove::Reorder { - id: "API".to_owned(), - index: 1 - }) + drop_move(&tree, &api, &item(HttpItemKind::Collection, "Autre"), DropZone::After), + Some(RailMove::Reorder { id: "API".to_owned(), index: 1 }) ); } } diff --git a/crates/ui/src/state/http/runner.rs b/crates/ui/src/state/http/runner.rs index 282d3c409..864bab528 100644 --- a/crates/ui/src/state/http/runner.rs +++ b/crates/ui/src/state/http/runner.rs @@ -228,9 +228,9 @@ impl Runner { /// With a data file, one iteration a row: the field says so, greyed. pub fn runs(&self) -> u32 { - self.data.as_ref().map_or(self.iterations.max(1), |file| { - u32::try_from(file.data.rows.len()).unwrap_or(u32::MAX) - }) + self.data + .as_ref() + .map_or(self.iterations.max(1), |file| u32::try_from(file.data.rows.len()).unwrap_or(u32::MAX)) } pub fn delay_ms(&self) -> u32 { @@ -344,10 +344,7 @@ impl Runner { /// « Run… » on a collection or a folder: its requests in the tree's order at once, then in /// the order last arranged, kept by Rust with the requests added since at its end. fn open(&mut self, tree: &HttpTree, target: Target) { - let same = self - .target - .as_ref() - .is_some_and(|open| open.item == target.item); + let same = self.target.as_ref().is_some_and(|open| open.item == target.item); if !same { self.rows = rows_under(tree, &target.item); self.clear_report(); @@ -363,10 +360,7 @@ impl Runner { let order = self .rows .iter() - .map(|row| RunEntry { - id: row.id.clone(), - enabled: row.enabled, - }) + .map(|row| RunEntry { id: row.id.clone(), enabled: row.enabled }) .collect(); let saved = api::http::save_run_order(backend, target.item.clone(), order); self.saving.push(saved); @@ -411,11 +405,7 @@ impl Runner { fn stop_asking(&mut self) { if self.phase == Phase::Asking { - self.phase = if self.results.is_empty() { - Phase::Idle - } else { - Phase::Done - }; + self.phase = if self.results.is_empty() { Phase::Idle } else { Phase::Done }; } } @@ -455,16 +445,8 @@ impl Runner { return; } match event.step { - RunStep::Started { - iteration, - index, - name, - } => { - self.progress = Some(Progress { - iteration, - index, - name, - }); + RunStep::Started { iteration, index, name } => { + self.progress = Some(Progress { iteration, index, name }); } RunStep::Ended { result } => { if result.failed() { @@ -472,16 +454,8 @@ impl Runner { } self.results.push(*result); } - RunStep::Finished { - cancelled, - millis, - capped, - } => { - self.ended = Some(Ended { - cancelled, - millis, - capped, - }); + RunStep::Finished { cancelled, millis, capped } => { + self.ended = Some(Ended { cancelled, millis, capped }); } } } @@ -538,10 +512,7 @@ impl Runner { .into_iter() .filter_map(|entry| { let row = known.iter().find(|row| row.id == entry.id)?; - Some(Row { - enabled: entry.enabled, - ..row.clone() - }) + Some(Row { enabled: entry.enabled, ..row.clone() }) }) .collect(); } diff --git a/crates/ui/src/state/http/send.rs b/crates/ui/src/state/http/send.rs index 7c7a621e0..9503e124e 100644 --- a/crates/ui/src/state/http/send.rs +++ b/crates/ui/src/state/http/send.rs @@ -64,13 +64,7 @@ impl Sends { } pub fn is_sending(&self, key: &str) -> bool { - matches!( - self.of(key), - Some(Sent { - phase: Phase::Sending { .. }, - .. - }) - ) + matches!(self.of(key), Some(Sent { phase: Phase::Sending { .. }, .. })) } /// Answers arrived this frame, under whatever tab now holds their send. @@ -130,11 +124,7 @@ impl Sends { let pending = api::http::send(backend, request); let previous = self.by_tab.insert( tab.key.clone(), - Sent { - id: id.clone(), - phase: Phase::Sending { started: now }, - consent, - }, + Sent { id: id.clone(), phase: Phase::Sending { started: now }, consent }, ); if let Some(previous) = previous { api::http::forget_response(backend, previous.id); diff --git a/crates/ui/src/state/http/sockets.rs b/crates/ui/src/state/http/sockets.rs index 396153b4c..364ca3473 100644 --- a/crates/ui/src/state/http/sockets.rs +++ b/crates/ui/src/state/http/sockets.rs @@ -100,19 +100,12 @@ impl Sockets { } pub fn connect(&mut self, backend: &Backend, tab: &Tab, environment_id: Option) { - if self - .phase(&tab.key) - .is_some_and(|phase| phase != Phase::Closed) - { + if self.phase(&tab.key).is_some_and(|phase| phase != Phase::Closed) { return; } self.connections += 1; let socket_id = format!("{}#{}", tab.key, self.connections); - let log = self - .by_tab - .remove(&tab.key) - .map(|state| state.log) - .unwrap_or_default(); + let log = self.by_tab.remove(&tab.key).map(|state| state.log).unwrap_or_default(); self.by_tab.insert( tab.key.clone(), SocketState { @@ -173,8 +166,7 @@ impl Sockets { if let Some(state) = self.by_tab.remove(key) && state.phase != Phase::Closed { - self.asked - .push(api::http::close_socket(backend, state.socket_id)); + self.asked.push(api::http::close_socket(backend, state.socket_id)); } } @@ -195,17 +187,9 @@ impl Sockets { state.notice = None; } SocketEvent::Closed { .. } => state.phase = Phase::Closed, - SocketEvent::Failed { - code, - params, - detail, - } => { + SocketEvent::Failed { code, params, detail } => { state.phase = Phase::Closed; - state.notice = Some(AppError { - code: *code, - params: params.clone(), - detail: detail.clone(), - }); + state.notice = Some(AppError { code: *code, params: params.clone(), detail: detail.clone() }); } SocketEvent::Sent { .. } | SocketEvent::Received { .. } => {} } diff --git a/crates/ui/src/state/http/tabs.rs b/crates/ui/src/state/http/tabs.rs index 7226ea8e8..3aa331157 100644 --- a/crates/ui/src/state/http/tabs.rs +++ b/crates/ui/src/state/http/tabs.rs @@ -9,8 +9,8 @@ use engine::http::environments::Variable; use engine::http::graphql::GraphqlDocument; use engine::http::model::{ - Extraction, HttpMethod, HttpRequest, HttpRequestDraft, HttpRequestPatch, HttpTree, KeyValue, - NewPlace, RequestAuth, RequestBody, RequestDocument, RequestKind, RequestScripts, + Extraction, HttpMethod, HttpRequest, HttpRequestDraft, HttpRequestPatch, HttpTree, KeyValue, NewPlace, + RequestAuth, RequestBody, RequestDocument, RequestKind, RequestScripts, }; use engine::http::query::QuerySide; use engine::http::transport::TransportSettings; @@ -220,11 +220,7 @@ impl Tabs { /// Once a frame while the area is shown. pub fn update(&mut self, backend: &Backend, errors: &mut ErrorNotifier) -> Answered { - let mut answered = Answered { - rekeyed: Vec::new(), - saved: false, - changed_preferences: false, - }; + let mut answered = Answered { rekeyed: Vec::new(), saved: false, changed_preferences: false }; if let Some((ids, active)) = self.to_restore.take() { let pending = api::http::requests(backend, ids); self.restoring = Some((pending, active)); @@ -274,12 +270,9 @@ impl Tabs { return true; }; match answer { - Ok(request) => saved.push(( - saving.key.clone(), - saving.sent.clone(), - request, - saving.then_close, - )), + Ok(request) => { + saved.push((saving.key.clone(), saving.sent.clone(), request, saving.then_close)); + } Err(error) => errors.report(i18n::keys::http::FAILED, &error), } false @@ -345,9 +338,7 @@ impl Tabs { pub fn unsaved_among(&self, ids: &[String]) -> Vec { self.open .iter() - .filter(|tab| { - tab.request_id.as_ref().is_some_and(|id| ids.contains(id)) && tab.is_dirty() - }) + .filter(|tab| tab.request_id.as_ref().is_some_and(|id| ids.contains(id)) && tab.is_dirty()) .map(|tab| tab.draft.name.clone()) .collect() } @@ -364,19 +355,9 @@ impl Tabs { pub fn new_request(&mut self, kind: RequestKind, name: String) { self.drafts += 1; let key = format!("draft-{}", self.drafts); - let draft = Draft { - name, - kind, - method: HttpMethod::Get, - document: RequestDocument::default(), - }; - self.open.push(Tab { - key: key.clone(), - request_id: None, - place: None, - saved: None, - draft, - }); + let draft = Draft { name, kind, method: HttpMethod::Get, document: RequestDocument::default() }; + self.open + .push(Tab { key: key.clone(), request_id: None, place: None, saved: None, draft }); self.active = Some(key); } @@ -495,10 +476,7 @@ impl Tabs { /// The answer to that question: one write for the request and what it lacks. pub fn save_to(&mut self, backend: &Backend, key: &str, target: SaveTarget) { - let then_close = self - .asking_place - .take() - .is_some_and(|(_, then_close)| then_close); + let then_close = self.asking_place.take().is_some_and(|(_, then_close)| then_close); let Some(tab) = self.find(key) else { return; }; @@ -512,14 +490,8 @@ impl Tabs { }; let create = match target.create { ToCreate::Nothing => None, - ToCreate::Collection(name) => Some(NewPlace { - collection: Some(name), - folder: None, - }), - ToCreate::Folder(name) => Some(NewPlace { - collection: None, - folder: Some(name), - }), + ToCreate::Collection(name) => Some(NewPlace { collection: Some(name), folder: None }), + ToCreate::Folder(name) => Some(NewPlace { collection: None, folder: Some(name) }), }; self.creating.push(Creating { key: key.to_owned(), @@ -577,12 +549,8 @@ impl Tabs { document: Some(draft.document.clone()), }; let pending = api::http::save_request(backend, id, patch); - self.saving.push(Saving { - key: key.to_owned(), - sent: draft, - pending, - then_close, - }); + self.saving + .push(Saving { key: key.to_owned(), sent: draft, pending, then_close }); } /// Closed at once when closing costs nothing; asked first otherwise: what was typed, or the @@ -627,10 +595,8 @@ impl Tabs { gone.push(tab.key.clone()); continue; }; - tab.place = Some(Place { - collection_id: held.collection_id.clone(), - folder_id: held.folder_id.clone(), - }); + tab.place = + Some(Place { collection_id: held.collection_id.clone(), folder_id: held.folder_id.clone() }); if saved.name != held.name { saved.name.clone_from(&held.name); tab.draft.name.clone_from(&held.name); @@ -642,11 +608,7 @@ impl Tabs { } pub fn remember(&self, preferences: &mut Preferences) { - let open: Vec<&str> = self - .open - .iter() - .filter_map(|tab| tab.request_id.as_deref()) - .collect(); + let open: Vec<&str> = self.open.iter().filter_map(|tab| tab.request_id.as_deref()).collect(); let stored = serde_json::json!({ "open": open, "active": self.active_request() }); preferences.set(TABS_KEY, &stored.to_string()); } @@ -699,10 +661,7 @@ mod tests { assert!(tabs.active().unwrap().is_dirty()); assert_eq!(tabs.active().unwrap().draft.kind, RequestKind::Websocket); - assert_eq!( - preferences.get(TABS_KEY), - Some(r#"{"open":["login"],"active":null}"#) - ); + assert_eq!(preferences.get(TABS_KEY), Some(r#"{"open":["login"],"active":null}"#)); } #[test] @@ -766,10 +725,7 @@ mod tests { tabs.move_to("c", 0); tabs.remember(&mut preferences); - assert_eq!( - preferences.get(TABS_KEY), - Some(r#"{"open":["c","a","b"],"active":"c"}"#) - ); + assert_eq!(preferences.get(TABS_KEY), Some(r#"{"open":["c","a","b"],"active":"c"}"#)); } #[test] @@ -778,14 +734,9 @@ mod tests { let mut tabs = opened(&["login", "gone"]); tabs.edit("login", |draft| draft.method = HttpMethod::Put); let mut tree = HttpTree { - collections: vec![collection( - "API", - vec![node("login", HttpMethod::Get, RequestKind::Http)], - )], + collections: vec![collection("API", vec![node("login", HttpMethod::Get, RequestKind::Http)])], }; - if let engine::http::model::HttpNode::Request { request } = - &mut tree.collections[0].children[0] - { + if let engine::http::model::HttpNode::Request { request } = &mut tree.collections[0].children[0] { request.name = "Connexion".to_owned(); } @@ -803,26 +754,15 @@ mod tests { let mut tabs = opened(&["login"]); tabs.edit("login", |draft| { - draft.apply(DraftEdit::Url( - "https://api.test/users?page=2&q=a".to_owned(), - )); + draft.apply(DraftEdit::Url("https://api.test/users?page=2&q=a".to_owned())); }); let params = &tabs.tabs()[0].draft.document.params; - assert_eq!( - params - .iter() - .map(|row| row.key.as_str()) - .collect::>(), - ["page", "q"] - ); + assert_eq!(params.iter().map(|row| row.key.as_str()).collect::>(), ["page", "q"]); let mut kept = params.clone(); kept[0].enabled = false; tabs.edit("login", |draft| draft.apply(DraftEdit::Params(kept))); - assert_eq!( - tabs.tabs()[0].draft.document.url, - "https://api.test/users?q=a" - ); + assert_eq!(tabs.tabs()[0].draft.document.url, "https://api.test/users?q=a"); assert_eq!(tabs.tabs()[0].draft.document.params.len(), 2); } @@ -831,10 +771,7 @@ mod tests { let mut preferences = Preferences::default(); preferences.set(TABS_KEY, r#"{"open":["a",3,null,"b"],"active":7}"#); - assert_eq!( - read_stored(&preferences), - (vec!["a".to_owned(), "b".to_owned()], None) - ); + assert_eq!(read_stored(&preferences), (vec!["a".to_owned(), "b".to_owned()], None)); preferences.set(TABS_KEY, "not json"); assert_eq!(read_stored(&preferences), (Vec::new(), None)); } diff --git a/crates/ui/src/state/http/tree.rs b/crates/ui/src/state/http/tree.rs index 158d5c2a3..3b77b368f 100644 --- a/crates/ui/src/state/http/tree.rs +++ b/crates/ui/src/state/http/tree.rs @@ -53,22 +53,14 @@ pub struct RailRow { /// A collection or a folder of the tree, for its settings. pub fn container_of(tree: &HttpTree, id: &str) -> Option { - fn inside( - nodes: &[HttpNode], - collection_id: &str, - parent: Option<&str>, - id: &str, - ) -> Option { + fn inside(nodes: &[HttpNode], collection_id: &str, parent: Option<&str>, id: &str) -> Option { nodes.iter().find_map(|node| { let HttpNode::Folder { folder, children } = node else { return None; }; if folder.id == id { return Some(Container { - item: HttpItem { - kind: HttpItemKind::Folder, - id: folder.id.clone(), - }, + item: HttpItem { kind: HttpItemKind::Folder, id: folder.id.clone() }, name: folder.name.clone(), collection_id: collection_id.to_owned(), folder_id: parent.map(str::to_owned), @@ -81,10 +73,7 @@ pub fn container_of(tree: &HttpTree, id: &str) -> Option { let collection = &node.collection; if collection.id == id { return Some(Container { - item: HttpItem { - kind: HttpItemKind::Collection, - id: collection.id.clone(), - }, + item: HttpItem { kind: HttpItemKind::Collection, id: collection.id.clone() }, name: collection.name.clone(), collection_id: collection.id.clone(), folder_id: None, @@ -111,12 +100,7 @@ pub fn save_places(tree: &HttpTree) -> Vec { folder_id: None, path: collection.name.clone(), }); - folders_into( - &mut places, - &node.children, - &collection.id, - &collection.name, - ); + folders_into(&mut places, &node.children, &collection.id, &collection.name); } places } @@ -153,11 +137,7 @@ pub fn rail_rows(tree: &HttpTree, collapsed: &BTreeSet) -> Vec badge: None, }); if expanded { - let at = Level { - collection_id: &collection.id, - folder_id: None, - depth: 1, - }; + let at = Level { collection_id: &collection.id, folder_id: None, depth: 1 }; walk(&mut rows, &node.children, &at, collapsed); } } @@ -216,9 +196,7 @@ pub fn find_request<'a>(tree: &'a HttpTree, id: &str) -> Option<&'a HttpRequestS HttpNode::Folder { children, .. } => walk(children, id), }) } - tree.collections - .iter() - .find_map(|node| walk(&node.children, id)) + tree.collections.iter().find_map(|node| walk(&node.children, id)) } /// Every request a deletion takes: the request itself, or all a folder or a collection holds. @@ -233,10 +211,7 @@ pub fn requests_under(tree: &HttpTree, item: &HttpItem) -> Vec { } fn folder<'a>(nodes: &'a [HttpNode], id: &str) -> Option<&'a [HttpNode]> { nodes.iter().find_map(|node| match node { - HttpNode::Folder { - folder: held, - children, - } if held.id == id => Some(children.as_slice()), + HttpNode::Folder { folder: held, children } if held.id == id => Some(children.as_slice()), HttpNode::Folder { children, .. } => folder(children, id), HttpNode::Request { .. } => None, }) @@ -245,20 +220,13 @@ pub fn requests_under(tree: &HttpTree, item: &HttpItem) -> Vec { match item.kind { HttpItemKind::Request => found.push(item.id.clone()), HttpItemKind::Folder => { - if let Some(children) = tree - .collections - .iter() - .find_map(|node| folder(&node.children, &item.id)) + if let Some(children) = tree.collections.iter().find_map(|node| folder(&node.children, &item.id)) { all(children, &mut found); } } HttpItemKind::Collection => { - if let Some(node) = tree - .collections - .iter() - .find(|node| node.collection.id == item.id) - { + if let Some(node) = tree.collections.iter().find(|node| node.collection.id == item.id) { all(&node.children, &mut found); } } @@ -318,10 +286,7 @@ pub(crate) mod tests { collections: vec![collection( "API", vec![ - folder( - "Auth", - vec![request("Login", HttpMethod::Post, RequestKind::Http)], - ), + folder("Auth", vec![request("Login", HttpMethod::Post, RequestKind::Http)]), request("Socket", HttpMethod::Get, RequestKind::Websocket), ], )], @@ -340,12 +305,7 @@ pub(crate) mod tests { assert_eq!( outline(&rows), - [ - (0, "API", None), - (1, "Auth", None), - (2, "Login", Some("Auth")), - (1, "Socket", None), - ] + [(0, "API", None), (1, "Auth", None), (2, "Login", Some("Auth")), (1, "Socket", None),] ); assert!(rows.iter().all(|row| row.collection_id == "API")); assert_eq!(rows[2].badge, Some(Badge::Method(HttpMethod::Post))); @@ -358,10 +318,7 @@ pub(crate) mod tests { let rows = rail_rows(&sample(), &collapsed); - assert_eq!( - outline(&rows), - [(0, "API", None), (1, "Auth", None), (1, "Socket", None)] - ); + assert_eq!(outline(&rows), [(0, "API", None), (1, "Auth", None), (1, "Socket", None)]); assert!(!rows[1].expanded); } @@ -375,23 +332,11 @@ pub(crate) mod tests { #[test] fn a_deletion_takes_what_its_item_holds() { let tree = sample(); - let item = |kind, id: &str| HttpItem { - kind, - id: id.to_owned(), - }; + let item = |kind, id: &str| HttpItem { kind, id: id.to_owned() }; - assert_eq!( - requests_under(&tree, &item(HttpItemKind::Folder, "Auth")), - ["Login"] - ); - assert_eq!( - requests_under(&tree, &item(HttpItemKind::Collection, "API")), - ["Login", "Socket"] - ); - assert_eq!( - find_request(&tree, "Login").map(|request| request.name.as_str()), - Some("Login") - ); + assert_eq!(requests_under(&tree, &item(HttpItemKind::Folder, "Auth")), ["Login"]); + assert_eq!(requests_under(&tree, &item(HttpItemKind::Collection, "API")), ["Login", "Socket"]); + assert_eq!(find_request(&tree, "Login").map(|request| request.name.as_str()), Some("Login")); assert!(find_request(&tree, "Auth").is_none()); } diff --git a/crates/ui/src/state/libraries.rs b/crates/ui/src/state/libraries.rs index 6fab94f4d..3eed9d6d1 100644 --- a/crates/ui/src/state/libraries.rs +++ b/crates/ui/src/state/libraries.rs @@ -43,9 +43,7 @@ impl LibrariesState { } pub fn libraries(&self) -> &[LibraryEntry] { - self.registry - .as_ref() - .map_or(&[], |registry| registry.libraries.as_slice()) + self.registry.as_ref().map_or(&[], |registry| registry.libraries.as_slice()) } pub fn is_open(&self, id: &str) -> bool { @@ -104,12 +102,7 @@ impl LibrariesState { self.goal.take() } - pub fn update( - &mut self, - backend: &Backend, - status: &mut StatusNotifier, - errors: &mut ErrorNotifier, - ) { + pub fn update(&mut self, backend: &Backend, status: &mut StatusNotifier, errors: &mut ErrorNotifier) { if let Some(answer) = self.asked.as_mut().and_then(Pending::poll) { self.asked = None; match answer { @@ -170,16 +163,13 @@ mod tests { fn settle(&mut self) { while self.libraries.is_working() || self.libraries.asked.is_some() { self.backend.settle(); - self.libraries - .update(&self.backend, &mut self.status, &mut self.errors); + self.libraries.update(&self.backend, &mut self.status, &mut self.errors); } } fn add(&mut self, name: &str) -> String { let name = name.to_owned(); - let mut made = self - .backend - .db(move |engine| engine::libraries::create_library(engine, &name)); + let mut made = self.backend.db(move |engine| engine::libraries::create_library(engine, &name)); self.backend.settle(); let id = made.poll().unwrap().unwrap().id; self.libraries.load(&self.backend); @@ -203,9 +193,7 @@ mod tests { let mut bench = Bench::new(); let id = bench.open_id(); - bench - .libraries - .rename(&bench.backend, id, "Maison".to_owned()); + bench.libraries.rename(&bench.backend, id, "Maison".to_owned()); bench.settle(); assert_eq!(bench.libraries.libraries()[0].name, "Maison"); @@ -247,9 +235,7 @@ mod tests { let mut bench = Bench::new(); let before = bench.libraries.libraries()[0].name.clone(); - bench - .libraries - .rename(&bench.backend, "gone".to_owned(), "Maison".to_owned()); + bench.libraries.rename(&bench.backend, "gone".to_owned(), "Maison".to_owned()); bench.settle(); assert!(bench.errors.notice().is_some()); diff --git a/crates/ui/src/state/mod.rs b/crates/ui/src/state/mod.rs index ba01436e2..ab24af93d 100644 --- a/crates/ui/src/state/mod.rs +++ b/crates/ui/src/state/mod.rs @@ -33,6 +33,14 @@ mod apply_http; mod apply_notes; mod apply_tools; mod apply_window; +#[cfg(test)] +pub(crate) mod held; +#[cfg(test)] +mod notes_tests; +#[cfg(test)] +mod refused_tests; +#[cfg(test)] +mod window_tests; pub use query::QueryCell; use engine::folders::board::PreviewLines; @@ -294,10 +302,7 @@ impl AppState { let offered = self.updates.offered().is_some() && self.gate.is_open(); let prompt = crate::banners::update_prompt::id(); self.dialogs.follow(ctx, Layer::Update, prompt, offered); - if self - .gate - .update(backend, &mut self.status, &mut self.errors) - { + if self.gate.update(backend, &mut self.status, &mut self.errors) { if self.gate.is_open() { self.updates.put_away(); } @@ -311,8 +316,7 @@ impl AppState { } self.adopt_library_preferences(backend); self.adopt_seeding(backend); - if self.gate.is_open() && self.library_preferences_read.is_none() && self.seeding.is_none() - { + if self.gate.is_open() && self.library_preferences_read.is_none() && self.seeding.is_none() { self.update_library(ctx, backend); } } @@ -332,28 +336,19 @@ impl AppState { self.undo.record(done, time); } self.undo.update(&mut self.revision, &mut self.errors); - if let Some(arranged) = self - .board - .write(ctx, backend, &mut self.revision, &mut self.errors) - { + if let Some(arranged) = self.board.write(ctx, backend, &mut self.revision, &mut self.errors) { self.undo.record(arranged, time); } - self.trash - .update(ctx, backend, &mut self.revision, &mut self.errors); - self.tags - .update(backend, &mut self.revision, &mut self.errors); + self.trash.update(ctx, backend, &mut self.revision, &mut self.errors); + self.tags.update(backend, &mut self.revision, &mut self.errors); let filled = self.fill.update(&mut self.revision, &mut self.errors); for (text, said) in filled.copied { self.copy_out(ctx, backend, text, said); } let pinned_first = self.settings.show_pinned_first; - self.palette.update( - ctx, - backend, - (self.clock.now(), pinned_first, self.revision), - ); - self.editor - .adopt(backend, &mut self.revision, &mut self.errors); + self.palette + .update(ctx, backend, (self.clock.now(), pinned_first, self.revision)); + self.editor.adopt(backend, &mut self.revision, &mut self.errors); self.editor.update(backend, self.revision, &mut self.errors); self.exports.update(&mut self.status, &mut self.errors); if self.attachments.wants_row() { @@ -364,17 +359,11 @@ impl AppState { errors: &mut self.errors, revision: &mut self.revision, }; - self.attachments.update( - ctx, - backend, - self.editor.open_id(), - &self.opener, - &mut reports, - ); + self.attachments + .update(ctx, backend, self.editor.open_id(), &self.opener, &mut reports); self.explored.update(backend); for saved in self.formatting.update() { - self.editor - .save_body(backend, saved.session, saved.id, saved.body); + self.editor.save_body(backend, saved.session, saved.id, saved.body); } self.presentation.update(ctx, &mut self.errors); for (note, sheet) in self.calc.update(&mut self.errors) { @@ -408,8 +397,7 @@ impl AppState { let now = self.clock.now(); let folder = self.active_folder().map(str::to_owned); let place = (self.spaces.active_space(), folder.as_deref()); - self.notes_query - .update(ctx, backend, now, place, self.revision); + self.notes_query.update(ctx, backend, now, place, self.revision); if let Some(place) = self.board_place() { let asked = (place, self.notes_query.criteria(), self.preview_lines); self.board.update(backend, now, asked, self.revision); @@ -418,8 +406,7 @@ impl AppState { /// What the bar's menus set going. fn update_menus(&mut self, ctx: &egui::Context, backend: &Backend) { - self.libraries - .update(backend, &mut self.status, &mut self.errors); + self.libraries.update(backend, &mut self.status, &mut self.errors); self.security.update(&mut self.status, &mut self.errors); self.backups.update(&mut self.errors); if self.security.take_changed() { @@ -437,8 +424,7 @@ impl AppState { revision: &mut self.revision, }; let now = self.clock.now(); - self.transfer - .update(ctx, backend, &self.dialog, now, &mut reports); + self.transfer.update(ctx, backend, &self.dialog, now, &mut reports); let asking = self.transfer.prompt().is_some(); let prompt = crate::gate::prompt::id(); self.dialogs.follow(ctx, Layer::Passphrase, prompt, asking); @@ -455,50 +441,25 @@ impl AppState { (Layer::App, "folder-name-prompt", self.folders.naming()), (Layer::Fields, "placeholder-form", self.fill.is_open()), (Layer::Palette, "palette", self.palette.is_open()), - ( - Layer::Zoom, - "image-lightbox", - self.attachments.zoomed().is_some(), - ), - ( - Layer::Presentation, - "presentation", - self.presentation.shown().is_some(), - ), - ( - Layer::App, - "http-close-dialog", - http.tabs().closing().is_some(), - ), + (Layer::Zoom, "image-lightbox", self.attachments.zoomed().is_some()), + (Layer::Presentation, "presentation", self.presentation.shown().is_some()), + (Layer::App, "http-close-dialog", http.tabs().closing().is_some()), (Layer::App, "http-code-dialog", http.code().key().is_some()), - ( - Layer::App, - "http-settings-dialog", - http.container().is_some(), - ), + (Layer::App, "http-settings-dialog", http.container().is_some()), (Layer::App, "http-cookies-dialog", http.cookies().is_open()), (Layer::App, "http-leave-dialog", http.leave().is_asking()), (Layer::App, "save-as-note", http.kept().asked().is_some()), - ( - Layer::App, - "http-save-dialog", - http.tabs().asking_place().is_some(), - ), + (Layer::App, "http-save-dialog", http.tabs().asking_place().is_some()), (Layer::App, "note-picker", self.tools_view.is_picking()), ]; for (layer, name, open) in modals { - self.dialogs - .follow(ctx, layer, egui::Id::unique(name), open); + self.dialogs.follow(ctx, layer, egui::Id::unique(name), open); } } /// The open library's preferences; a library that was never seeded is seeded now. fn adopt_library_preferences(&mut self, backend: &Backend) { - let Some(answer) = self - .library_preferences_read - .as_mut() - .and_then(Pending::poll) - else { + let Some(answer) = self.library_preferences_read.as_mut().and_then(Pending::poll) else { return; }; self.library_preferences_read = None; @@ -521,9 +482,7 @@ impl AppState { .unwrap_or_default(); self.library_preferences = preferences; } - Err(error) => self - .errors - .report(i18n::keys::errors::LIBRARY_ACTION_FAILED, &error), + Err(error) => self.errors.report(i18n::keys::errors::LIBRARY_ACTION_FAILED, &error), } } @@ -538,10 +497,7 @@ impl AppState { Ok(seeded) => { let mark = if seeded { "true" } else { "skipped" }; self.library_preferences.set(samples::SEEDED_KEY, mark); - drop(api::preferences::write_library( - backend, - self.library_preferences.clone(), - )); + drop(api::preferences::write_library(backend, self.library_preferences.clone())); self.revision.bump(); } // Silent: the canvas says its own failures, and samples nobody asked for are not @@ -711,10 +667,7 @@ impl AppState { self.settings.write(&mut self.preferences); self.tools.write(&mut self.preferences); // A write that fails says so in the log (`api::preferences`); nothing on screen waits for it. - drop(api::preferences::write_application( - backend, - self.preferences.clone(), - )); + drop(api::preferences::write_application(backend, self.preferences.clone())); } /// What reloading the page did in the reference: another library is open, so nothing of @@ -725,10 +678,7 @@ impl AppState { self.prettier = crate::notes::prettier::PrettierSettings::default(); self.preview_lines = PreviewLines::default(); // A library left for the gate has nothing to read until it is unlocked. - self.library_preferences_read = self - .gate - .is_open() - .then(|| api::preferences::library(backend)); + self.library_preferences_read = self.gate.is_open().then(|| api::preferences::library(backend)); self.seeding = None; self.presentation.close(ctx); self.caches = LibraryCaches::default(); @@ -785,13 +735,10 @@ mod tests { fn a_library_switch_reopens_its_preferences_and_keeps_the_settings() { let (backend, _profile) = testing::unlocked(); let directory = - engine::db::run_here(backend.engine(), engine::libraries::open_library_directory) - .unwrap(); + engine::db::run_here(backend.engine(), engine::libraries::open_library_directory).unwrap(); let mut library = Preferences::default(); library.set("devnotes.notes.arrangement", "board"); - library - .write(&directory.join(engine::layout::PREFERENCES)) - .unwrap(); + library.write(&directory.join(engine::layout::PREFERENCES)).unwrap(); let ctx = egui::Context::default(); let mut state = AppState::new(compact(), true); state.apply_look(&ctx); @@ -806,10 +753,7 @@ mod tests { backend.settle(); state.update(&ctx, &backend); - assert_eq!( - state.library_preferences.get("devnotes.notes.arrangement"), - Some("board") - ); + assert_eq!(state.library_preferences.get("devnotes.notes.arrangement"), Some("board")); assert_eq!(state.settings.density, Density::Compact); assert_eq!(ctx.data(|data| data.get_temp::(typed)), None); assert_eq!(theme::spacing(&ctx), &theme::tokens::COMPACT); @@ -822,8 +766,7 @@ mod tests { fn the_preview_lines_are_the_librarys() { let (backend, _profile) = testing::unlocked(); let directory = - engine::db::run_here(backend.engine(), engine::libraries::open_library_directory) - .unwrap(); + engine::db::run_here(backend.engine(), engine::libraries::open_library_directory).unwrap(); let file = directory.join(engine::layout::PREFERENCES); let mut library = Preferences::read(&file); library.set(PREVIEW_LINES_KEY, "5"); @@ -851,11 +794,7 @@ mod tests { let mut state = AppState::new(compact(), false); state.apply(Action::App(AppAction::ShowArea(Area::Http)), &ctx, &backend); - state.apply( - Action::App(AppAction::SetAppearance(Appearance::Light)), - &ctx, - &backend, - ); + state.apply(Action::App(AppAction::SetAppearance(Appearance::Light)), &ctx, &backend); backend.settle(); let written = Preferences::read(&profile.path().join(engine::layout::PREFERENCES)); diff --git a/crates/ui/src/state/note_revisions.rs b/crates/ui/src/state/note_revisions.rs index e44958f87..23de372eb 100644 --- a/crates/ui/src/state/note_revisions.rs +++ b/crates/ui/src/state/note_revisions.rs @@ -35,10 +35,7 @@ impl RevisionsState { /// The note the editor shows; `None` for a draft or a todo list, which keep no body. pub fn follow(&mut self, note: Option<&str>) { if self.note.as_deref() != note { - *self = Self { - note: note.map(str::to_owned), - ..Self::default() - }; + *self = Self { note: note.map(str::to_owned), ..Self::default() }; } } @@ -69,10 +66,9 @@ impl RevisionsState { /// The kept body `id` compared with the current text. pub fn look(&mut self, backend: &Backend, id: &str) { - let (Some(note), Some(newer)) = ( - self.note.clone(), - self.kept().iter().position(|kept| kept.id == id), - ) else { + let (Some(note), Some(newer)) = + (self.note.clone(), self.kept().iter().position(|kept| kept.id == id)) + else { return; }; let pending = api::notes::revision_diff(backend, note, id.to_owned()); @@ -98,17 +94,12 @@ impl RevisionsState { ) -> Option { if let Some(note) = &self.note { self.list.want((note.clone(), *revision)); - let answered = self - .list - .update(|(id, _)| api::notes::list_revisions(backend, id.clone())); + let answered = self.list.update(|(id, _)| api::notes::list_revisions(backend, id.clone())); if answered && let Some(error) = self.list.error() { errors.report(keys::errors::REVISIONS_LIST_FAILED, error); } } - let compared = self - .comparing - .as_mut() - .and_then(|(_, _, pending)| pending.poll()); + let compared = self.comparing.as_mut().and_then(|(_, _, pending)| pending.poll()); if let Some(answer) = compared && let Some((id, newer, _)) = self.comparing.take() { diff --git a/crates/ui/src/state/notes.rs b/crates/ui/src/state/notes.rs index d493b1569..6f9353e1a 100644 --- a/crates/ui/src/state/notes.rs +++ b/crates/ui/src/state/notes.rs @@ -38,10 +38,7 @@ pub struct Answered { impl NotesState { /// A todo list's items, the whole list: a position is all the identity an item has. pub fn set_items(&mut self, backend: &Backend, id: String, items: Vec) { - let patch = NotePatch { - items: Some(items), - ..NotePatch::default() - }; + let patch = NotePatch { items: Some(items), ..NotePatch::default() }; self.saves.push(api::notes::update(backend, id, patch)); } @@ -65,12 +62,7 @@ impl NotesState { self.writes.push((keys::errors::NOTE_MOVE_FAILED, pending)); } - pub fn move_to( - &mut self, - backend: &Backend, - (ids, to): (Vec, Destination), - lines: PreviewLines, - ) { + pub fn move_to(&mut self, backend: &Backend, (ids, to): (Vec, Destination), lines: PreviewLines) { let pending = match to { Destination::NoFolder => api::folders::file(backend, ids, None, lines), Destination::Space(space) => api::notes::move_to(backend, ids, space), @@ -81,20 +73,17 @@ impl NotesState { pub fn delete(&mut self, backend: &Backend, ids: Vec) { let pending = api::notes::delete(backend, ids); - self.writes - .push((keys::errors::NOTE_DELETE_FAILED, pending)); + self.writes.push((keys::errors::NOTE_DELETE_FAILED, pending)); } pub fn tag(&mut self, backend: &Backend, ids: Vec, tag: String) { let pending = api::notes::tag(backend, ids, tag); - self.writes - .push((keys::errors::BULK_ACTION_FAILED, pending)); + self.writes.push((keys::errors::BULK_ACTION_FAILED, pending)); } pub fn untag(&mut self, backend: &Backend, ids: Vec, tag: String) { let pending = api::notes::untag(backend, ids, tag); - self.writes - .push((keys::errors::BULK_ACTION_FAILED, pending)); + self.writes.push((keys::errors::BULK_ACTION_FAILED, pending)); } /// Into another kind: the core converts the body, the undo puts the old one back. @@ -104,8 +93,7 @@ impl NotesState { } pub fn duplicate(&mut self, backend: &Backend, id: String, title: String) { - self.duplicates - .push(api::notes::duplicate(backend, id, title)); + self.duplicates.push(api::notes::duplicate(backend, id, title)); } pub fn copy(&mut self, backend: &Backend, id: String) { @@ -115,19 +103,18 @@ impl NotesState { /// The answers that arrived: each one written moves the revision. pub fn update(&mut self, revision: &mut Revision, errors: &mut ErrorNotifier) -> Answered { let mut answered = Answered::default(); - self.writes - .retain_mut(|(failed, pending)| match pending.poll() { - None => true, - Some(Ok(done)) => { - revision.bump(); - answered.done.push(done); - false - } - Some(Err(error)) => { - errors.report(*failed, &error); - false - } - }); + self.writes.retain_mut(|(failed, pending)| match pending.poll() { + None => true, + Some(Ok(done)) => { + revision.bump(); + answered.done.push(done); + false + } + Some(Err(error)) => { + errors.report(*failed, &error); + false + } + }); let saved = |failed: Key, revision: &mut Revision, errors: &mut ErrorNotifier, @@ -144,16 +131,10 @@ impl NotesState { } } }; - self.saves.retain_mut(|pending| { - saved(keys::errors::NOTE_SAVE_FAILED, revision, errors, pending).is_none() - }); + self.saves + .retain_mut(|pending| saved(keys::errors::NOTE_SAVE_FAILED, revision, errors, pending).is_none()); self.duplicates.retain_mut(|pending| { - match saved( - keys::errors::NOTE_DUPLICATE_FAILED, - revision, - errors, - pending, - ) { + match saved(keys::errors::NOTE_DUPLICATE_FAILED, revision, errors, pending) { None => true, Some(made) => { answered.open = made.map(|note| note.id.clone()).or(answered.open.take()); diff --git a/crates/ui/src/state/notes_query.rs b/crates/ui/src/state/notes_query.rs index fc9b37caa..9555ec7a0 100644 --- a/crates/ui/src/state/notes_query.rs +++ b/crates/ui/src/state/notes_query.rs @@ -9,9 +9,7 @@ use engine::error::AppError; use engine::notes::kind::NoteKind; use engine::notes::language::Language; use engine::notes::priority::Priority; -use engine::notes::view::{ - Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey, -}; +use engine::notes::view::{Grouping, NoteFilter, NoteOrder, NotesQuery, NotesView, SortDirection, SortKey}; use serde_json::{Value, json}; use super::{QueryCell, Revision}; @@ -28,20 +26,10 @@ pub(super) fn debounce() -> f64 { f64::from(crate::theme::motion::TYPING) } -pub const SORT_KEYS: [SortKey; 5] = [ - SortKey::Modified, - SortKey::Created, - SortKey::Priority, - SortKey::Format, - SortKey::Title, -]; +pub const SORT_KEYS: [SortKey; 5] = + [SortKey::Modified, SortKey::Created, SortKey::Priority, SortKey::Format, SortKey::Title]; pub const DIRECTIONS: [SortDirection; 2] = [SortDirection::Descending, SortDirection::Ascending]; -pub const GROUPINGS: [Grouping; 4] = [ - Grouping::Date, - Grouping::Priority, - Grouping::Format, - Grouping::None, -]; +pub const GROUPINGS: [Grouping; 4] = [Grouping::Date, Grouping::Priority, Grouping::Format, Grouping::None]; /// How the list view is laid out: the library's choice, remembered between launches. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -53,11 +41,7 @@ pub struct Arrangement { impl Default for Arrangement { fn default() -> Self { - Self { - order: natural_order(SortKey::Modified), - grouping: Grouping::Date, - pinned_first: true, - } + Self { order: natural_order(SortKey::Modified), grouping: Grouping::Date, pinned_first: true } } } @@ -83,20 +67,16 @@ impl Arrangement { }; Self { order: NoteOrder { - key: pick(&stored["order"]["key"], &SORT_KEYS, key_name) - .unwrap_or(fallback.order.key), + key: pick(&stored["order"]["key"], &SORT_KEYS, key_name).unwrap_or(fallback.order.key), direction: pick(&stored["order"]["direction"], &DIRECTIONS, direction_name) .unwrap_or(fallback.order.direction), }, - grouping: pick(&stored["grouping"], &GROUPINGS, grouping_name) - .unwrap_or(fallback.grouping), - pinned_first: stored["pinnedFirst"] - .as_bool() - .unwrap_or(fallback.pinned_first), + grouping: pick(&stored["grouping"], &GROUPINGS, grouping_name).unwrap_or(fallback.grouping), + pinned_first: stored["pinnedFirst"].as_bool().unwrap_or(fallback.pinned_first), } } - pub fn write(&self, preferences: &mut Preferences) { + pub fn write(self, preferences: &mut Preferences) { let stored = json!({ "order": { "key": key_name(self.order.key), @@ -184,11 +164,7 @@ pub struct Criteria { impl Default for Criteria { fn default() -> Self { - Self { - search: String::new(), - filter: NoteFilter::All, - facets: Facets::default(), - } + Self { search: String::new(), filter: NoteFilter::All, facets: Facets::default() } } } @@ -270,8 +246,7 @@ impl NotesQueryState { day: local.date_naive(), revision, }); - self.cell - .update(|params| api::notes::query(backend, query(¶ms, now))) + self.cell.update(|params| api::notes::query(backend, query(¶ms, now))) } /// What was typed, the moment it is typed; asked of the core once the keys rest. @@ -331,11 +306,7 @@ impl NotesQueryState { } pub fn criteria(&self) -> Criteria { - Criteria { - search: self.search.clone(), - filter: self.filter, - facets: self.facets.clone(), - } + Criteria { search: self.search.clone(), filter: self.filter, facets: self.facets.clone() } } pub fn set_filter(&mut self, filter: NoteFilter) { @@ -356,15 +327,14 @@ impl NotesQueryState { /// How many notes a filter leaves; `None` while nothing is filtered. pub fn matched(&self) -> Option { - self.view() - .filter(|view| view.is_filtering) - .map(|view| view.matched) + self.view().filter(|view| view.is_filtering).map(|view| view.matched) } pub fn error(&self) -> Option<&AppError> { self.cell.error() } + #[cfg(test)] pub fn is_loading(&self) -> bool { self.cell.is_loading() } @@ -397,11 +367,7 @@ fn toggle(set: &mut BTreeSet, value: T) { /// `Date#getTimezoneOffset()`'s sign, which the core reads: −120 for UTC+2. pub(crate) fn tz_offset_minutes(now: DateTime) -> i32 { - -Local - .offset_from_utc_datetime(&now.naive_utc()) - .fix() - .local_minus_utc() - / 60 + -Local.offset_from_utc_datetime(&now.naive_utc()).fix().local_minus_utc() / 60 } /// « Today » becomes « this week » at the next local midnight, when nothing else may repaint. @@ -424,8 +390,7 @@ mod tests { fn settled(state: &mut NotesQueryState, backend: &Backend, revision: Revision) { let ctx = egui::Context::default(); let now = Utc::now(); - let update = - |state: &mut NotesQueryState| state.update(&ctx, backend, now, (None, None), revision); + let update = |state: &mut NotesQueryState| state.update(&ctx, backend, now, (None, None), revision); update(state); backend.settle(); update(state); @@ -476,10 +441,7 @@ mod tests { fn an_arrangement_survives_its_file_and_a_damaged_one_reads_as_the_default() { let mut preferences = Preferences::default(); let chosen = Arrangement { - order: NoteOrder { - key: SortKey::Title, - direction: SortDirection::Ascending, - }, + order: NoteOrder { key: SortKey::Title, direction: SortDirection::Ascending }, grouping: Grouping::None, pinned_first: false, }; @@ -487,10 +449,7 @@ mod tests { chosen.write(&mut preferences); assert_eq!(Arrangement::read(&preferences), chosen); - preferences.set( - ARRANGEMENT_KEY, - r#"{"grouping":"kind","pinnedFirst":"yes"}"#, - ); + preferences.set(ARRANGEMENT_KEY, r#"{"grouping":"kind","pinnedFirst":"yes"}"#); assert_eq!(Arrangement::read(&preferences), Arrangement::default()); } diff --git a/crates/ui/src/state/notes_tests.rs b/crates/ui/src/state/notes_tests.rs new file mode 100644 index 000000000..b0113a1e1 --- /dev/null +++ b/crates/ui/src/state/notes_tests.rs @@ -0,0 +1,599 @@ +//! The notes' state as the actions change it, without a window. + +use engine::folders::board::BoardFrame; +use engine::folders::model::Folder; +use engine::notes::kind::NoteKind; +use engine::notes::language::Language; +use engine::notes::model::{HeldNotes, NoteLifecycle}; +use engine::notes::priority::Priority; + +use super::held::{Held, held}; +use crate::action::Action; +use crate::notes::canvas::grid::Direction; +use crate::notes::canvas::shortcuts::CanvasKey; +use crate::notes::{Action as Notes, Batch, BoardGesture, Editing, Tags, Trash, bench}; +use crate::state::board::Mode; +use crate::state::editor::{Body, Edit}; +use crate::state::folders::ACTIVE_FOLDER_KEY; +use crate::state::notes_query::Facet; +use crate::testing; + +/// Notes of those titles in one space. +fn with_notes(titles: &[&str]) -> (Held, Vec) { + let (backend, profile) = testing::unlocked(); + let ids = titles.iter().map(|title| testing::note(&backend, title).id.clone()).collect(); + (held((backend, profile)), ids) +} + +/// A folder `a` holding `b` holding `c`. +fn nested() -> (Held, [Folder; 3]) { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let a = bench::folder(&backend, &space, None, "a"); + let b = bench::folder(&backend, &space, Some(&a), "b"); + let c = bench::folder(&backend, &space, Some(&b), "c"); + (held((backend, profile)), [a, b, c]) +} + +fn focus(held: &mut Held, id: &str) { + held.state.notes_view.canvas.focused = Some(id.to_owned()); +} + +// The keys of the canvas + +#[test] +fn a_key_of_the_canvas_acts_on_the_card_with_the_focus() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + + held.key(CanvasKey::Pin); + assert!(held.note(&ids[0]).pinned && !held.note(&ids[1]).pinned); + held.key(CanvasKey::Pin); + assert!(!held.note(&ids[0]).pinned); + held.key(CanvasKey::Priority(Priority::High)); + assert_eq!(held.note(&ids[0]).priority, Priority::High); + held.key(CanvasKey::Check); + assert!(held.state.selection.is_checked(&ids[0])); + held.key(CanvasKey::Copy); + assert!(held.done().unwrap().contains("psql"), "{:?}", held.done()); +} + +#[test] +fn without_a_card_in_focus_the_keys_that_need_one_do_nothing() { + let (mut held, ids) = with_notes(&["psql"]); + for key in [ + CanvasKey::Pin, + CanvasKey::Priority(Priority::High), + CanvasKey::Check, + CanvasKey::Copy, + CanvasKey::Trash, + ] { + held.key(key); + } + + let note = held.note(&ids[0]); + assert!(!note.pinned && note.priority == Priority::None); + assert!(!held.state.selection.is_checked(&ids[0])); + assert_eq!(held.done(), None); +} + +/// The focused card can be scrolled out of view: it takes two. +#[test] +fn the_key_of_the_trash_is_pressed_twice() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + + held.key(CanvasKey::Trash); + assert_eq!(held.shown().len(), 2); + held.key(CanvasKey::Trash); + assert_eq!(held.shown(), ["curl"]); +} + +#[test] +fn the_focus_moves_from_card_to_card_as_they_are_shown() { + let (mut held, _) = with_notes(&["one", "two", "three"]); + let order = held.state.on_screen(); + focus(&mut held, &order[0]); + + held.key(CanvasKey::Move(Direction::Next)); + assert_eq!(held.state.notes_view.canvas.request.as_ref(), Some(&order[1])); +} + +#[test] +fn on_the_board_the_focus_walks_the_cards_one_by_one() { + let (mut held, ids) = with_notes(&["one", "two"]); + let space = held.note(&ids[0]).space_id.clone(); + held.notes(Notes::ChooseSpace(Some(space))); + held.notes(Notes::SetView(Mode::Board)); + let order = held.state.on_screen(); + assert_eq!(order.len(), 2); + focus(&mut held, &order[0]); + + held.key(CanvasKey::Move(Direction::Down)); + assert_eq!(held.state.notes_view.canvas.request.as_ref(), Some(&order[1])); + held.key(CanvasKey::Pin); + assert!(held.note(&order[0]).pinned, "read from the board's cards"); + held.key(CanvasKey::Pin); + assert!(!held.note(&order[0]).pinned); +} + +#[test] +fn the_key_of_undo_puts_the_last_write_back_once_its_bar_is_gone() { + let (mut held, ids) = with_notes(&["psql"]); + held.notes(Notes::Pin { id: ids[0].clone(), pinned: true }); + assert!(held.state.undo.banner(1e9).is_none()); + + held.key(CanvasKey::Undo); + assert!(!held.note(&ids[0]).pinned); +} + +// Escape + +#[test] +fn escape_goes_down_one_rung_at_a_time() { + let (mut held, ids) = with_notes(&["psql", "curl"]); + focus(&mut held, &ids[0]); + held.notes(Notes::SetFilter(engine::notes::view::NoteFilter::Pinned)); + held.notes(Notes::SetFilter(engine::notes::view::NoteFilter::All)); + held.notes(Notes::Facet(Facet::Kind(NoteKind::Snippet))); + held.notes(Notes::Check(ids[1].clone())); + held.key(CanvasKey::Trash); + + held.key(CanvasKey::StepBack); + assert!(held.state.selection.is_checked(&ids[1]), "what is armed first"); + held.key(CanvasKey::StepBack); + assert!(!held.state.selection.is_checked(&ids[1]), "then the selection"); + assert!(held.state.notes_query.has_user_filters()); + held.key(CanvasKey::StepBack); + assert!(!held.state.notes_query.has_user_filters(), "then the search"); +} + +#[test] +fn escape_climbs_the_folders_to_their_space_and_no_further() { + let (mut held, [a, b, c]) = nested(); + held.notes(Notes::ChooseFolder(c.id.clone())); + + for shown in [Some(&b.id), Some(&a.id), None, None] { + held.key(CanvasKey::StepBack); + assert_eq!(held.state.active_folder(), shown.map(String::as_str)); + } + assert_eq!(held.state.spaces.active_space(), Some(a.space_id.as_str())); +} + +#[test] +fn escape_takes_back_what_the_bar_offers_while_it_is_there() { + let (mut held, ids) = with_notes(&["psql"]); + held.notes(Notes::Pin { id: ids[0].clone(), pinned: true }); + + held.key(CanvasKey::StepBack); + assert!(!held.note(&ids[0]).pinned); +} + +// The selection + +#[test] +fn each_batch_acts_on_the_notes_ticked_and_on_no_other() { + let (mut held, ids) = with_notes(&["one", "two", "three"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Check(ids[1].clone())); + + held.notes(Notes::Batch(Batch::Prioritise(Priority::Urgent))); + held.notes(Notes::Batch(Batch::Tag("ops".to_owned()))); + held.notes(Notes::Batch(Batch::Pin(true))); + for (id, ticked) in [(&ids[0], true), (&ids[1], true), (&ids[2], false)] { + let note = held.note(id); + assert_eq!(note.priority == Priority::Urgent, ticked); + assert_eq!(note.tags == ["ops"], ticked); + assert_eq!(note.pinned, ticked); + } + held.notes(Notes::Batch(Batch::Untag("ops".to_owned()))); + assert!(held.note(&ids[0]).tags.is_empty()); +} + +#[test] +fn a_batch_on_nothing_asks_nothing() { + let (mut held, ids) = with_notes(&["one"]); + held.notes(Notes::Batch(Batch::Delete)); + + assert_eq!(held.shown(), ["one"]); + assert!(!held.note(&ids[0]).pinned); + assert!(held.state.undo.last().is_none()); +} + +#[test] +fn the_notes_deleted_together_are_ticked_no_more() { + let (mut held, ids) = with_notes(&["one", "two"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Batch(Batch::Delete)); + + assert_eq!(held.shown(), ["two"]); + assert!(!held.state.selection.is_checked(&ids[0])); +} + +// Where a note goes + +#[test] +fn a_new_note_goes_where_the_person_is_looking() { + let (mut held, [a, ..]) = nested(); + held.notes(Notes::ChooseFolder(a.id.clone())); + held.notes(Notes::NewNote(None)); + + let draft = held.state.editor.opened().unwrap().note().unwrap(); + assert_eq!((&draft.space_id, draft.folder_id.as_ref()), (&a.space_id, Some(&a.id))); + assert_eq!(draft.kind, held.state.settings.default_note_kind); +} + +#[test] +fn over_all_the_spaces_a_new_note_goes_to_the_first() { + let (mut held, [a, ..]) = nested(); + held.notes(Notes::ChooseSpace(None)); + held.notes(Notes::NewNote(Some(NoteKind::Calc))); + + let draft = held.state.editor.opened().unwrap().note().unwrap(); + assert_eq!((&draft.space_id, &draft.folder_id), (&a.space_id, &None)); + assert_eq!(draft.kind, NoteKind::Calc); +} + +#[test] +fn without_a_space_a_new_note_is_refused_and_said() { + let mut held = held(testing::unlocked()); + for action in [Notes::NewNote(None), Notes::Canvas(CanvasKey::New(NoteKind::Note))] { + held.notes(action); + assert!(!held.state.editor.is_open()); + } + + let said = held.state.errors.notice().unwrap().key; + assert_eq!(said, i18n::keys::errors::SPACE_REQUIRED); +} + +// The note being written + +/// A draft has no row until its first write is answered: what is left meanwhile waits for it. +#[test] +fn every_field_left_while_a_note_is_first_written_goes_with_it() { + let (backend, profile) = testing::unlocked(); + bench::space(&backend, "Home"); + let mut held = held((backend, profile)); + held.notes(Notes::NewNote(Some(NoteKind::Snippet))); + let session = held.state.editor.opened().unwrap().session; + let at = chrono::DateTime::from_timestamp(4_000_000_000, 0).unwrap(); + for edit in [ + Edit { title: Some("psql".to_owned()), ..Edit::default() }, + Edit { + source: Some("the wiki".to_owned()), + body: Some(Body::Content("select 1".to_owned())), + tags: Some(vec!["db".to_owned()]), + lifecycle: Some(NoteLifecycle::Expires { at }), + language: Some(Language::Sql), + ..Edit::default() + }, + Edit { title: Some("psql, at last".to_owned()), ..Edit::default() }, + ] { + let save = Action::Notes(Notes::Editor(Editing::Save { session, edit })); + held.state.apply(save, &held.ctx, &held.backend); + } + held.settle(); + + let note = held.note(held.state.editor.open_id().unwrap()); + assert_eq!((note.title.as_str(), note.source.as_str()), ("psql, at last", "the wiki")); + assert_eq!((note.content.as_str(), ¬e.tags), ("select 1", &vec!["db".to_owned()])); + assert_eq!(note.lifecycle, NoteLifecycle::Expires { at }); + assert_eq!(note.language, Language::Sql); +} + +#[test] +fn a_body_formatted_is_awaited_until_its_answer_and_no_longer() { + let (mut held, ids) = with_notes(&["psql"]); + held.notes(Notes::OpenNote(ids[0].clone())); + let session = held.state.editor.opened().unwrap().session; + let request = text::format::Request { + text: "{\"a\":1}".to_owned(), + cursor: 0, + parser: text::format::Parser::Json, + options: text::format::Options { + print_width: 80, + tab_width: 2, + use_tabs: false, + single_quote: false, + semi: true, + trailing_comma: true, + }, + }; + let format = Action::Notes(Notes::Editor(Editing::Format { session, request })); + held.state.apply(format, &held.ctx, &held.backend); + assert!(held.state.formatting.busy(session)); + assert!(!held.state.formatting.busy(session + 1), "another opening waits for nothing"); + + held.settle(); + assert!(!held.state.formatting.busy(session)); + assert!(held.state.formatting.answered(session).is_some()); +} + +// Folders + +/// The rail sorts them by name, whatever was made first. +#[test] +fn a_folder_goes_into_the_one_above_it_on_the_rail() { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let zebra = bench::folder(&backend, &space, None, "Zebra"); + let apple = bench::folder(&backend, &space, None, "apple"); + let mut held = held((backend, profile)); + + held.notes(Notes::NudgeFolder { id: apple.id.clone(), outwards: false }); + let refused = i18n::keys::sidebar::moved::refused::NO_FOLDER_ABOVE; + assert_eq!(held.state.status.latest().unwrap().1.key, refused); + held.notes(Notes::NudgeFolder { id: zebra.id.clone(), outwards: false }); + assert_eq!(held.state.folders.find(&zebra.id).unwrap().parent_id, Some(apple.id)); +} + +#[test] +fn the_open_folder_deleted_leaves_its_parent_open_and_the_next_launch_too() { + let (mut held, [_, b, c]) = nested(); + held.notes(Notes::ChooseFolder(c.id.clone())); + held.notes(Notes::DeleteFolder { id: c.id, held: HeldNotes::Keep }); + + assert_eq!(held.state.active_folder(), Some(b.id.as_str())); + assert_eq!(held.state.library_preferences.get(ACTIVE_FOLDER_KEY), Some(b.id.as_str())); +} + +#[test] +fn a_folder_takes_a_name_used_elsewhere_and_its_own_writes_nothing() { + let (mut held, [a, _, c]) = nested(); + held.notes(Notes::RenameFolder { id: c.id.clone(), name: a.name.clone() }); + assert_eq!(held.state.folders.find(&c.id).unwrap().name, a.name); + + for name in [a.name.clone(), format!(" {} ", a.name), " ".to_owned()] { + let before = held.backend.launched(); + held.notes(Notes::RenameFolder { id: c.id.clone(), name }); + assert_eq!(held.backend.launched(), before); + } +} + +#[test] +fn what_one_folder_holds_is_never_shown_for_another() { + let (mut held, [a, b, _]) = nested(); + held.notes(Notes::CountFolder(a.id.clone())); + assert!(held.state.folders.contents(&a.id).is_some()); + + let count = Action::Notes(Notes::CountFolder(b.id.clone())); + held.state.apply(count, &held.ctx, &held.backend); + assert!(held.state.folders.contents(&b.id).is_none(), "not read yet"); + held.settle(); + assert!(held.state.folders.contents(&b.id).is_some()); +} + +#[test] +fn a_folder_is_nudged_out_a_level_and_into_the_one_above_it() { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let first = bench::folder(&backend, &space, None, "First"); + let second = bench::folder(&backend, &space, None, "Second"); + let mut held = held((backend, profile)); + let parent = |held: &Held| held.state.folders.find(&second.id).unwrap().parent_id.clone(); + + held.notes(Notes::NudgeFolder { id: second.id.clone(), outwards: false }); + assert_eq!(parent(&held), Some(first.id.clone())); + held.notes(Notes::NudgeFolder { id: second.id.clone(), outwards: true }); + assert_eq!(parent(&held), None); +} + +#[test] +fn a_nudge_with_nowhere_to_go_is_said() { + use i18n::keys::sidebar::moved::refused; + let (mut held, [a, ..]) = nested(); + + held.notes(Notes::NudgeFolder { id: a.id.clone(), outwards: true }); + assert_eq!(held.state.status.latest().unwrap().1.key, refused::AT_TOP); + held.notes(Notes::NudgeFolder { id: a.id.clone(), outwards: false }); + assert_eq!(held.state.status.latest().unwrap().1.key, refused::NO_FOLDER_ABOVE); +} + +#[test] +fn a_folder_that_cannot_go_there_is_refused_and_said() { + use i18n::keys::sidebar::moved; + let (mut held, [a, b, c]) = nested(); + for (id, parent, said) in [ + (&b.id, Some(a.id.clone()), moved::ALREADY), + (&a.id, None, moved::ALREADY), + (&a.id, Some(c.id.clone()), moved::refused::THERE), + (&a.id, Some(a.id.clone()), moved::refused::THERE), + ] { + held.notes(Notes::MoveFolder { id: id.clone(), parent, space: a.space_id.clone() }); + assert_eq!(held.state.status.latest().unwrap().1.key, said); + assert_eq!(held.failed(), None); + } +} + +#[test] +fn what_is_asked_of_a_folder_that_is_gone_does_nothing() { + let (mut held, [a, ..]) = nested(); + let gone = "gone".to_owned(); + held.notes(Notes::MoveFolder { id: gone.clone(), parent: None, space: a.space_id.clone() }); + held.notes(Notes::NudgeFolder { id: gone.clone(), outwards: true }); + held.notes(Notes::ChooseFolder(gone)); + + assert_eq!((held.done(), held.failed()), (None, None)); + assert_eq!(held.state.active_folder(), None); +} + +// The board + +/// There is no board across every space. +#[test] +fn over_all_the_spaces_there_is_no_board() { + let (mut held, _) = with_notes(&["one"]); + held.notes(Notes::ChooseSpace(None)); + held.notes(Notes::SetView(Mode::Board)); + held.notes(Notes::Board(BoardGesture::DrawZone(BoardFrame { x: 0, y: 0, width: 200, height: 200 }))); + + assert!(held.state.board_place().is_none()); + assert!(held.state.board.drawn_zone().is_none()); +} + +#[test] +fn a_zone_is_made_once_it_is_named() { + let (mut held, ids) = with_notes(&["one"]); + let space = held.note(&ids[0]).space_id.clone(); + held.notes(Notes::ChooseSpace(Some(space))); + held.notes(Notes::SetView(Mode::Board)); + let frame = BoardFrame { x: 0, y: 0, width: 240, height: 200 }; + + held.notes(Notes::Board(BoardGesture::DrawZone(frame))); + assert_eq!(held.state.board.drawn_zone(), Some(frame)); + held.notes(Notes::NameZone(" ".to_owned())); + assert!(held.state.folders.list().is_empty(), "a name of spaces is none"); + held.notes(Notes::Board(BoardGesture::DrawZone(frame))); + held.notes(Notes::NameZone(" Scripts ".to_owned())); + let names: Vec<&str> = held.state.folders.list().iter().map(|folder| folder.name.as_str()).collect(); + assert_eq!(names, ["Scripts"]); +} + +// The tags + +fn tagged() -> (Held, Vec) { + let (mut held, ids) = with_notes(&["one", "two"]); + held.notes(Notes::Check(ids[0].clone())); + held.notes(Notes::Batch(Batch::Tag("db".to_owned()))); + held.notes(Notes::ClearSelection); + held.notes(Notes::Check(ids[1].clone())); + held.notes(Notes::Batch(Batch::Tag("ops".to_owned()))); + held.notes(Notes::Tags(Tags::Open)); + (held, ids) +} + +fn tick(held: &mut Held, tag: &str) { + held.notes(Notes::Tags(Tags::Toggle(tag.to_owned()))); +} + +/// One ticked is renamed, several are merged, and nothing is done before it is confirmed. +#[test] +fn a_change_of_tags_is_proposed_with_its_count_then_confirmed() { + use crate::state::tags::ChangeKind; + let (mut held, ids) = tagged(); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Rename(" base ".to_owned()))); + let pending = held.state.tags.pending().unwrap(); + assert_eq!((pending.kind, pending.notes, pending.into.as_str()), (ChangeKind::Rename, 1, "base")); + assert_eq!(held.note(&ids[0]).tags, ["db"]); + + tick(&mut held, "ops"); + assert!(held.state.tags.pending().is_none(), "another selection withdraws it"); + held.notes(Notes::Tags(Tags::Rename("base".to_owned()))); + let pending = held.state.tags.pending().unwrap(); + assert_eq!((pending.kind, pending.notes), (ChangeKind::Merge, 2)); + held.notes(Notes::Tags(Tags::Confirm)); + assert_eq!([held.note(&ids[0]).tags.clone(), held.note(&ids[1]).tags.clone()], [["base"], ["base"]]); +} + +#[test] +fn tags_are_deleted_from_their_notes_once_confirmed() { + let (mut held, ids) = tagged(); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Cancel)); + held.notes(Notes::Tags(Tags::Confirm)); + assert_eq!(held.note(&ids[0]).tags, ["db"], "cancelled"); + + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Confirm)); + assert!(held.note(&ids[0]).tags.is_empty()); + assert_eq!(held.note(&ids[1]).tags, ["ops"]); +} + +#[test] +fn with_nothing_ticked_or_no_name_nothing_is_proposed() { + let (mut held, _) = tagged(); + held.notes(Notes::Tags(Tags::Delete)); + held.notes(Notes::Tags(Tags::Rename("x".to_owned()))); + tick(&mut held, "db"); + held.notes(Notes::Tags(Tags::Rename(" ".to_owned()))); + + assert!(held.state.tags.pending().is_none()); +} + +#[test] +fn the_tags_opened_again_have_nothing_ticked() { + let (mut held, _) = tagged(); + tick(&mut held, "db"); + tick(&mut held, "ops"); + tick(&mut held, "ops"); + assert_eq!(held.state.tags.selected(), 1); + held.notes(Notes::Tags(Tags::Close)); + assert!(!held.state.tags.is_open()); + + held.notes(Notes::Tags(Tags::Open)); + assert_eq!(held.state.tags.selected(), 0); + assert_eq!(held.state.tags.tags().len(), 2); +} + +// The trash + +#[test] +fn the_trash_gives_back_what_was_asked_and_for_good_takes_the_rest() { + let (mut held, ids) = with_notes(&["one", "two", "three"]); + for id in &ids { + held.notes(Notes::Delete(id.clone())); + } + held.notes(Notes::Trash(Trash::Open)); + assert_eq!(held.state.trash.notes().len(), 3); + + held.notes(Notes::Trash(Trash::Restore(ids[0].clone()))); + held.notes(Notes::Trash(Trash::Purge(ids[1].clone()))); + assert_eq!(held.shown(), ["one"]); + assert_eq!(held.state.trash.notes().len(), 1); + held.notes(Notes::Trash(Trash::Empty)); + assert!(held.state.trash.notes().is_empty()); +} + +#[test] +fn everything_found_is_given_back_together() { + let (mut held, ids) = with_notes(&["psql one", "psql two", "curl"]); + for id in &ids { + held.notes(Notes::Delete(id.clone())); + } + held.notes(Notes::Trash(Trash::Open)); + held.notes(Notes::Trash(Trash::Search(" psql ".to_owned()))); + assert!(held.state.trash.searching()); + held.notes(Notes::Trash(Trash::RestoreAll)); + + let mut shown = held.shown(); + shown.sort(); + assert_eq!(shown, ["psql one", "psql two"]); +} + +#[test] +fn the_trash_opened_again_searches_nothing() { + let (mut held, _) = with_notes(&["one"]); + held.notes(Notes::Trash(Trash::Open)); + held.notes(Notes::Trash(Trash::Search("psql".to_owned()))); + held.notes(Notes::Trash(Trash::Close)); + assert!(!held.state.trash.is_open()); + + held.notes(Notes::Trash(Trash::Open)); + assert_eq!(held.state.trash.search(), ""); +} + +// The facets + +#[test] +fn each_facet_is_pressed_then_let_go_and_all_of_a_kind_at_once() { + let (mut held, _) = with_notes(&["one"]); + let pressed = |held: &Held| held.state.notes_query.facets().count(); + for (each, all) in [ + (vec![Facet::Tag("db".to_owned()), Facet::Tag("ops".to_owned())], Facet::AllTags), + (vec![Facet::Language(Language::Sql), Facet::Language(Language::Rs)], Facet::AllLanguages), + (vec![Facet::Kind(NoteKind::Note), Facet::Kind(NoteKind::Calc)], Facet::AllKinds), + (vec![Facet::Priority(Priority::Low), Facet::Priority(Priority::High)], Facet::AllPriorities), + ] { + for facet in &each { + held.notes(Notes::Facet(facet.clone())); + } + assert_eq!(pressed(&held), 2, "{all:?}"); + held.notes(Notes::Facet(each[0].clone())); + assert_eq!(pressed(&held), 1, "{all:?}: pressed again, let go"); + held.notes(Notes::Facet(all)); + assert_eq!(pressed(&held), 0); + } + assert!(!held.state.notes_query.has_user_filters()); +} diff --git a/crates/ui/src/state/palette.rs b/crates/ui/src/state/palette.rs index 56f9a0647..a894978c3 100644 --- a/crates/ui/src/state/palette.rs +++ b/crates/ui/src/state/palette.rs @@ -93,7 +93,7 @@ impl PaletteState { self.open } - pub fn from_elsewhere(&self) -> bool { + pub fn is_from_elsewhere(&self) -> bool { self.from_elsewhere } @@ -128,10 +128,7 @@ impl PaletteState { _ => None, }) .collect(); - let narrowed = self - .chips - .iter() - .any(|chip| !matches!(chip, Chip::Scope(_))); + let narrowed = self.chips.iter().any(|chip| !matches!(chip, Chip::Scope(_))); if scoped.is_empty() && !narrowed { return true; } @@ -147,10 +144,7 @@ impl PaletteState { /// The requests found, ranked; none while a list of chips is offered. pub fn requests(&self) -> &[RequestHit] { let wanted = matches!(self.mode(), Mode::Search(_)) && self.searched(Scope::Requests); - self.requests - .value() - .filter(|_| wanted) - .map_or(&[], Vec::as_slice) + self.requests.value().filter(|_| wanted).map_or(&[], Vec::as_slice) } /// Opens on the recent notes: reopening without typing has a meaning. @@ -181,8 +175,7 @@ impl PaletteState { /// The word that asked for it leaves the field. A second space takes the place of the first. pub fn add_chip(&mut self, chip: Chip) { self.chips.retain(|other| { - other != &chip - && !(matches!(chip, Chip::Space { .. }) && matches!(other, Chip::Space { .. })) + other != &chip && !(matches!(chip, Chip::Space { .. }) && matches!(other, Chip::Space { .. })) }); self.chips.push(chip); let kept = match self.text.rfind(char::is_whitespace) { @@ -245,20 +238,13 @@ impl PaletteState { _ => None, }) .collect(); - self.cell.want(Params { - term: self.term.clone(), - space, - tags, - pinned_first, - revision, - }); self.cell - .update(|params| api::notes::query(backend, query(¶ms, now))); + .want(Params { term: self.term.clone(), space, tags, pinned_first, revision }); + self.cell.update(|params| api::notes::query(backend, query(¶ms, now))); if matches!(self.mode(), Mode::Search(_)) && self.searched(Scope::Requests) { self.requests.want((self.term.clone(), revision)); } - self.requests - .update(|(term, _)| api::http::search_requests(backend, term)); + self.requests.update(|(term, _)| api::http::search_requests(backend, term)); } } @@ -303,10 +289,7 @@ mod tests { #[test] fn a_chip_takes_the_word_that_asked_for_it_and_narrows_to_notes() { - let mut palette = PaletteState { - text: "reset #op".into(), - ..PaletteState::default() - }; + let mut palette = PaletteState { text: "reset #op".into(), ..PaletteState::default() }; palette.add_chip(Chip::Tag("ops".into())); assert_eq!(palette.text(), "reset"); @@ -317,10 +300,7 @@ mod tests { #[test] fn a_second_space_takes_the_first_one_s_place() { let mut palette = PaletteState::default(); - let space = |id: &str| Chip::Space { - id: id.into(), - name: id.into(), - }; + let space = |id: &str| Chip::Space { id: id.into(), name: id.into() }; palette.add_chip(space("a")); palette.add_chip(space("b")); diff --git a/crates/ui/src/state/placeholder_fill.rs b/crates/ui/src/state/placeholder_fill.rs index 04f15864b..8a9c77ee4 100644 --- a/crates/ui/src/state/placeholder_fill.rs +++ b/crates/ui/src/state/placeholder_fill.rs @@ -51,16 +51,10 @@ impl FillState { Fill::Cancel => None, Fill::Raw => Some((note.content.clone(), copied_note(¬e))), Fill::Submit(values) => { - self.filling.push(api::notes::fill( - backend, - note.content.clone(), - values.clone(), - )); - self.keeping.push(api::notes::set_field_values( - backend, - note.id.clone(), - values, - )); + self.filling + .push(api::notes::fill(backend, note.content.clone(), values.clone())); + self.keeping + .push(api::notes::set_field_values(backend, note.id.clone(), values)); None } } @@ -68,13 +62,11 @@ impl FillState { /// The editor's panel: what it holds is written, its filled text copied or shown. pub fn keep(&mut self, backend: &Backend, id: String, values: BTreeMap) { - self.keeping - .push(api::notes::set_field_values(backend, id, values)); + self.keeping.push(api::notes::set_field_values(backend, id, values)); } pub fn copy(&mut self, backend: &Backend, content: String, values: BTreeMap) { - self.filling - .push(api::notes::fill(backend, content, values)); + self.filling.push(api::notes::fill(backend, content, values)); } /// A newer value takes the place of the one on its way. @@ -108,9 +100,7 @@ impl FillState { self.filling.retain_mut(|pending| match pending.poll() { None => true, Some(Ok(text)) => { - filled - .copied - .push((text, Message::new(keys::placeholders::COPIED_FILLED))); + filled.copied.push((text, Message::new(keys::placeholders::COPIED_FILLED))); false } Some(Err(error)) => { diff --git a/crates/ui/src/state/presentation.rs b/crates/ui/src/state/presentation.rs index 1c3bebfd6..47aeac7ab 100644 --- a/crates/ui/src/state/presentation.rs +++ b/crates/ui/src/state/presentation.rs @@ -64,11 +64,7 @@ impl PresentationState { self.sessions += 1; self.shown = Some(Presenting { title, - slides: presentation - .slides - .iter() - .map(|slide| richtext::read(slide)) - .collect(), + slides: presentation.slides.iter().map(|slide| richtext::read(slide)).collect(), map: presentation.map, session: self.sessions, }); @@ -90,28 +86,20 @@ mod tests { use super::*; fn presentation() -> Presentation { - Presentation { - slides: vec!["## One".to_owned()], - map: Vec::new(), - } + Presentation { slides: vec!["## One".to_owned()], map: Vec::new() } } /// The commands a frame sent the window, its full screen as `full`. fn sent(full: bool, mut frame: impl FnMut(&Context)) -> Vec { let mut harness = crate::testing::harness().build_ui(|_| {}); - harness.input_mut().viewports.insert( - ViewportId::ROOT, - ViewportInfo { - fullscreen: Some(full), - ..ViewportInfo::default() - }, - ); + harness + .input_mut() + .viewports + .insert(ViewportId::ROOT, ViewportInfo { fullscreen: Some(full), ..ViewportInfo::default() }); harness.step(); frame(&harness.ctx); harness.step(); - harness.output().viewport_output[&ViewportId::ROOT] - .commands - .clone() + harness.output().viewport_output[&ViewportId::ROOT].commands.clone() } #[test] diff --git a/crates/ui/src/state/query.rs b/crates/ui/src/state/query.rs index 30bcf7db4..7c4ca61ae 100644 --- a/crates/ui/src/state/query.rs +++ b/crates/ui/src/state/query.rs @@ -20,13 +20,7 @@ pub struct QueryCell { impl Default for QueryCell { fn default() -> Self { - Self { - value: None, - error: None, - answered: None, - wanted: None, - in_flight: None, - } + Self { value: None, error: None, answered: None, wanted: None, in_flight: None } } } @@ -161,16 +155,13 @@ mod tests { cell.update(asker(&backend, &calls)); cell.want(2); - cell.update(|_| backend.db(|_| Err(engine::error::AppError::storage_unavailable()))); + cell.update(|_| backend.db(|_| Err(engine::error::StorageError::Unavailable.into()))); assert_eq!(cell.value(), Some(&1)); backend.settle(); assert!(cell.update(asker(&backend, &calls))); assert_eq!(cell.value(), Some(&1)); assert!(cell.error().is_some()); - assert!( - !cell.update(asker(&backend, &calls)), - "an error is not asked again in a loop" - ); + assert!(!cell.update(asker(&backend, &calls)), "an error is not asked again in a loop"); } } diff --git a/crates/ui/src/state/refused_tests.rs b/crates/ui/src/state/refused_tests.rs new file mode 100644 index 000000000..ae5f59ea3 --- /dev/null +++ b/crates/ui/src/state/refused_tests.rs @@ -0,0 +1,354 @@ +//! What the core refuses is said, never swallowed, and the window goes on: each gesture asked of +//! a library that closed under it. + +use engine::folders::board::{BoardFrame, BoardPoint, BoardScope}; +use engine::folders::model::FolderColour; +use engine::notes::checklist::ChecklistItem; +use engine::notes::model::HeldNotes; +use engine::notes::priority::Priority; + +use super::held::{Held, held}; +use crate::action::Action; +use crate::notes::destinations::Destination; +use crate::notes::{Action as Notes, Batch, BoardGesture, Editing, Fill, Revisions, Tags, Trash}; +use crate::state::board::Mode; +use crate::testing; + +/// A library of a space, a folder in it and two notes, one with a field and a kept body. +struct Library { + held: Held, + space: String, + folder: String, + note: String, +} + +fn library() -> Library { + let (backend, profile) = testing::unlocked(); + let first = testing::note(&backend, "psql"); + testing::note(&backend, "curl"); + let folder = crate::notes::bench::spaces_of_backend(&backend) + .first() + .map(|space| crate::notes::bench::folder(&backend, space, None, "Scripts")) + .unwrap(); + let mut held = held((backend, profile)); + let patch = engine::notes::model::NotePatch { + content: Some("psql -h {{host}}".to_owned()), + tags: Some(vec!["db".to_owned()]), + ..Default::default() + }; + let id = first.id.clone(); + engine::db::run_here(held.backend.engine(), move |engine| { + engine::notes::update_note(engine, &id, &patch) + }) + .unwrap(); + held.notes(Notes::Reload); + Library { space: first.space_id.clone(), folder: folder.id, note: first.id.clone(), held } +} + +type Before = fn(&mut Library); +type Asks = fn(&mut Library); +type MakesBatch = fn(&Library) -> Batch; +type MakesEditing = fn(&Library) -> Editing; + +fn nothing(_: &mut Library) {} + +fn open_note(library: &mut Library) { + library.held.notes(Notes::OpenNote(library.note.clone())); +} + +fn check(library: &mut Library) { + library.held.notes(Notes::Check(library.note.clone())); +} + +fn on_the_board(library: &mut Library) { + library.held.notes(Notes::ChooseSpace(Some(library.space.clone()))); + library.held.notes(Notes::SetView(Mode::Board)); +} + +#[track_caller] +fn said(name: &str, before: Before, asks: Asks) { + let mut library = library(); + before(&mut library); + assert_eq!(library.held.failed(), None, "{name}: before"); + library.held.close_library(); + + asks(&mut library); + library.held.settle(); + + assert!(library.held.failed().is_some(), "{name} is refused and nothing says it"); +} + +#[test] +fn a_gesture_on_notes_that_is_refused_is_said() { + let gestures: [(&str, Asks); 10] = [ + ("open", open_note), + ("pin", |l| { + l.held.notes(Notes::Pin { id: l.note.clone(), pinned: true }); + }), + ("prioritise", |l| { + l.held + .notes(Notes::Prioritise { id: l.note.clone(), priority: Priority::Urgent }); + }), + ("move to a folder", |l| { + l.held + .notes(Notes::MoveTo { id: l.note.clone(), to: Destination::Folder(l.folder.clone()) }); + }), + ("move to a space", |l| { + l.held + .notes(Notes::MoveTo { id: l.note.clone(), to: Destination::Space(l.space.clone()) }); + }), + ("move out of a folder", |l| { + l.held.notes(Notes::MoveTo { id: l.note.clone(), to: Destination::NoFolder }); + }), + ("delete", |l| l.held.notes(Notes::Delete(l.note.clone()))), + ("duplicate", |l| { + l.held.notes(Notes::Duplicate { id: l.note.clone(), title: "copy".to_owned() }); + }), + ("copy", |l| l.held.notes(Notes::Copy(l.note.clone()))), + ("tick", |l| { + let item = ChecklistItem { text: "a".to_owned(), done: true }; + l.held.notes(Notes::SetItems { id: l.note.clone(), items: vec![item] }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_the_selection_that_is_refused_is_said() { + let batches: [(&str, MakesBatch); 6] = [ + ("move", |l| Batch::MoveTo(Destination::Folder(l.folder.clone()))), + ("prioritise", |_| Batch::Prioritise(Priority::High)), + ("tag", |_| Batch::Tag("ops".to_owned())), + ("untag", |_| Batch::Untag("db".to_owned())), + ("pin", |_| Batch::Pin(true)), + ("delete", |_| Batch::Delete), + ]; + for (name, batch) in batches { + let mut library = library(); + check(&mut library); + library.held.close_library(); + let batch = batch(&library); + library.held.notes(Notes::Batch(batch)); + assert!(library.held.failed().is_some(), "{name}"); + } +} + +#[test] +fn a_gesture_on_spaces_that_is_refused_is_said() { + let gestures: [(&str, Asks); 4] = [ + ("create", |l| { + l.held.notes(Notes::CreateSpace("Work".to_owned())); + }), + ("rename", |l| { + l.held + .notes(Notes::RenameSpace { id: l.space.clone(), name: "Work".to_owned() }); + }), + ("pin", |l| { + l.held.notes(Notes::PinSpace { id: l.space.clone(), pinned: true }); + }), + ("delete", |l| { + let refuge = "another".to_owned(); + l.held + .notes(Notes::DeleteSpace { id: l.space.clone(), refuge, held: HeldNotes::Keep }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_folders_that_is_refused_is_said() { + let gestures: [(&str, Asks); 5] = [ + ("create", |l| { + l.held.notes(Notes::CreateFolder { + space_id: l.space.clone(), + parent_id: None, + name: "New".to_owned(), + }); + }), + ("rename", |l| { + l.held + .notes(Notes::RenameFolder { id: l.folder.clone(), name: "New".to_owned() }); + }), + ("recolour", |l| { + l.held + .notes(Notes::RecolourFolder { id: l.folder.clone(), colour: FolderColour::Purple }); + }), + ("delete", |l| { + l.held + .notes(Notes::DeleteFolder { id: l.folder.clone(), held: HeldNotes::Keep }); + }), + ("move", |l| { + let space = "another".to_owned(); + l.held.notes(Notes::MoveFolder { id: l.folder.clone(), parent: None, space }); + }), + ]; + for (name, asks) in gestures { + said(name, nothing, asks); + } +} + +#[test] +fn a_gesture_on_the_board_that_is_refused_is_said() { + let gestures: [(&str, Asks); 4] = [ + ("tidy", |l| { + l.held.notes(Notes::Tidy(BoardScope::LooseCards)); + }), + ("drop a card", |l| { + let (note_id, folder) = (l.note.clone(), Some(l.folder.clone())); + l.held.notes(Notes::Board(BoardGesture::DropCard { + note_id, + folder, + at: BoardPoint { x: 10, y: 10 }, + })); + }), + ("file on the rail", |l| { + let (note_id, folder) = (l.note.clone(), Some(l.folder.clone())); + l.held.notes(Notes::Board(BoardGesture::FileOnRail { note_id, folder })); + }), + ("name a zone", |l| { + l.held.notes(Notes::Board(BoardGesture::DrawZone(BoardFrame { + x: 0, + y: 0, + width: 200, + height: 200, + }))); + l.held.notes(Notes::NameZone("Zone".to_owned())); + }), + ]; + for (name, asks) in gestures { + said(name, on_the_board, asks); + } +} + +#[test] +fn a_gesture_on_the_trash_that_is_refused_is_said() { + let trashed: Before = |l| { + l.held.notes(Notes::Delete(l.note.clone())); + l.held.notes(Notes::DismissUndo); + l.held.notes(Notes::Trash(Trash::Open)); + }; + let gestures: [(&str, Asks); 4] = [ + ("restore", |l| { + l.held.notes(Notes::Trash(Trash::Restore(l.note.clone()))); + }), + ("purge", |l| { + l.held.notes(Notes::Trash(Trash::Purge(l.note.clone()))); + }), + ("restore all", |l| { + l.held.notes(Notes::Trash(Trash::RestoreAll)); + }), + ("empty", |l| l.held.notes(Notes::Trash(Trash::Empty))), + ]; + for (name, asks) in gestures { + said(name, trashed, asks); + } + said("open", nothing, |l| l.held.notes(Notes::Trash(Trash::Open))); +} + +#[test] +fn a_gesture_on_the_tags_that_is_refused_is_said() { + let ticked: Before = |l| { + l.held.notes(Notes::Tags(Tags::Open)); + l.held.notes(Notes::Tags(Tags::Toggle("db".to_owned()))); + }; + let proposed: Before = |l| { + l.held.notes(Notes::Tags(Tags::Open)); + l.held.notes(Notes::Tags(Tags::Toggle("db".to_owned()))); + l.held.notes(Notes::Tags(Tags::Delete)); + }; + said("open", nothing, |l| l.held.notes(Notes::Tags(Tags::Open))); + said("rename", ticked, |l| { + l.held.notes(Notes::Tags(Tags::Rename("base".to_owned()))); + }); + said("delete", ticked, |l| { + l.held.notes(Notes::Tags(Tags::Delete)); + }); + said("confirm", proposed, |l| { + l.held.notes(Notes::Tags(Tags::Confirm)); + }); +} + +#[test] +fn an_undo_that_is_refused_is_said() { + said( + "undo", + |l| { + l.held.notes(Notes::Pin { id: l.note.clone(), pinned: true }); + }, + |l| l.held.notes(Notes::Undo), + ); +} + +#[test] +fn a_write_of_the_editor_that_is_refused_is_said() { + let editing: [(&str, MakesEditing); 6] = [ + ("save", |l| Editing::Save { + session: l.held.state.editor.opened().unwrap().session, + edit: crate::state::editor::Edit { title: Some("other".to_owned()), ..Default::default() }, + }), + ("pin", |_| Editing::Pin(true)), + ("prioritise", |_| Editing::Prioritise(Priority::Low)), + ("move", |_| Editing::MoveTo("another".to_owned())), + ("file", |l| Editing::File(Some(l.folder.clone()))), + ("delete", |_| Editing::Delete), + ]; + for (name, asked) in editing { + let mut library = library(); + open_note(&mut library); + library.held.close_library(); + let asked = asked(&library); + library.held.notes(Notes::Editor(asked)); + assert!(library.held.failed().is_some(), "{name}"); + } +} + +fn kept(library: &Library) -> String { + library.held.state.revisions.kept()[0].id.clone() +} + +#[test] +fn a_kept_body_that_cannot_be_read_or_put_back_is_said() { + let listed: Before = |l| { + open_note(l); + l.held.notes(Notes::Editor(Editing::Revisions(Revisions::Toggle))); + }; + let looked: Before = |l| { + open_note(l); + l.held.notes(Notes::Editor(Editing::Revisions(Revisions::Toggle))); + l.held.notes(Notes::Editor(Editing::Revisions(Revisions::Look(kept(l))))); + }; + said("look", listed, |l| { + l.held.notes(Notes::Editor(Editing::Revisions(Revisions::Look(kept(l))))); + }); + said("restore", looked, |l| { + l.held.notes(Notes::Editor(Editing::Revisions(Revisions::Restore))); + }); +} + +#[test] +fn fields_that_cannot_be_filled_are_said() { + said( + "fill", + |l| l.held.notes(Notes::Copy(l.note.clone())), + |l| { + let values = [("host".to_owned(), "prod".to_owned())].into(); + l.held.notes(Notes::Fill(Fill::Submit(values))); + }, + ); +} + +#[test] +fn a_menu_that_is_refused_is_said() { + use crate::titlebar::Action as Menu; + + said("export", nothing, |l| { + l.held.apply(Action::Menu(Menu::ExportAll)); + }); + said("the backups", nothing, |l| { + l.held.apply(Action::Menu(Menu::OpenPreferences)); + }); +} diff --git a/crates/ui/src/state/security.rs b/crates/ui/src/state/security.rs index efd0c8d92..08e97a897 100644 --- a/crates/ui/src/state/security.rs +++ b/crates/ui/src/state/security.rs @@ -65,12 +65,7 @@ impl SecurityState { self.refused = false; } - pub fn change( - &mut self, - backend: &Backend, - current: Zeroizing, - next: Zeroizing, - ) { + pub fn change(&mut self, backend: &Backend, current: Zeroizing, next: Zeroizing) { if !self.is_changing() { self.refused = false; self.changing = Some(api::vault::change_passphrase(backend, current, next)); @@ -96,8 +91,7 @@ impl SecurityState { pub fn save_variables(&mut self, backend: &Backend, rows: Vec) { let values = record(&rows); self.stored = Some(rows); - self.saving - .push(api::notes::set_global_variables(backend, values)); + self.saving.push(api::notes::set_global_variables(backend, values)); } pub fn update(&mut self, status: &mut StatusNotifier, errors: &mut ErrorNotifier) { @@ -117,8 +111,7 @@ impl SecurityState { match answer { Ok(stored) => { let rows = stored.into_iter(); - self.stored = - Some(rows.map(|(name, value)| Variable { name, value }).collect()); + self.stored = Some(rows.map(|(name, value)| Variable { name, value }).collect()); } Err(error) => errors.report(keys::errors::VARIABLES_LOAD_FAILED, &error), } @@ -150,10 +143,7 @@ mod tests { use crate::testing; fn row(name: &str, value: &str) -> Variable { - Variable { - name: name.to_owned(), - value: value.to_owned(), - } + Variable { name: name.to_owned(), value: value.to_owned() } } fn settled(state: &mut SecurityState, backend: &Backend) -> (StatusNotifier, ErrorNotifier) { @@ -165,12 +155,7 @@ mod tests { #[test] fn a_badly_named_or_empty_row_is_not_sent_and_the_last_of_a_duplicate_wins() { - let rows = [ - row("host", "first"), - row("host", "last"), - row("has space", "refused"), - row("port", ""), - ]; + let rows = [row("host", "first"), row("host", "last"), row("has space", "refused"), row("port", "")]; let sent = record(&rows); @@ -190,10 +175,7 @@ mod tests { let (status, _) = settled(&mut state, &backend); assert!(state.take_changed()); - assert_eq!( - status.latest().map(|(_, said)| said.key), - Some(keys::settings::security::CHANGED) - ); + assert_eq!(status.latest().map(|(_, said)| said.key), Some(keys::settings::security::CHANGED)); } #[test] diff --git a/crates/ui/src/state/selection.rs b/crates/ui/src/state/selection.rs index b6d9e5115..49aabcefc 100644 --- a/crates/ui/src/state/selection.rs +++ b/crates/ui/src/state/selection.rs @@ -48,8 +48,7 @@ impl SelectionState { .and_then(|anchor| order.iter().position(|each| *each == anchor)) .unwrap_or(to); let (low, high) = (from.min(to), from.max(to)); - self.checked - .extend(order[low..=high].iter().map(|each| (*each).to_owned())); + self.checked.extend(order[low..=high].iter().map(|each| (*each).to_owned())); } /// Every one of `ids` ticked, none untoggled: a sweep or a whole zone. diff --git a/crates/ui/src/state/spaces.rs b/crates/ui/src/state/spaces.rs index d31781d15..e6f8c0e3d 100644 --- a/crates/ui/src/state/spaces.rs +++ b/crates/ui/src/state/spaces.rs @@ -48,10 +48,7 @@ pub struct SpacesState { impl SpacesState { /// The space the library was left on, from its preferences. pub fn restore(&mut self, preferences: &Preferences) { - self.chosen = preferences - .get(ACTIVE_SPACE_KEY) - .filter(|id| !id.is_empty()) - .map(str::to_owned); + self.chosen = preferences.get(ACTIVE_SPACE_KEY).filter(|id| !id.is_empty()).map(str::to_owned); } /// The choice into `preferences`, every other key kept. @@ -71,15 +68,9 @@ impl SpacesState { let mut said = Vec::new(); self.writes.retain_mut(|writing| { let answer = match &mut writing.write { - Write::Made(pending) => pending - .poll() - .map(|answer| answer.map(|space| Some(space.id))), + Write::Made(pending) => pending.poll().map(|answer| answer.map(|space| Some(space.id))), Write::Changed(pending) => pending.poll().map(|answer| answer.map(|_| None)), - Write::Deleted { - pending, - refuge: (id, name), - held, - } => pending.poll().map(|answer| { + Write::Deleted { pending, refuge: (id, name), held } => pending.poll().map(|answer| { answer.map(|moved| { said.push(deleted(*held, name, moved)); Some(id.clone()) @@ -114,8 +105,7 @@ impl SpacesState { } if let Some(id) = &self.counted { self.contents.want((id.clone(), *revision)); - self.contents - .update(|(id, _)| api::spaces::contents(backend, id)); + self.contents.update(|(id, _)| api::spaces::contents(backend, id)); } moved } @@ -132,17 +122,12 @@ impl SpacesState { let Some(spaces) = self.spaces.value() else { return Some(chosen); }; - spaces - .iter() - .any(|space| space.id == chosen) - .then_some(chosen) + spaces.iter().any(|space| space.id == chosen).then_some(chosen) } /// The space whose deletion is considered, and what it holds once counted. pub fn contents(&self, id: &str) -> Option<&SpaceContents> { - (self.counted.as_deref() == Some(id)) - .then(|| self.contents.value()) - .flatten() + (self.counted.as_deref() == Some(id)).then(|| self.contents.value()).flatten() } /// The caller leaves the folder: the row means the space itself. @@ -166,26 +151,17 @@ impl SpacesState { pub fn rename_space(&mut self, backend: &Backend, id: String, name: &str) { let Some(name) = trimmed(name) else { return }; - let unchanged = self - .spaces() - .iter() - .any(|space| space.id == id && space.name == name); + let unchanged = self.spaces().iter().any(|space| space.id == id && space.name == name); if unchanged { return; } let failed = Message::new(keys::errors::SPACE_RENAME_FAILED).with("name", name.as_str()); - self.push( - Write::Changed(api::spaces::rename(backend, id, name)), - failed, - ); + self.push(Write::Changed(api::spaces::rename(backend, id, name)), failed); } pub fn pin_space(&mut self, backend: &Backend, id: String, pinned: bool) { let failed = Message::new(keys::errors::SPACE_PIN_FAILED); - self.push( - Write::Changed(api::spaces::pin(backend, id, pinned)), - failed, - ); + self.push(Write::Changed(api::spaces::pin(backend, id, pinned)), failed); } /// The refuge is then shown: the notes have just landed there. diff --git a/crates/ui/src/state/tags.rs b/crates/ui/src/state/tags.rs index 1e4485ddb..e93517f9b 100644 --- a/crates/ui/src/state/tags.rs +++ b/crates/ui/src/state/tags.rs @@ -94,11 +94,7 @@ impl TagsState { if into.is_empty() { return; } - let kind = if self.selected.len() == 1 { - ChangeKind::Rename - } else { - ChangeKind::Merge - }; + let kind = if self.selected.len() == 1 { ChangeKind::Rename } else { ChangeKind::Merge }; self.propose(backend, kind, into); } Tags::Delete => self.propose(backend, ChangeKind::Delete, String::new()), @@ -123,21 +119,11 @@ impl TagsState { } let tags: Vec = self.selected.iter().cloned().collect(); let counting = api::notes::count_tagged(backend, tags.clone()); - let change = TagChange { - kind, - tags, - into, - notes: 0, - }; + let change = TagChange { kind, tags, into, notes: 0 }; self.proposing = Some((change, counting)); } - pub fn update( - &mut self, - backend: &Backend, - revision: &mut Revision, - errors: &mut ErrorNotifier, - ) { + pub fn update(&mut self, backend: &Backend, revision: &mut Revision, errors: &mut ErrorNotifier) { if let Some(answer) = self.loading.as_mut().and_then(Pending::poll) { self.loading = None; match answer { @@ -145,11 +131,7 @@ impl TagsState { Err(error) => errors.report(keys::errors::TAGS_LOAD_FAILED, &error), } } - if let Some(answer) = self - .proposing - .as_mut() - .and_then(|(_, counting)| counting.poll()) - { + if let Some(answer) = self.proposing.as_mut().and_then(|(_, counting)| counting.poll()) { let (change, _) = self.proposing.take().expect("polled just now"); match answer { Ok(notes) => self.pending = Some(TagChange { notes, ..change }), diff --git a/crates/ui/src/state/tools.rs b/crates/ui/src/state/tools.rs index ad2c20008..9eace2f14 100644 --- a/crates/ui/src/state/tools.rs +++ b/crates/ui/src/state/tools.rs @@ -66,15 +66,11 @@ impl ToolsState { pub fn read(preferences: &Preferences) -> Self { Self { recents: preferences.get(RECENTS).map_or_else(Vec::new, read_recents), - favourites: preferences - .get(FAVOURITES) - .map_or_else(Vec::new, read_favourites), + favourites: preferences.get(FAVOURITES).map_or_else(Vec::new, read_favourites), zones: preferences .get(ZONES) .map_or_else(|| DEFAULT_ZONES.map(str::to_owned).to_vec(), read_zones), - csv_separator: preferences - .get(CSV_SEPARATOR) - .map_or(CsvSeparator::Comma, read_separator), + csv_separator: preferences.get(CSV_SEPARATOR).map_or(CsvSeparator::Comma, read_separator), ..Self::default() } } @@ -143,10 +139,7 @@ impl ToolsState { /// The starred tools the catalogue still has, in the order they were starred. pub fn favourites(&self) -> Vec<&'static ToolEntry> { - self.favourites - .iter() - .filter_map(|id| catalogue::find(id)) - .collect() + self.favourites.iter().filter_map(|id| catalogue::find(id)).collect() } pub fn is_favourite(&self, id: &str) -> bool { @@ -247,10 +240,7 @@ mod tests { let read = ToolsState::read(&preferences); assert_eq!(read.recents().next().unwrap().0.id, "cron"); - assert_eq!( - read.favourites().iter().map(|t| t.id).collect::>(), - ["jwt"] - ); + assert_eq!(read.favourites().iter().map(|t| t.id).collect::>(), ["jwt"]); assert!(read.is_favourite("gone")); } diff --git a/crates/ui/src/state/transfer.rs b/crates/ui/src/state/transfer.rs index b5e2cf812..d61c6016a 100644 --- a/crates/ui/src/state/transfer.rs +++ b/crates/ui/src/state/transfer.rs @@ -103,19 +103,10 @@ impl TransferState { Stage::Protecting { path, .. } => (Purpose::Protect, path, false, false), Stage::Writing { path, .. } => (Purpose::Protect, path, false, true), Stage::Unlocking { path, refused } => (Purpose::Unlock, path, *refused, false), - Stage::Reading { - path, - protected: true, - .. - } => (Purpose::Unlock, path, false, true), + Stage::Reading { path, protected: true, .. } => (Purpose::Unlock, path, false, true), _ => return None, }; - Some(Request { - purpose, - file_name: file_name(path), - refused, - working, - }) + Some(Request { purpose, file_name: file_name(path), refused, working }) } pub fn answer(&mut self, answer: Answer, backend: &Backend) { @@ -131,13 +122,8 @@ impl TransferState { }; match std::mem::replace(&mut self.stage, Stage::Idle) { Stage::Protecting { scope, path } => { - let report = - api::transfer::export(backend, path.clone(), scope.clone(), passphrase); - self.stage = Stage::Writing { - scope, - path, - report, - }; + let report = api::transfer::export(backend, path.clone(), scope.clone(), passphrase); + self.stage = Stage::Writing { scope, path, report }; } Stage::Unlocking { path, .. } => { self.stage = reading(backend, path, passphrase, true); @@ -156,22 +142,12 @@ impl TransferState { reports: &mut Reports<'_>, ) { self.stage = match std::mem::replace(&mut self.stage, Stage::Idle) { - Stage::Counting { scope, count } => { - counted(scope, count, (backend, dialog, now), reports) - } + Stage::Counting { scope, count } => counted(scope, count, (backend, dialog, now), reports), Stage::Placing { scope, place } => placed(scope, place, reports), - Stage::Writing { - scope, - path, - report, - } => written(scope, path, report, reports), + Stage::Writing { scope, path, report } => written(scope, path, report, reports), Stage::Picking(path) => picked(path, backend, reports), Stage::Probing { path, protected } => probed(path, protected, backend, reports), - Stage::Reading { - path, - protected, - report, - } => read(path, protected, report, reports), + Stage::Reading { path, protected, report } => read(path, protected, report, reports), Stage::Sharing { notes, markdown } => shared(notes, markdown, ctx, reports), waiting => waiting, }; @@ -199,17 +175,10 @@ fn counted( } } -fn placed( - scope: ExportScope, - mut place: Pending>, - reports: &mut Reports<'_>, -) -> Stage { +fn placed(scope: ExportScope, mut place: Pending>, reports: &mut Reports<'_>) -> Stage { match place.poll() { None => Stage::Placing { scope, place }, - Some(Ok(Some(path))) => Stage::Protecting { - scope, - path: path.to_string_lossy().into_owned(), - }, + Some(Ok(Some(path))) => Stage::Protecting { scope, path: path.to_string_lossy().into_owned() }, Some(Ok(None)) => Stage::Idle, Some(Err(error)) => failed(reports, keys::errors::EXPORT_FAILED, &error), } @@ -222,11 +191,7 @@ fn written( reports: &mut Reports<'_>, ) -> Stage { match report.poll() { - None => Stage::Writing { - scope, - path, - report, - }, + None => Stage::Writing { scope, path, report }, Some(Ok(report)) => { reports.status.report(exported(&report, &scope, &path)); Stage::Idle @@ -235,11 +200,7 @@ fn written( } } -fn picked( - mut path: Pending>, - backend: &Backend, - reports: &mut Reports<'_>, -) -> Stage { +fn picked(mut path: Pending>, backend: &Backend, reports: &mut Reports<'_>) -> Stage { match path.poll() { None => Stage::Picking(path), Some(Ok(Some(path))) => { @@ -252,18 +213,10 @@ fn picked( } } -fn probed( - path: String, - mut protected: Pending, - backend: &Backend, - reports: &mut Reports<'_>, -) -> Stage { +fn probed(path: String, mut protected: Pending, backend: &Backend, reports: &mut Reports<'_>) -> Stage { match protected.poll() { None => Stage::Probing { path, protected }, - Some(Ok(true)) => Stage::Unlocking { - path, - refused: false, - }, + Some(Ok(true)) => Stage::Unlocking { path, refused: false }, Some(Ok(false)) => reading(backend, path, None, false), Some(Err(error)) => failed(reports, keys::errors::IMPORT_FAILED, &error), } @@ -276,26 +229,18 @@ fn read( reports: &mut Reports<'_>, ) -> Stage { match report.poll() { - None => Stage::Reading { - path, - protected, - report, - }, + None => Stage::Reading { path, protected, report }, Some(Ok(report)) => { reports.status.report(imported(&report, &path)); // The spaces and the folders follow the revision, as the canvas does. - if report.notes_imported > 0 || report.spaces_created > 0 || report.folders_created > 0 - { + if report.notes_imported > 0 || report.spaces_created > 0 || report.folders_created > 0 { reports.revision.bump(); } Stage::Idle } // The ordinary answer to a typo: a file nobody can reopen for one is a file lost. Some(Err(error)) if protected && error.code == ErrorCode::WrongPassphrase => { - Stage::Unlocking { - path, - refused: true, - } + Stage::Unlocking { path, refused: true } } Some(Err(error)) => failed(reports, keys::errors::IMPORT_FAILED, &error), } @@ -311,9 +256,7 @@ fn shared( None => Stage::Sharing { notes, markdown }, Some(Ok(markdown)) => { ctx.copy_text(markdown); - reports - .status - .report(Message::new(keys::file::COPIED).with("notes", notes)); + reports.status.report(Message::new(keys::file::COPIED).with("notes", notes)); Stage::Idle } Some(Err(error)) => failed(reports, keys::errors::SHARE_FAILED, &error), @@ -322,11 +265,7 @@ fn shared( fn reading(backend: &Backend, path: String, passphrase: Option, protected: bool) -> Stage { let report = api::transfer::import(backend, path.clone(), passphrase); - Stage::Reading { - path, - protected, - report, - } + Stage::Reading { path, protected, report } } fn failed(reports: &mut Reports<'_>, key: Key, error: &AppError) -> Stage { @@ -340,10 +279,9 @@ fn plain(mut phrase: Zeroizing) -> String { } fn file_name(path: &str) -> String { - Path::new(path).file_name().map_or_else( - || path.to_owned(), - |name| name.to_string_lossy().into_owned(), - ) + Path::new(path) + .file_name() + .map_or_else(|| path.to_owned(), |name| name.to_string_lossy().into_owned()) } /// Stamped to the second, and in local time: to the minute, two exports in a row were offered the @@ -457,22 +395,15 @@ mod tests { /// Until the operation stops, or stands at the prompt. fn run(&mut self) { - while self.transfer.is_busy() - && self.transfer.prompt().is_none_or(|request| request.working) - { + while self.transfer.is_busy() && self.transfer.prompt().is_none_or(|request| request.working) { self.backend.settle(); let mut reports = Reports { status: &mut self.status, errors: &mut self.errors, revision: &mut self.revision, }; - self.transfer.update( - &self.ctx, - &self.backend, - &self.dialog, - Utc::now(), - &mut reports, - ); + self.transfer + .update(&self.ctx, &self.backend, &self.dialog, Utc::now(), &mut reports); } } @@ -622,11 +553,7 @@ mod tests { #[test] fn an_export_that_left_attachments_out_says_how_many() { - let report = ExportReport { - notes: 2, - attachments_unreadable: 1, - ..ExportReport::nothing(false) - }; + let report = ExportReport { notes: 2, attachments_unreadable: 1, ..ExportReport::nothing(false) }; let said = exported(&report, &ExportScope::Library, "/tmp/notes.devnotes"); @@ -635,4 +562,132 @@ mod tests { "2 notes exported to notes.devnotes. ⚠️ 1 attachment could not be read and was left out." ); } + + fn import_report() -> ImportReport { + ImportReport { notes_imported: 3, ..ImportReport::default() } + } + + /// The first that applies: a preview that will never load before everything else. + #[test] + fn an_import_says_what_most_deserves_saying() { + type Set = fn(&mut ImportReport); + let rungs: [(Set, Key); 6] = [ + (|r| r.notes_imported = 0, keys::file::IMPORTED_NOTHING), + (|r| r.attachments_missing = 1, keys::file::IMPORTED_WITHOUT_SOME_ATTACHMENTS), + (|r| r.notes_degraded = 1, keys::file::IMPORTED_FROM_NEWER_VERSION), + (|r| r.folders_created = 1, keys::file::IMPORTED_INTO_FOLDERS), + (|r| r.attachments_imported = 1, keys::file::IMPORTED_WITH_ATTACHMENTS), + (|_| {}, keys::file::IMPORTED), + ]; + for at in 0..rungs.len() { + let mut report = import_report(); + for (set, _) in &rungs[at..] { + set(&mut report); + } + let said = imported(&report, "/tmp/notes.devnotes"); + assert_eq!(said.key, rungs[at].1); + for language in i18n::Language::ALL { + assert!(!said.text(language).contains("{{"), "{at}"); + } + } + } + + #[test] + fn an_export_says_whether_it_is_protected_and_carries_files() { + for (protected, attachments, key) in [ + (true, 2, keys::file::EXPORTED_PROTECTED_WITH_ATTACHMENTS), + (true, 0, keys::file::EXPORTED_PROTECTED), + (false, 2, keys::file::EXPORTED_WITH_ATTACHMENTS), + (false, 0, keys::file::EXPORTED), + ] { + let report = ExportReport { notes: 2, attachments, ..ExportReport::nothing(protected) }; + let said = exported(&report, &ExportScope::Library, "a/b/notes.devnotes"); + assert_eq!(said.key, key); + assert!(said.text(i18n::Language::En).contains("notes.devnotes")); + assert!(!said.text(i18n::Language::En).contains("a/b")); + } + } + + #[test] + fn an_export_emptied_meanwhile_says_there_was_nothing() { + let nothing = ExportReport::nothing(true); + let space = ExportScope::Space { space_id: "a".to_owned() }; + + assert_eq!(exported(¬hing, &space, "a").key, keys::file::EMPTY_SPACE); + assert_eq!(exported(¬hing, &ExportScope::Library, "a").key, keys::file::EMPTY_LIBRARY); + } + + #[test] + fn an_empty_space_is_said_before_a_place_is_asked() { + let mut bench = Bench::new(); + let space = crate::notes::bench::space(&bench.backend, "Empty"); + + bench.transfer.export(&bench.backend, ExportScope::Space { space_id: space.id }); + bench.run(); + assert_eq!(bench.said(), Some(keys::file::EMPTY_SPACE)); + } + + #[test] + fn a_dialog_cancelled_ends_the_operation_without_a_word() { + let mut bench = Bench::new(); + testing::note(&bench.backend, "Worth exporting"); + bench.dialog = Arc::new(platform::dialog::NoDialog); + + bench.export(); + assert!(!bench.transfer.is_busy()); + bench.import(); + assert!(!bench.transfer.is_busy()); + assert!(bench.status.latest().is_none() && bench.errors.notice().is_none()); + } + + #[test] + fn an_export_that_cannot_be_written_is_said() { + let mut bench = Bench::new(); + testing::note(&bench.backend, "Worth exporting"); + bench.dialog = Arc::new(Fixed(bench.file.join("no-such-folder").join("a.devnotes"))); + std::fs::write(&bench.file, "a file, not a folder").unwrap(); + + bench.export(); + bench.answer(Answer::Plain); + assert!(bench.errors.notice().is_some()); + assert!(!bench.transfer.is_busy()); + } + + /// The same file into another library: its notes are new there. + #[test] + fn an_import_that_brought_notes_is_said_and_shows_them() { + let mut from = Bench::new(); + testing::note(&from.backend, "Worth exporting"); + from.export(); + from.answer(Answer::Plain); + let mut into = Bench::new(); + into.dialog = Arc::new(Fixed(from.file.clone())); + let before = into.revision; + + into.import(); + assert_eq!(into.said(), Some(keys::file::IMPORTED)); + assert_ne!(into.revision, before); + } + + #[test] + fn an_answer_with_nothing_asked_changes_nothing() { + let mut bench = Bench::new(); + + for answer in [Answer::Plain, Answer::Cancel, phrase(PHRASE)] { + bench.answer(answer); + assert!(!bench.transfer.is_busy()); + } + assert!(!bench.file.exists()); + } + + #[test] + fn a_share_of_what_is_gone_is_said() { + let mut bench = Bench::new(); + testing::close_library(&bench.backend); + + bench.transfer.share(&bench.backend, vec!["gone".to_owned()]); + bench.run(); + assert!(bench.errors.notice().is_some()); + assert!(!bench.transfer.is_busy()); + } } diff --git a/crates/ui/src/state/undo.rs b/crates/ui/src/state/undo.rs index 6653613d0..569e36980 100644 --- a/crates/ui/src/state/undo.rs +++ b/crates/ui/src/state/undo.rs @@ -33,9 +33,7 @@ impl UndoState { /// What the bar offers at `now`; `None` once its time is up, though `Ctrl+Z` still can. pub fn banner(&self, now: f64) -> Option<&Reversible> { - self.banner_until - .filter(|until| now < *until) - .and(self.last.as_ref()) + self.banner_until.filter(|until| now < *until).and(self.last.as_ref()) } /// Seconds until the banner goes: the window is redrawn then, without an input. @@ -55,8 +53,7 @@ impl UndoState { return false; }; self.banner_until = None; - self.reverting - .push(api::undo::revert(backend, action, lines)); + self.reverting.push(api::undo::revert(backend, action, lines)); true } @@ -85,10 +82,7 @@ mod tests { use super::*; fn pinned() -> Reversible { - Reversible::Pin { - ids: vec!["a".into()], - pinned: true, - } + Reversible::Pin { ids: vec!["a".into()], pinned: true } } #[test] @@ -100,27 +94,15 @@ mod tests { assert!(undo.banner(17.9).is_some()); assert!(undo.banner(18.0).is_none()); assert!(undo.banner_left(18.0).is_none()); - assert!( - undo.revert(&backend, PreviewLines::default()), - "Ctrl+Z still reads the record" - ); - assert!( - !undo.revert(&backend, PreviewLines::default()), - "and puts it back once" - ); + assert!(undo.revert(&backend, PreviewLines::default()), "Ctrl+Z still reads the record"); + assert!(!undo.revert(&backend, PreviewLines::default()), "and puts it back once"); } #[test] fn nothing_touched_is_nothing_to_offer() { let mut undo = UndoState::default(); undo.record(Reversible::Move(Vec::new()), 0.0); - undo.record( - Reversible::Deletion { - ids: vec!["a".into()], - count: 0, - }, - 0.0, - ); + undo.record(Reversible::Deletion { ids: vec!["a".into()], count: 0 }, 0.0); assert!(undo.banner(0.0).is_none()); } diff --git a/crates/ui/src/state/window_tests.rs b/crates/ui/src/state/window_tests.rs new file mode 100644 index 000000000..da40423f2 --- /dev/null +++ b/crates/ui/src/state/window_tests.rs @@ -0,0 +1,479 @@ +//! What the palette, the menus and the editor's files change, without a window. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use engine::notes::kind::NoteKind; +use platform::desktop::Opener; +use platform::dialog::{Fixed, NoDialog}; + +use super::Area; +use super::attachments::Asked as Attach; +use super::held::{Held, held}; +use crate::action::{Action, AppAction, GlobalAction}; +use crate::notes::{Action as Notes, Editing, bench}; +use crate::palette::Asked; +use crate::palette::commands::Command; +use crate::palette::options::Chosen; +use crate::testing; +use crate::titlebar::Action as Menu; + +fn with_a_note() -> (Held, String) { + let (backend, profile) = testing::unlocked(); + let id = testing::note(&backend, "psql").id.clone(); + (held((backend, profile)), id) +} + +// The palette + +fn choose(held: &mut Held, chosen: Chosen) { + held.state.palette.open(&held.backend, false); + held.settle(); + held.apply(Action::Palette(Asked::Choose(chosen))); + assert!(!held.state.palette.is_open(), "chosen, it closes"); +} + +#[test] +fn what_is_chosen_in_the_palette_shows_its_area() { + for (chosen, from, shown) in [ + (Chosen::Command(Command::Area(Area::Tools)), Area::Notes, Area::Tools), + (Chosen::Command(Command::Area(Area::Notes)), Area::Http, Area::Notes), + (Chosen::Command(Command::Request), Area::Notes, Area::Http), + (Chosen::Tool("uuid"), Area::Notes, Area::Tools), + (Chosen::Command(Command::Folder), Area::Tools, Area::Notes), + (Chosen::Create("psql".to_owned()), Area::Http, Area::Notes), + (Chosen::Command(Command::Preferences), Area::Http, Area::Http), + (Chosen::Command(Command::Shortcuts), Area::Tools, Area::Tools), + ] { + let (mut held, _) = with_a_note(); + held.state.settings.area = from; + choose(&mut held, chosen.clone()); + assert_eq!(held.state.settings.area, shown, "{chosen:?}"); + } +} + +#[test] +fn a_note_chosen_in_the_palette_opens() { + let (mut held, id) = with_a_note(); + choose(&mut held, Chosen::Note(id.clone())); + + assert_eq!(held.state.editor.open_id(), Some(id.as_str())); +} + +#[test] +fn a_kind_chosen_in_the_palette_is_a_draft_of_it() { + for kind in [NoteKind::Snippet, NoteKind::Note, NoteKind::Checklist, NoteKind::Calc] { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Command(Command::Create(kind))); + let opened = held.state.editor.opened().unwrap(); + assert!(opened.is_draft()); + assert_eq!(opened.note().unwrap().kind, kind); + } +} + +#[test] +fn what_was_typed_in_the_palette_is_the_title_of_the_note_made_of_it() { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Create("pg_dump".to_owned())); + + assert_eq!(held.state.editor.opened().unwrap().note().unwrap().title, "pg_dump"); +} + +#[test] +fn a_space_chosen_in_the_palette_is_the_one_shown() { + let (mut held, id) = with_a_note(); + let space = held.note(&id).space_id.clone(); + held.notes(Notes::ChooseSpace(None)); + choose(&mut held, Chosen::Space(space.clone())); + + assert_eq!(held.state.spaces.active_space(), Some(space.as_str())); +} + +#[test] +fn a_request_asked_of_the_palette_is_a_draft_in_its_tab() { + let (mut held, _) = with_a_note(); + choose(&mut held, Chosen::Command(Command::Request)); + + assert!(held.state.http.tabs().active().is_some()); +} + +#[test] +fn a_copy_asked_of_the_palette_closes_it_and_is_said() { + let (mut held, id) = with_a_note(); + held.state.palette.open(&held.backend, false); + held.settle(); + held.apply(Action::Palette(Asked::Copy(id))); + + assert!(!held.state.palette.is_open()); + assert!(held.done().unwrap().contains("psql")); +} + +#[test] +fn a_copy_is_not_said_to_a_person_who_asked_not_to_be_told() { + let (mut held, id) = with_a_note(); + held.state.settings.copy_confirmation = false; + held.notes(Notes::Copy(id)); + + assert_eq!(held.done(), None); + assert_eq!(held.failed(), None); +} + +#[test] +fn a_drawing_cannot_be_copied_as_text_and_says_so() { + let (backend, profile) = testing::unlocked(); + let space = bench::space(&backend, "Home"); + let mut draft = testing::snippet(space.id, "plan".to_owned()); + draft.kind = NoteKind::Drawing; + draft.content = r#"{"version":1,"scene":{"objects":[]}}"#.to_owned(); + let id = engine::db::run_here(backend.engine(), move |engine| engine::notes::create_note(engine, draft)) + .unwrap() + .id + .clone(); + let mut held = held((backend, profile)); + held.notes(Notes::Copy(id)); + + assert_eq!(held.state.status.latest().unwrap().1.key, i18n::keys::notes::DRAWING_NOT_COPIED); +} + +// The menus + +#[test] +fn an_export_of_a_space_or_of_a_selection_needs_one() { + let (mut held, _) = with_a_note(); + held.notes(Notes::ChooseSpace(None)); + for menu in [Menu::ExportSpace, Menu::ExportSelection, Menu::CopyMarkdown] { + held.apply(Action::Menu(menu)); + assert!(!held.state.transfer.is_busy()); + assert_eq!(held.done(), None); + } +} + +#[test] +fn the_notes_ticked_are_shared_as_markdown() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Check(id)); + held.apply(Action::Menu(Menu::CopyMarkdown)); + + assert_eq!(held.state.status.latest().unwrap().1.key, i18n::keys::file::COPIED); +} + +#[test] +fn a_panel_of_the_menus_opens_once_and_closes() { + use crate::titlebar::about_menu::{self, Panel}; + let (mut held, _) = with_a_note(); + held.apply(Action::Menu(Menu::OpenHelp(Panel::Sheet))); + assert!(held.state.dialogs.is_open(about_menu::id())); + held.apply(Action::Menu(Menu::CloseHelp)); + assert!(!held.state.dialogs.is_open(about_menu::id())); + + held.apply(Action::Menu(Menu::OpenLibraries)); + assert!(held.state.dialogs.is_open(crate::titlebar::libraries::id())); + held.apply(Action::Menu(Menu::Libraries(crate::titlebar::libraries::Ask::Close))); + assert_eq!(held.state.dialogs.top(), None); +} + +/// The draft is dropped, whatever it held. +#[test] +fn the_preferences_discarded_change_nothing() { + use crate::titlebar::preferences::{self, Ask}; + let (mut held, _) = with_a_note(); + let before = held.state.settings.clone(); + held.apply(Action::Menu(Menu::OpenPreferences)); + assert!(held.state.dialogs.is_open(preferences::id())); + + held.apply(Action::Menu(Menu::Preferences(Ask::Discard))); + assert_eq!(held.state.settings, before); + assert!(!held.state.dialogs.is_open(preferences::id())); + assert_eq!(held.state.titlebar_view.previewed(), None); +} + +#[test] +fn a_look_chosen_and_the_rail_put_away_are_kept_for_the_next_launch() { + let (mut held, _) = with_a_note(); + let shown = held.state.settings.rail_shown; + held.apply(Action::App(AppAction::ToggleRail)); + held.apply(Action::App(AppAction::SetRailWidth(300))); + held.apply(Action::App(AppAction::SetHistoryWidth(420))); + held.apply(Action::App(AppAction::SetEditorPanelWidth(600))); + + let settings = &held.state.settings; + assert_eq!(settings.rail_shown, !shown); + assert_eq!( + (settings.rail_width, settings.history_list_width, settings.editor_panel_width), + (300, 420, 600) + ); + let written = crate::services::preferences::Preferences::read( + &held.profile.path().join(engine::layout::PREFERENCES), + ); + assert_eq!(&crate::services::settings::Settings::read(&written), settings); +} + +#[test] +fn what_is_said_is_dismissed_by_its_number() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Copy(id)); + let (number, _) = held.state.status.latest().unwrap(); + held.apply(Action::App(AppAction::DismissStatus(number + 1))); + assert!(held.done().is_some()); + + held.apply(Action::App(AppAction::DismissStatus(number))); + assert_eq!(held.done(), None); +} + +// From outside the window + +#[derive(Clone)] +struct Clip(String); + +impl platform::clipboard::Clipboard for Clip { + fn html(&self) -> Option { + None + } + + fn text(&self) -> Option { + Some(self.0.clone()) + } +} + +/// Code makes a snippet, prose a Note, and either is written at once. +#[test] +fn a_capture_is_a_note_of_what_the_clipboard_holds() { + for (text, kind) in [ + ("SELECT id, title FROM notes WHERE pinned = 1 ORDER BY id;", NoteKind::Snippet), + ("Penser à rappeler le support demain matin.", NoteKind::Note), + ] { + let (mut held, _) = with_a_note(); + held.state.clipboard = Arc::new(Clip(text.to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + let opened = held.state.editor.opened().unwrap(); + assert!(!opened.is_draft()); + assert_eq!((opened.note().unwrap().kind, opened.note().unwrap().content.as_str()), (kind, text)); + } +} + +#[test] +fn a_capture_of_nothing_opens_nothing() { + let (mut held, _) = with_a_note(); + held.apply(Action::Global(GlobalAction::Capture)); + held.state.clipboard = Arc::new(Clip(" \n".to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + assert!(!held.state.editor.is_open()); + assert_eq!(held.shown(), ["psql"]); +} + +#[test] +fn a_capture_before_the_library_is_open_is_left_alone() { + let (backend, profile) = testing::backend(); + let mut held = held((backend, profile)); + held.state.clipboard = Arc::new(Clip("words".to_owned())); + held.apply(Action::Global(GlobalAction::Capture)); + + assert!(!held.state.editor.is_open()); +} + +// The files of a note + +#[derive(Clone, Default)] +struct Opened(Arc>>); + +impl Opener for Opened { + fn open(&self, path: &Path) -> std::io::Result<()> { + self.0.lock().unwrap().push(path.to_owned()); + Ok(()) + } +} + +/// A note open with `plan.txt` attached, and where the test writes. +fn with_a_file() -> (Held, String, tempfile::TempDir) { + let (mut held, id) = with_a_note(); + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("plan.txt"); + std::fs::write(&file, "the plan").unwrap(); + held.notes(Notes::OpenNote(id)); + attach(&mut held, Attach::Dropped(vec![file])); + let attached = held.state.attachments.list()[0].id.clone(); + (held, attached, directory) +} + +fn attach(held: &mut Held, asked: Attach) { + held.notes(Notes::Editor(Editing::Attachment(asked))); +} + +#[test] +fn a_file_dropped_on_a_note_is_attached_to_it() { + let (held, _, _directory) = with_a_file(); + let names: Vec<&str> = held + .state + .attachments + .list() + .iter() + .map(|file| file.file_name.as_str()) + .collect(); + + assert_eq!(names, ["plan.txt"]); + assert!(!held.state.attachments.is_busy()); +} + +#[test] +fn a_file_picked_is_attached_and_a_dialog_cancelled_attaches_none() { + let (mut held, _, directory) = with_a_file(); + let other = directory.path().join("other.txt"); + std::fs::write(&other, "other").unwrap(); + held.state.dialog = Arc::new(NoDialog); + attach(&mut held, Attach::Pick); + assert_eq!(held.state.attachments.list().len(), 1); + + held.state.dialog = Arc::new(Fixed(other)); + attach(&mut held, Attach::Pick); + assert_eq!(held.state.attachments.list().len(), 2); +} + +#[test] +fn a_file_that_is_not_there_is_not_attached_and_says_so() { + let (mut held, _, directory) = with_a_file(); + attach(&mut held, Attach::Dropped(vec![directory.path().join("gone.txt")])); + + assert_eq!(held.state.attachments.list().len(), 1); + assert!(held.failed().is_some()); +} + +#[test] +fn an_attachment_is_saved_where_the_dialog_says() { + let (mut held, id, directory) = with_a_file(); + let copy = directory.path().join("copy.txt"); + held.state.dialog = Arc::new(Fixed(copy.clone())); + attach(&mut held, Attach::Save(id)); + + assert_eq!(std::fs::read_to_string(copy).unwrap(), "the plan"); + assert!(held.done().is_some()); +} + +#[test] +fn a_save_cancelled_or_of_no_attachment_says_nothing() { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(NoDialog); + attach(&mut held, Attach::Save(id)); + held.state.dialog = Arc::new(Fixed(directory.path().join("copy.txt"))); + attach(&mut held, Attach::Save("gone".to_owned())); + + assert!(!directory.path().join("copy.txt").exists()); + assert_eq!(held.failed(), None); +} + +#[test] +fn a_save_that_cannot_be_written_is_said() { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(Fixed(directory.path().join("plan.txt").join("copy.txt"))); + attach(&mut held, Attach::Save(id)); + + assert!(held.failed().is_some()); +} + +#[test] +fn an_attachment_is_handed_to_the_desktop_and_a_refusal_is_said() { + let (mut held, id, _directory) = with_a_file(); + attach(&mut held, Attach::Open(id.clone())); + assert_eq!(held.state.errors.notice().unwrap().key, i18n::keys::errors::ATTACHMENT_OPEN_FAILED); + + let opened = Opened::default(); + held.state.opener = Arc::new(opened.clone()); + attach(&mut held, Attach::Open(id)); + let paths = opened.0.lock().unwrap(); + assert_eq!(paths.len(), 1); + assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "the plan"); +} + +#[test] +fn a_picture_attached_is_shown_at_once_until_it_is_removed() { + let (mut held, _, directory) = with_a_file(); + let picture = directory.path().join("plan.png"); + image::RgbaImage::from_pixel(4, 4, image::Rgba([240, 160, 40, 255])) + .save(&picture) + .unwrap(); + attach(&mut held, Attach::Dropped(vec![picture])); + let mut listed = held.state.attachments.list().iter(); + let id = listed.find(|file| file.file_name == "plan.png").unwrap().id.clone(); + assert_eq!(held.state.attachments.preview_id(), Some(id.as_str())); + attach(&mut held, Attach::Zoom(true)); + assert_eq!(held.state.attachments.zoomed().unwrap().0, "plan.png"); + + attach(&mut held, Attach::Remove(id)); + assert_eq!(held.state.attachments.list().len(), 1); + assert_eq!(held.state.attachments.preview_id(), None); + assert!(held.state.attachments.zoomed().is_none()); +} + +/// Anything else is opened, not shown. +#[test] +fn a_text_has_no_preview() { + let (mut held, id, _directory) = with_a_file(); + attach(&mut held, Attach::TogglePreview(id)); + + assert_eq!(held.state.attachments.preview_id(), None); +} + +#[test] +fn what_is_refused_about_a_file_is_said() { + let asked: [fn(String) -> Attach; 3] = [Attach::Open, Attach::Save, Attach::Remove]; + for asked in asked { + let (mut held, id, directory) = with_a_file(); + held.state.dialog = Arc::new(Fixed(directory.path().join("copy.txt"))); + held.close_library(); + attach(&mut held, asked(id.clone())); + assert!(held.failed().is_some(), "{:?}", asked(id)); + } +} + +// The editor + +#[test] +fn a_note_that_cannot_be_read_closes_the_editor_and_says_so() { + let (mut held, _) = with_a_note(); + held.notes(Notes::OpenNote("gone".to_owned())); + + assert!(!held.state.editor.is_open()); + assert!(held.failed().is_some()); +} + +/// What was typed stays on screen: nothing says it is written. +#[test] +fn a_draft_that_cannot_be_written_says_so_and_stays_a_draft() { + let (mut held, _) = with_a_note(); + held.notes(Notes::NewNote(Some(NoteKind::Snippet))); + held.close_library(); + let session = held.state.editor.opened().unwrap().session; + let edit = super::editor::Edit { title: Some("typed".to_owned()), ..Default::default() }; + held.notes(Notes::Editor(Editing::Save { session, edit })); + + assert!(held.failed().is_some()); + assert!(held.state.editor.opened().unwrap().is_draft()); +} + +#[test] +fn an_edit_of_a_note_closed_since_or_of_nothing_is_left_alone() { + let (mut held, id) = with_a_note(); + held.notes(Notes::OpenNote(id.clone())); + let session = held.state.editor.opened().unwrap().session; + let save = |held: &mut Held, session, edit| held.notes(Notes::Editor(Editing::Save { session, edit })); + + let launched = held.backend.launched(); + save(&mut held, session, super::editor::Edit::default()); + assert_eq!(held.backend.launched(), launched, "nothing left, nothing asked"); + let edit = super::editor::Edit { title: Some("late".to_owned()), ..Default::default() }; + save(&mut held, session + 7, edit); + assert_eq!(held.note(&id).title, "psql"); +} + +#[test] +fn a_step_past_the_first_or_the_last_card_stays_where_it_is() { + let (mut held, id) = with_a_note(); + held.notes(Notes::Editor(Editing::Step(1))); + assert!(!held.state.editor.is_open()); + held.notes(Notes::OpenNote(id.clone())); + for by in [1, -1] { + held.notes(Notes::Editor(Editing::Step(by))); + assert_eq!(held.state.editor.open_id(), Some(id.as_str())); + } +} diff --git a/crates/ui/src/testing.rs b/crates/ui/src/testing.rs index e503a6577..ddf3f6d3d 100644 --- a/crates/ui/src/testing.rs +++ b/crates/ui/src/testing.rs @@ -10,10 +10,7 @@ pub(crate) fn harness() -> HarnessBuilder { /// One frame of `ctx` at `time`, outside a harness. pub(crate) fn frame(ctx: &egui::Context, time: f64, draw: impl FnMut(&mut egui::Ui)) { - let input = egui::RawInput { - time: Some(time), - ..Default::default() - }; + let input = egui::RawInput { time: Some(time), ..Default::default() }; let mut output = ctx.run_ui(input, draw); // Nothing renders here: the textures are not uploaded anywhere. output.textures_delta.clear(); @@ -52,9 +49,7 @@ pub(crate) fn backend() -> (crate::backend::Backend, tempfile::TempDir) { /// A real core over `profile`, as a later launch finds it. pub(crate) fn backend_on(profile: &std::path::Path) -> crate::backend::Backend { - let paths = engine::Paths { - profile: profile.to_path_buf(), - }; + let paths = engine::Paths { profile: profile.to_path_buf() }; crate::backend::Backend::start( paths, std::sync::Arc::new(engine::RecordingSink::default()), @@ -69,8 +64,7 @@ pub(crate) const PASSPHRASE: &str = "correct horse battery staple"; /// A real library, created and open, through the same calls the gate makes. pub(crate) fn unlocked() -> (crate::backend::Backend, tempfile::TempDir) { let (backend, profile) = backend(); - let mut created = - crate::api::vault::create(&backend, zeroize::Zeroizing::new(PASSPHRASE.to_string())); + let mut created = crate::api::vault::create(&backend, zeroize::Zeroizing::new(PASSPHRASE.to_string())); backend.settle(); created.poll().unwrap().unwrap(); (backend, profile) @@ -96,19 +90,14 @@ pub(crate) fn snippet(space_id: String, title: String) -> engine::notes::model:: } /// A snippet titled `title` in the library's first space, made if there is none, written through the core. -pub(crate) fn note( - backend: &crate::backend::Backend, - title: &str, -) -> engine::notes::model::DisplayNote { +pub(crate) fn note(backend: &crate::backend::Backend, title: &str) -> engine::notes::model::DisplayNote { let title = title.to_string(); let mut created = backend.db(move |engine| { let space = match engine::spaces::list_spaces(engine)?.into_iter().next() { Some(space) => space, None => engine::spaces::create_space( engine, - &engine::spaces::model::SpaceDraft { - name: "Home".to_string(), - }, + &engine::spaces::model::SpaceDraft { name: "Home".to_string() }, )?, }; engine::notes::create_note(engine, snippet(space.id, title)) @@ -138,9 +127,8 @@ pub(crate) fn corpus(backend: &crate::backend::Backend, count: usize) { draft: snippet(String::new(), format!("note {index}")), }) .collect(); - let mut seeded = backend.db(move |engine| { - engine::notes::seed_samples(engine, "Corpus".to_string(), &Vec::new(), notes) - }); + let mut seeded = backend + .db(move |engine| engine::notes::seed_samples(engine, "Corpus".to_string(), &Vec::new(), notes)); backend.settle(); seeded.poll().unwrap().unwrap(); } @@ -174,7 +162,7 @@ pub(crate) fn slow_arrived(port: u16) -> bool { } /// A server on this machine for the sends of a test: `/json` answers a small JSON, `/slow` the -/// same after five seconds, anything else a 404. Each connection is answered once, then closed. +/// same after five seconds, `/empty` no body, anything else a 404. Each connection is answered once, then closed. pub(crate) fn serve() -> u16 { use std::io::{Read, Write}; let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).expect("a local port is free"); @@ -208,22 +196,21 @@ pub(crate) fn serve() -> u16 { let (status, body) = if path.starts_with("/big") { // A megabyte of JSON, laid out on one line: the budget's answer. let rows: Vec = (0..14_000) - .map(|at| { - format!(r#"{{"id":{at},"name":"row {at}","tags":["a","b"],"on":true}}"#) - }) + .map(|at| format!(r#"{{"id":{at},"name":"row {at}","tags":["a","b"],"on":true}}"#)) .collect(); ("200 OK", format!("[{}]", rows.join(","))) - } else if path.starts_with("/json") - || path.starts_with("/slow") - || path.starts_with("/image") + } else if path.starts_with("/json") || path.starts_with("/slow") || path.starts_with("/image") { - ( - "200 OK", - r#"{"name":"Ada","languages":["fr","en"],"admin":true}"#.to_owned(), - ) + ("200 OK", r#"{"name":"Ada","languages":["fr","en"],"admin":true}"#.to_owned()) } else { ("404 Not Found", "missing".to_owned()) }; + if path.starts_with("/empty") { + let answer = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\ + Content-Length: 0\r\nConnection: close\r\n\r\n"; + let _ = stream.write_all(answer.as_bytes()); + return; + } if path.starts_with("/redirect") { let answer = "HTTP/1.1 302 Found\r\nLocation: /json\r\n\ Content-Length: 0\r\nConnection: close\r\n\r\n"; diff --git a/crates/ui/src/theme/focus.rs b/crates/ui/src/theme/focus.rs index 4be955b28..17969243f 100644 --- a/crates/ui/src/theme/focus.rs +++ b/crates/ui/src/theme/focus.rs @@ -17,9 +17,7 @@ enum Modality { pub fn track(ctx: &Context) { let last = ctx.input(|input| { input.events.iter().rev().find_map(|event| match event { - Event::Key { - key, pressed: true, .. - } if navigates(*key) => Some(Modality::Keyboard), + Event::Key { key, pressed: true, .. } if navigates(*key) => Some(Modality::Keyboard), Event::PointerButton { pressed: true, .. } => Some(Modality::Pointer), _ => None, }) @@ -54,8 +52,7 @@ fn modality_id() -> Id { /// Whether `response` wears the ring this frame. pub fn visible(ctx: &Context, response: &Response) -> bool { response.has_focus() - && ctx.data(|data| data.get_temp::(modality_id()).unwrap_or_default()) - == Modality::Keyboard + && ctx.data(|data| data.get_temp::(modality_id()).unwrap_or_default()) == Modality::Keyboard } /// The ring around `response`, following its corners two pixels out. diff --git a/crates/ui/src/theme/fonts.rs b/crates/ui/src/theme/fonts.rs index 34226e250..2aa8c8070 100644 --- a/crates/ui/src/theme/fonts.rs +++ b/crates/ui/src/theme/fonts.rs @@ -8,34 +8,18 @@ use std::sync::{Arc, LazyLock}; use egui::{FontData, FontDefinitions, FontFamily, FontId, TextStyle}; const FACES: [(&str, &[u8]); 5] = [ - ( - "inter-latin", - include_bytes!("../../assets/fonts/inter-latin-wght-normal.ttf"), - ), - ( - "inter-latin-ext", - include_bytes!("../../assets/fonts/inter-latin-ext-wght-normal.ttf"), - ), - ( - "jetbrains-mono-latin", - include_bytes!("../../assets/fonts/jetbrains-mono-latin-wght-normal.ttf"), - ), + ("inter-latin", include_bytes!("../../assets/fonts/inter-latin-wght-normal.ttf")), + ("inter-latin-ext", include_bytes!("../../assets/fonts/inter-latin-ext-wght-normal.ttf")), + ("jetbrains-mono-latin", include_bytes!("../../assets/fonts/jetbrains-mono-latin-wght-normal.ttf")), ( "jetbrains-mono-latin-ext", include_bytes!("../../assets/fonts/jetbrains-mono-latin-ext-wght-normal.ttf"), ), - ( - "noto-emoji", - include_bytes!("../../assets/fonts/NotoEmoji-wght.ttf"), - ), + ("noto-emoji", include_bytes!("../../assets/fonts/NotoEmoji-wght.ttf")), ]; const SANS: [&str; 3] = ["inter-latin", "inter-latin-ext", "noto-emoji"]; -const MONO: [&str; 3] = [ - "jetbrains-mono-latin", - "jetbrains-mono-latin-ext", - "noto-emoji", -]; +const MONO: [&str; 3] = ["jetbrains-mono-latin", "jetbrains-mono-latin-ext", "noto-emoji"]; /// The body's size: every other size of the reference is written against it. pub const BASE: f32 = 14.0; @@ -61,12 +45,8 @@ pub fn definitions() -> FontDefinitions { .insert(name.to_string(), FontData::from_static(bytes).into()); } let family = |names: [&str; 3]| names.iter().map(ToString::to_string).collect(); - definitions - .families - .insert(FontFamily::Proportional, family(SANS)); - definitions - .families - .insert(FontFamily::Monospace, family(MONO)); + definitions.families.insert(FontFamily::Proportional, family(SANS)); + definitions.families.insert(FontFamily::Monospace, family(MONO)); definitions } diff --git a/crates/ui/src/theme/icons.rs b/crates/ui/src/theme/icons.rs index 8c1b6f888..2c88e8356 100644 --- a/crates/ui/src/theme/icons.rs +++ b/crates/ui/src/theme/icons.rs @@ -81,7 +81,6 @@ pub enum Icon { Fold, Unfold, Paperclip, - Image, Hourglass, /// A snippet's `{{fields}}`, on its card. Zap, @@ -119,10 +118,9 @@ impl Icon { fn paths(self) -> &'static [&'static str] { match self { Self::ArrowLeftRight => &["m8 3-4 4 4 4", "M4 7h16", "m16 21 4-4-4-4", "M20 17H4"], - Self::Sidebar => &[ - "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", - "M9 3v18", - ], + Self::Sidebar => { + &["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", "M9 3v18"] + } Self::Trash => &[ "M3 6h18", "M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6", @@ -153,10 +151,7 @@ impl Icon { Self::Format => &["M4 6h16", "M4 12h10", "M4 18h13"], Self::Ellipsis => &["M12 12h.01", "M19 12h.01", "M5 12h.01"], Self::ArrowUpRight => &["M7 7h10v10", "M7 17 17 7"], - Self::Flag => &[ - "M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z", - "M4 22v-7", - ], + Self::Flag => &["M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z", "M4 22v-7"], Self::CopyPlus => &[ "M15 12v6", "M12 15h6", @@ -186,29 +181,16 @@ impl Icon { "M12 7v14", "M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z", ], - Self::Bold => { - &["M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"] - } + Self::Bold => &["M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8"], Self::Italic => &["M19 4h-9", "M14 20H5", "M15 4 9 20"], - Self::Strike => &[ - "M16 4H9a3 3 0 0 0-2.83 4", - "M14 12a4 4 0 0 1 0 8H6", - "M4 12h16", - ], + Self::Strike => &["M16 4H9a3 3 0 0 0-2.83 4", "M14 12a4 4 0 0 1 0 8H6", "M4 12h16"], Self::Code => &["m16 18 6-6-6-6", "m8 6-6 6 6 6"], Self::Save => &[ "M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", "M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7", "M7 3v4a1 1 0 0 0 1 1h7", ], - Self::ListBullet => &[ - "M3 12h.01", - "M3 18h.01", - "M3 6h.01", - "M8 12h13", - "M8 18h13", - "M8 6h13", - ], + Self::ListBullet => &["M3 12h.01", "M3 18h.01", "M3 6h.01", "M8 12h13", "M8 18h13", "M8 6h13"], Self::ListOrdered => &[ "M10 12h11", "M10 18h11", @@ -217,13 +199,7 @@ impl Icon { "M4 6h1v4", "M6 18H4c0-1 2-2 2-3s-1-1.5-2-1", ], - Self::ListTasks => &[ - "m3 17 2 2 4-4", - "m3 7 2 2 4-4", - "M13 6h8", - "M13 12h8", - "M13 18h8", - ], + Self::ListTasks => &["m3 17 2 2 4-4", "m3 7 2 2 4-4", "M13 6h8", "M13 12h8", "M13 18h8"], Self::Quote => &["M17 6H3", "M21 12H8", "M21 18H8", "M3 12v6"], Self::Link => &[ "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71", @@ -255,11 +231,7 @@ impl Icon { "M15.5 8.5 18 6", ], Self::Clock => &["M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20z", "M12 6v6l4 2"], - Self::Info => &[ - "M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20z", - "M12 16v-4", - "M12 8h.01", - ], + Self::Info => &["M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20z", "M12 16v-4", "M12 8h.01"], Self::Calculator => &[ "M6 2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2z", "M8 6h8", @@ -286,10 +258,9 @@ impl Icon { "M9 13h6", "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z", ], - Self::Eye => &[ - "M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z", - "M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z", - ], + Self::Eye => { + &["M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z", "M12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z"] + } Self::EyeOff => &[ "M9.88 9.88a3 3 0 1 0 4.24 4.24", "M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68", @@ -304,11 +275,6 @@ impl Icon { Self::Paperclip => &[ "m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48", ], - Self::Image => &[ - "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", - "M9 7a2 2 0 1 0 0 4a2 2 0 1 0 0-4z", - "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21", - ], Self::TriangleAlert => &[ "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3", "M12 9v4", @@ -333,29 +299,20 @@ impl Icon { "M5.5 8h9a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 4 18.5v-9A1.5 1.5 0 0 1 5.5 8z", "M8 8V5.5A1.5 1.5 0 0 1 9.5 4h9A1.5 1.5 0 0 1 20 5.5v9a1.5 1.5 0 0 1-1.5 1.5H16", ], - Self::Square => { - &["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"] - } + Self::Square => &["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"], Self::Circle => &["M12 2a10 10 0 1 0 0 20a10 10 0 1 0 0-20z"], Self::Diamond => &["M12 2.7 21.3 12 12 21.3 2.7 12z"], Self::Pencil => &[ "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z", "m15 5 4 4", ], - Self::Undo => &[ - "M9 14 4 9l5-5", - "M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11", - ], - Self::Redo => &[ - "m15 14 5-5-5-5", - "M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13", - ], + Self::Undo => &["M9 14 4 9l5-5", "M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11"], + Self::Redo => &["m15 14 5-5-5-5", "M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13"], Self::Play => &["M6 3 20 12 6 21z"], Self::CodeXml => &["m18 16 4-4-4-4", "m6 8-4 4 4 4", "m14.5 4-5 16"], - Self::SquareCheck => &[ - "M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", - "m9 12 2 2 4-4", - ], + Self::SquareCheck => { + &["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", "m9 12 2 2 4-4"] + } Self::Sigma => &[ "M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2", ], @@ -380,11 +337,7 @@ impl Icon { } fn svg(self) -> String { - let fill = if matches!(self, Self::StarFilled | Self::PinFilled) { - "white" - } else { - "none" - }; + let fill = if matches!(self, Self::StarFilled | Self::PinFilled) { "white" } else { "none" }; let paths = self.paths().iter().fold(String::new(), |mut paths, d| { let _ = write!(paths, ""); paths @@ -426,11 +379,7 @@ fn texture(ctx: &Context, icon: Icon, pixels: u32) -> Option { return cached; } let mask = rasterise(icon, pixels)?; - let texture = ctx.load_texture( - format!("icon-{icon:?}-{pixels}"), - mask, - TextureOptions::LINEAR, - ); + let texture = ctx.load_texture(format!("icon-{icon:?}-{pixels}"), mask, TextureOptions::LINEAR); ctx.data_mut(|data| { let cache = data.get_temp_mut_or_default::(cache_id()); Arc::make_mut(cache).insert((icon, pixels), texture.clone()); @@ -444,11 +393,7 @@ fn rasterise(icon: Icon, pixels: u32) -> Option { let mut pixmap = resvg::tiny_skia::Pixmap::new(pixels, pixels)?; #[allow(clippy::cast_precision_loss)] let scale = pixels as f32 / 24.0; - resvg::render( - &tree, - resvg::tiny_skia::Transform::from_scale(scale, scale), - &mut pixmap.as_mut(), - ); + resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut()); let size = [pixmap.width() as usize, pixmap.height() as usize]; Some(ColorImage::from_rgba_premultiplied(size, pixmap.data())) } @@ -457,7 +402,7 @@ fn rasterise(icon: Icon, pixels: u32) -> Option { mod tests { use super::*; - const ALL: [Icon; 82] = [ + const ALL: [Icon; 81] = [ Icon::ArrowLeftRight, Icon::MoveHorizontal, Icon::Sidebar, @@ -517,7 +462,6 @@ mod tests { Icon::Fold, Icon::Unfold, Icon::Paperclip, - Icon::Image, Icon::Hourglass, Icon::Zap, Icon::TriangleAlert, @@ -552,10 +496,7 @@ mod tests { let mask = rasterise(icon, 32).unwrap_or_else(|| panic!("{icon:?} did not parse")); assert!(coverage(&mask) > 0, "{icon:?} is empty"); - assert!( - mask.pixels.iter().all(|pixel| pixel.r() == pixel.a()), - "{icon:?} is not a white mask" - ); + assert!(mask.pixels.iter().all(|pixel| pixel.r() == pixel.a()), "{icon:?} is not a white mask"); } } diff --git a/crates/ui/src/theme/literals.rs b/crates/ui/src/theme/literals.rs index 453033372..b738c17c3 100644 --- a/crates/ui/src/theme/literals.rs +++ b/crates/ui/src/theme/literals.rs @@ -37,18 +37,14 @@ fn no_gap_radius_or_text_size_is_written_outside_the_theme() { } } - assert!( - offenders.is_empty(), - "gaps, radii or sizes outside theme::tokens: {offenders:#?}" - ); + assert!(offenders.is_empty(), "gaps, radii or sizes outside theme::tokens: {offenders:#?}"); } /// An item spacing, or a gap constant of the interface's (`f32`, a point or more), set to a number /// other than zero: a factor (`0.7` em) or a count of QR modules is not a gap. fn writes_a_spacing(line: &str) -> bool { let line = line.trim(); - let named_gap = - (line.starts_with("const ") || line.contains(" const ")) && line.contains(": f32 ="); + let named_gap = (line.starts_with("const ") || line.contains(" const ")) && line.contains(": f32 ="); let named_gap = named_gap && ["GAP", "PAD", "MARGIN", "INSET", "SPACING"] .iter() @@ -58,21 +54,13 @@ fn writes_a_spacing(line: &str) -> bool { return false; } let value = line.split('=').nth(1).unwrap_or_default(); - numbers(value).any(|number| { - if named_gap { - number >= 1.0 - } else { - number != 0.0 - } - }) + numbers(value).any(|number| if named_gap { number >= 1.0 } else { number != 0.0 }) } /// A text's `(size, weight)` with the size typed: `(12.5, 600.0)`, handed to a helper that /// draws text. A call's parenthesis (`vec2(12.0, 400.0)`) is a size on screen, not this. fn writes_a_size_and_weight(line: &str) -> bool { - const WEIGHTS: [&str; 7] = [ - "300.0", "400.0", "500.0", "600.0", "650.0", "700.0", "800.0", - ]; + const WEIGHTS: [&str; 7] = ["300.0", "400.0", "500.0", "600.0", "650.0", "700.0", "800.0"]; line.match_indices('(').any(|(at, _)| { let called = line[..at] .chars() @@ -160,21 +148,11 @@ fn the_sweep_sees_a_typed_gap_radius_or_size() { assert!(!writes_a_spacing("ui.spacing_mut().item_spacing.y = 0.0;")); assert!(!writes_a_spacing("const GAP: f32 = gap::INSET;")); assert_eq!(literal_calls("CornerRadius::same(6)").len(), 1); - assert_eq!( - literal_calls("widgets::text(ui, &words, 12.5, 400.0, family, ink)").len(), - 1 - ); - assert_eq!( - literal_calls("widgets::one_line(ui, &words, (12.5, 400.0), ink, 80.0)").len(), - 1 - ); + assert_eq!(literal_calls("widgets::text(ui, &words, 12.5, 400.0, family, ink)").len(), 1); + assert_eq!(literal_calls("widgets::one_line(ui, &words, (12.5, 400.0), ink, 80.0)").len(), 1); assert!(literal_calls("CornerRadius::same(radius::CONTROL)").is_empty()); - assert!(writes_a_size_and_weight( - "paragraph(ui, &words, (13.0, 600.0), ink);" - )); - assert!(!writes_a_size_and_weight( - "paragraph(ui, &words, (font::READING, 600.0), ink);" - )); + assert!(writes_a_size_and_weight("paragraph(ui, &words, (13.0, 600.0), ink);")); + assert!(!writes_a_size_and_weight("paragraph(ui, &words, (font::READING, 600.0), ink);")); assert!(!writes_a_size_and_weight("let size = vec2(12.0, 400.0);")); assert!(literal_calls("widgets::text(ui, &words, font::BODY, 400.0, f, ink)").is_empty()); } diff --git a/crates/ui/src/theme/mod.rs b/crates/ui/src/theme/mod.rs index a617c5c6e..5812cc172 100644 --- a/crates/ui/src/theme/mod.rs +++ b/crates/ui/src/theme/mod.rs @@ -91,10 +91,7 @@ fn style(palette: &Palette, theme: Theme) -> Style { ..Style::default() }; // 9 px, a rounded handle on no rail. - style.spacing.scroll = ScrollStyle { - bar_width: 9.0, - ..ScrollStyle::solid() - }; + style.spacing.scroll = ScrollStyle { bar_width: 9.0, ..ScrollStyle::solid() }; style } @@ -122,36 +119,11 @@ fn visuals(palette: &Palette, theme: Theme) -> Visuals { let widgets = &mut visuals.widgets; for (state, fill, edge, text) in [ - ( - &mut widgets.noninteractive, - palette.bg_1, - palette.line_soft, - palette.text_1, - ), - ( - &mut widgets.inactive, - palette.bg_2, - palette.line, - palette.text_0, - ), - ( - &mut widgets.hovered, - palette.bg_3, - palette.amber_dim, - palette.text_0, - ), - ( - &mut widgets.active, - palette.bg_3, - palette.amber_edge, - palette.text_0, - ), - ( - &mut widgets.open, - palette.bg_2, - palette.line, - palette.text_0, - ), + (&mut widgets.noninteractive, palette.bg_1, palette.line_soft, palette.text_1), + (&mut widgets.inactive, palette.bg_2, palette.line, palette.text_0), + (&mut widgets.hovered, palette.bg_3, palette.amber_dim, palette.text_0), + (&mut widgets.active, palette.bg_3, palette.amber_edge, palette.text_0), + (&mut widgets.open, palette.bg_2, palette.line, palette.text_0), ] { state.bg_fill = fill; state.weak_bg_fill = fill; diff --git a/crates/ui/src/theme/motion.rs b/crates/ui/src/theme/motion.rs index eab743685..780467b28 100644 --- a/crates/ui/src/theme/motion.rs +++ b/crates/ui/src/theme/motion.rs @@ -1,15 +1,10 @@ -//! The reference's durations and its three entrances, the only motion the interface has. One -//! switch, [`set_reduced`], turns all of it off, like the reference's single +//! The reference's durations, the only motion the interface has. One switch, [`set_reduced`], turns all of it off, like the reference's single //! `prefers-reduced-motion` block: what is added later is cut without being named. -use egui::emath::easing; use egui::{Context, Id, Pos2, Stroke, Ui}; /// What follows the pointer: a hover fill, a chip's state, a control appearing under it. pub const FAST: f32 = 0.12; -/// What enters: a menu, a dialog, a transient bar. Anything slower reads as lag on a tool -/// used in bursts. -pub const ENTER: f32 = 0.16; /// A spinner's turn, the one motion that lasts. pub const TURN: f32 = 0.8; /// Not a motion: how long a mark left by an action takes to fade, so the eye can find it. @@ -26,25 +21,6 @@ pub const TYPING_HEAVY: f32 = 0.25; /// beats it. pub const LAYOUT_SAVE: f32 = 0.4; -/// Where an element comes from when it appears: a short rise or lift, or a fade — never a size. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Entrance { - /// From 4 px above: what opens downwards, a menu. - Rise, - /// From 4 px below: what opens upwards, a bar at the bottom. - Lift, - Fade, -} - -/// How far into its entrance an element is: its opacity, and the vertical offset to draw it at. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Entering { - pub opacity: f32, - pub offset: f32, -} - -const DISTANCE: f32 = 4.0; - /// Turns every animation off, egui's own included. pub fn set_reduced(ctx: &Context, reduced: bool) { ctx.data_mut(|data| data.insert_temp(reduced_id(), reduced)); @@ -59,42 +35,6 @@ fn reduced_id() -> Id { Id::unique("theme.motion.reduced") } -/// An element drawn this frame under `id`: it enters from the first frame it is drawn after -/// a frame it was not, as a CSS animation runs on an element that did not exist a frame ago. -pub fn enter(ctx: &Context, id: Id, entrance: Entrance) -> Entering { - let now = ctx.input(|input| input.time); - let frame = ctx.cumulative_frame_nr(); - let started = ctx.data_mut(|data| { - let seen = data.get_temp_mut_or(id.with("entered"), (now, frame)); - if seen.1 + 1 < frame { - seen.0 = now; - } - seen.1 = frame; - seen.0 - }); - if reduced(ctx) { - return Entering { - opacity: 1.0, - offset: 0.0, - }; - } - #[allow(clippy::cast_possible_truncation)] - let progress = (((now - started) as f32) / ENTER).clamp(0.0, 1.0); - if progress < 1.0 { - ctx.request_repaint(); - } - let eased = easing::cubic_out(progress); - let from = match entrance { - Entrance::Rise => -DISTANCE, - Entrance::Lift => DISTANCE, - Entrance::Fade => 0.0, - }; - Entering { - opacity: eased, - offset: from * (1.0 - eased), - } -} - /// What is left of a mark set at `since` (in `input.time`): 1 when set, 0 once faded. pub fn fading(ctx: &Context, since: f64) -> f32 { if reduced(ctx) { @@ -142,43 +82,11 @@ mod tests { } #[test] - fn an_element_enters_once_and_again_after_it_was_gone() { - let ctx = Context::default(); - let id = Id::unique("menu"); - let mut seen = Vec::new(); - - for (time, drawn) in [ - (0.0, true), - (0.08, true), - (1.0, true), - (1.1, false), - (1.2, true), - ] { - frame(&ctx, time, |ctx| { - if drawn { - seen.push(enter(ctx, id, Entrance::Rise)); - } - }); - } - - assert!(seen[0].opacity < f32::EPSILON && (seen[0].offset + DISTANCE).abs() < 0.01); - assert!(seen[1].opacity > 0.0 && seen[1].opacity < 1.0); - assert!( - (seen[2].opacity - 1.0).abs() < f32::EPSILON && seen[2].offset.abs() < f32::EPSILON - ); - assert!(seen[3].opacity < f32::EPSILON, "it entered again"); - } - - #[test] - fn reduced_motion_cuts_every_entrance_and_mark() { + fn reduced_motion_cuts_every_mark() { let ctx = Context::default(); set_reduced(&ctx, true); frame(&ctx, 0.0, |ctx| { - assert!( - (enter(ctx, Id::unique("dialog"), Entrance::Lift).opacity - 1.0).abs() - < f32::EPSILON - ); assert!(fading(ctx, 0.0) < f32::EPSILON); }); assert!(ctx.global_style().animation_time < f32::EPSILON); @@ -212,10 +120,7 @@ mod tests { } } - assert!( - offenders.is_empty(), - "durations outside theme::motion: {offenders:?}" - ); + assert!(offenders.is_empty(), "durations outside theme::motion: {offenders:?}"); } fn writes_a_duration(line: &str) -> bool { @@ -239,14 +144,9 @@ mod tests { /// A constant named for a wait and set to a number: the escape the calls' check left open. fn names_a_duration(line: &str) -> bool { - const WAITS: [&str; 6] = [ - "DEBOUNCE", "DELAY", "FEEDBACK", "TIMEOUT", "DURATION", "LINGER", - ]; + const WAITS: [&str; 6] = ["DEBOUNCE", "DELAY", "FEEDBACK", "TIMEOUT", "DURATION", "LINGER"]; let line = line.trim(); - let Some((name, value)) = line - .split_once("const ") - .and_then(|(_, rest)| rest.split_once('=')) - else { + let Some((name, value)) = line.split_once("const ").and_then(|(_, rest)| rest.split_once('=')) else { return false; }; let seconds = name.contains(": f32") || name.contains(": f64"); @@ -276,12 +176,8 @@ mod tests { #[test] fn the_sweep_sees_a_typed_duration() { assert!(writes_a_duration("ctx.animate_bool_with_time(id, on, 0.2)")); - assert!(writes_a_duration( - "ctx.request_repaint_after(Duration::from_millis(300))" - )); - assert!(!writes_a_duration( - "ctx.animate_bool_with_time(id, on, motion::FAST)" - )); + assert!(writes_a_duration("ctx.request_repaint_after(Duration::from_millis(300))")); + assert!(!writes_a_duration("ctx.animate_bool_with_time(id, on, motion::FAST)")); assert!(names_a_duration("const DEBOUNCE: f64 = 0.250;")); assert!(!names_a_duration("const DEBOUNCE: f32 = motion::TYPING;")); assert!(!names_a_duration("const SHORTEST_TIMEOUT: u32 = 100;")); diff --git a/crates/ui/src/theme/tokens.rs b/crates/ui/src/theme/tokens.rs index 41c55de4a..2fe264394 100644 --- a/crates/ui/src/theme/tokens.rs +++ b/crates/ui/src/theme/tokens.rs @@ -1,10 +1,7 @@ //! The variables of the Angular reference's `styles.scss`, one for one: the dark //! palette is the base, the light one redefines what a light surface needs, and the compact //! density tightens four gaps and nothing else. -#![allow( - clippy::unreadable_literal, - reason = "written as the CSS writes them, so that a search finds both" -)] +#![allow(clippy::unreadable_literal, reason = "written as the CSS writes them, so that a search finds both")] use egui::Color32; use egui::epaint::Shadow; @@ -128,19 +125,9 @@ pub struct Spacing { pub canvas: f32, } -pub const COMFORTABLE: Spacing = Spacing { - card: 14.0, - grid: 12.0, - section: 28.0, - canvas: 24.0, -}; +pub const COMFORTABLE: Spacing = Spacing { card: 14.0, grid: 12.0, section: 28.0, canvas: 24.0 }; -pub const COMPACT: Spacing = Spacing { - card: 10.0, - grid: 8.0, - section: 18.0, - canvas: 16.0, -}; +pub const COMPACT: Spacing = Spacing { card: 10.0, grid: 8.0, section: 18.0, canvas: 16.0 }; /// The type scale: each size named by what it is for, defined once. A screen picks a role, never /// a number; changing a role's value changes every text that plays it. @@ -195,10 +182,7 @@ pub mod gap { pub const PAGE: f32 = 28.0; /// A frame's margin, from two gaps (`0.0` for none). - #[expect( - clippy::cast_possible_truncation, - reason = "the scale's steps are whole and small" - )] + #[expect(clippy::cast_possible_truncation, reason = "the scale's steps are whole and small")] pub const fn margin(x: f32, y: f32) -> egui::Margin { egui::Margin::symmetric(x as i8, y as i8) } @@ -241,12 +225,7 @@ const fn hex(rgb: u32) -> Color32 { /// `0 px px rgba(0, 0, 0, )`, the only shape of shadow the reference draws; /// the alpha in bytes (0.35 is 89). const fn shadow(y: i8, blur: u8, alpha: u8) -> Shadow { - Shadow { - offset: [0, y], - blur, - spread: 0, - color: Color32::from_black_alpha(alpha), - } + Shadow { offset: [0, y], blur, spread: 0, color: Color32::from_black_alpha(alpha) } } #[cfg(test)] @@ -265,11 +244,7 @@ mod tests { fn luminance(colour: Color32) -> f64 { let channel = |raw: u8| { let part = f64::from(raw) / 255.0; - if part <= 0.039_28 { - part / 12.92 - } else { - ((part + 0.055) / 1.055).powf(2.4) - } + if part <= 0.039_28 { part / 12.92 } else { ((part + 0.055) / 1.055).powf(2.4) } }; 0.2126 * channel(colour.r()) + 0.7152 * channel(colour.g()) + 0.0722 * channel(colour.b()) } @@ -340,13 +315,9 @@ mod tests { } = *palette; Roles { surfaces: [bg_0, bg_1, bg_2, bg_3], - text: [ - text_0, text_1, text_2, amber_text, green, blue, red, purple, teal, pink, olive, - ], + text: [text_0, text_1, text_2, amber_text, green, blue, red, purple, teal, pink, olive], edges: [amber_edge], - tinted: [ - amber_fill, green, blue, red, purple, teal, pink, olive, text_1, - ], + tinted: [amber_fill, green, blue, red, purple, teal, pink, olive, text_1], status: [green, blue, amber_fill, red], } } @@ -363,10 +334,7 @@ mod tests { for text in roles.text { for surface in roles.surfaces { let ratio = contrast(text, surface); - assert!( - ratio >= AA, - "{theme}: {text:?} on {surface:?} is {ratio:.2}:1" - ); + assert!(ratio >= AA, "{theme}: {text:?} on {surface:?} is {ratio:.2}:1"); } } }); @@ -380,10 +348,7 @@ mod tests { for surface in roles.surfaces { let tinted = mix(hue, surface, MAX_TINT); let ratio = contrast(palette.text_1, tinted); - assert!( - ratio >= AA, - "{theme}: a badge on a {hue:?} tint is {ratio:.2}:1" - ); + assert!(ratio >= AA, "{theme}: a badge on a {hue:?} tint is {ratio:.2}:1"); } } }); @@ -410,10 +375,7 @@ mod tests { for edge in roles.edges { for surface in roles.surfaces { let ratio = contrast(edge, surface); - assert!( - ratio >= AA_UI, - "{theme}: {edge:?} on {surface:?} is {ratio:.2}:1" - ); + assert!(ratio >= AA_UI, "{theme}: {edge:?} on {surface:?} is {ratio:.2}:1"); } } }); diff --git a/crates/ui/src/titlebar/about_menu/card.rs b/crates/ui/src/titlebar/about_menu/card.rs index da7331aca..d768eace8 100644 --- a/crates/ui/src/titlebar/about_menu/card.rs +++ b/crates/ui/src/titlebar/about_menu/card.rs @@ -18,13 +18,9 @@ const VERSION: &str = env!("CARGO_PKG_VERSION"); /// `true` when it asks to close. pub(super) fn show(ctx: &egui::Context, state: &AppState, actions: &mut Actions) -> bool { let close = i18n::translate(state.language, keys::about::CLOSE, &[]); - let shown = widgets::dialog( - ctx, - &state.dialogs, - (super::id(), (&close, "about-close")), - WIDTH, - |ui| body(ui, state, actions), - ); + let shown = widgets::dialog(ctx, &state.dialogs, (super::id(), (&close, "about-close")), WIDTH, |ui| { + body(ui, state, actions); + }); shown.is_some_and(|shown| shown.should_close()) } @@ -40,18 +36,9 @@ fn body(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let p = palette(ui.ctx()); let tr = |key: Key| i18n::translate(language, key, &[]); ui.spacing_mut().item_spacing.y = gap::CONTROLS; - let name = Message::new(keys::about::TITLE) - .with("app", METADATA.name) - .text(language); + let name = Message::new(keys::about::TITLE).with("app", METADATA.name).text(language); ui.horizontal(|ui| { - let words = widgets::text( - ui, - &name, - font::HEADING, - 700.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &name, font::HEADING, 700.0, FontFamily::Proportional, p.text_0); let (rect, title) = ui.allocate_exact_size(words.size(), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); widgets::address(ui, &title, "about-dialog"); @@ -63,9 +50,7 @@ fn body(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ); widgets::address(ui, &version, "about-version"); }); - let description = RichText::new(tr(keys::about::DESCRIPTION)) - .size(font::BODY) - .color(p.text_1); + let description = RichText::new(tr(keys::about::DESCRIPTION)).size(font::BODY).color(p.text_1); ui.add(egui::Label::new(description).wrap()); ui.add_space(gap::TIGHT); let developer = format!("{} ({})", METADATA.author, METADATA.author_handle); @@ -74,21 +59,11 @@ fn body(ui: &mut Ui, state: &AppState, actions: &mut Actions) { }); fact(ui, &tr(keys::about::REPOSITORY), |ui| { let label = METADATA.repository.trim_start_matches("https://"); - if Button::new(label, "about-repository") - .icon(Icon::Link) - .show(ui) - .clicked() - { - actions.push(Asked::Menu(Action::OpenLink( - METADATA.repository.to_owned(), - ))); + if Button::new(label, "about-repository").icon(Icon::Link).show(ui).clicked() { + actions.push(Asked::Menu(Action::OpenLink(METADATA.repository.to_owned()))); } }); - let stack = format!( - "egui {} · Rust {}", - egui_version().unwrap_or("—"), - METADATA.rust_version - ); + let stack = format!("egui {} · Rust {}", egui_version().unwrap_or("—"), METADATA.rust_version); fact(ui, &tr(keys::about::BUILT_WITH), |ui| { ui.label(RichText::new(stack).size(font::LABEL).color(p.text_1)); }); @@ -98,14 +73,7 @@ fn fact(ui: &mut Ui, name: &str, value: impl FnOnce(&mut Ui)) { let p = palette(ui.ctx()); ui.horizontal(|ui| { let (rect, _) = ui.allocate_exact_size(egui::vec2(110.0, 18.0), Sense::hover()); - let words = widgets::text( - ui, - name, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let words = widgets::text(ui, name, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); ui.painter().galley(rect.min, words, p.text_2); value(ui); }); diff --git a/crates/ui/src/titlebar/about_menu/docs/mod.rs b/crates/ui/src/titlebar/about_menu/docs/mod.rs index b1d7e42c2..0ddf8ad57 100644 --- a/crates/ui/src/titlebar/about_menu/docs/mod.rs +++ b/crates/ui/src/titlebar/about_menu/docs/mod.rs @@ -5,8 +5,8 @@ mod page; mod text; use egui::{ - Align, Color32, CornerRadius, FontFamily, Layout, Rect, Role, Sense, Stroke, Ui, Vec2, - WidgetInfo, pos2, vec2, + Align, Color32, CornerRadius, FontFamily, Layout, Rect, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2, + vec2, }; use engine::docs::model::{Block, Page}; use engine::docs::search::Hit; @@ -91,13 +91,10 @@ pub(super) fn show( ) -> bool { let cross = i18n::translate(state.language, keys::docs::CLOSE, &[]); let mut asked = None; - let shown = widgets::framed_dialog( - ctx, - &state.dialogs, - (super::id(), (&cross, "docs-close")), - SIZE, - |ui| asked = body(ui, state, id, view), - ); + let shown = + widgets::framed_dialog(ctx, &state.dialogs, (super::id(), (&cross, "docs-close")), SIZE, |ui| { + asked = body(ui, state, id, view); + }); match asked { Some(Go::Page(id, section)) => { view.section = section; @@ -119,14 +116,8 @@ fn body(ui: &mut Ui, state: &AppState, id: &'static str, view: &mut View) -> Opt header(ui, state, whole); ui.painter().hline(whole.x_range(), top, line); - let rail = Rect::from_min_max( - pos2(whole.left(), top), - pos2(whole.left() + RAIL, whole.bottom()), - ); - let corner = CornerRadius { - sw: radius::DIALOG, - ..CornerRadius::ZERO - }; + let rail = Rect::from_min_max(pos2(whole.left(), top), pos2(whole.left() + RAIL, whole.bottom())); + let corner = CornerRadius { sw: radius::DIALOG, ..CornerRadius::ZERO }; ui.painter().rect_filled(rail, corner, p.bg_0); ui.painter().vline(rail.right(), rail.y_range(), line); let mut list = ui.new_child( @@ -137,29 +128,16 @@ fn body(ui: &mut Ui, state: &AppState, id: &'static str, view: &mut View) -> Opt let chosen = rail_content(&mut list, state, id, view); let room = Rect::from_min_max(pos2(rail.right(), top), whole.right_bottom()); - let mut reading = ui.new_child( - egui::UiBuilder::new() - .max_rect(room) - .layout(Layout::top_down(Align::Min)), - ); + let mut reading = + ui.new_child(egui::UiBuilder::new().max_rect(room).layout(Layout::top_down(Align::Min))); chosen.or(reader(&mut reading, state, id, view)) } fn header(ui: &mut Ui, state: &AppState, whole: Rect) { let p = palette(ui.ctx()); let title = i18n::translate(state.language, keys::docs::TITLE, &[]); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); - let at = pos2( - whole.left() + gap::PANEL, - whole.top() + (HEADER - words.size().y) / 2.0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); + let at = pos2(whole.left() + gap::PANEL, whole.top() + (HEADER - words.size().y) / 2.0); let heading = ui.allocate_rect(Rect::from_min_size(at, words.size()), Sense::hover()); ui.painter().galley(at, words, p.text_0); heading.widget_info(|| WidgetInfo::labeled(Role::Heading, true, &title)); @@ -171,26 +149,16 @@ fn rail_content(ui: &mut Ui, state: &AppState, id: &str, view: &mut View) -> Opt let whole = ui.max_rect(); let mut asked = search(ui, state, view); ui.add_space(gap::CONTROLS); - let list = Rect::from_min_max( - ui.cursor().min, - pos2(whole.right(), whole.bottom() - FOOTER), - ); - let mut area = ui.new_child( - egui::UiBuilder::new() - .max_rect(list) - .layout(Layout::top_down(Align::Min)), - ); - let scrolled = egui::ScrollArea::vertical() - .id_salt("docs-rail") - .auto_shrink(false) - .show(&mut area, |ui| { - ui.spacing_mut().item_spacing.y = gap::LINE; - if view.query.trim().is_empty() { - contents(ui, state, id) - } else { - results(ui, state, view) - } - }); + let list = Rect::from_min_max(ui.cursor().min, pos2(whole.right(), whole.bottom() - FOOTER)); + let mut area = ui.new_child(egui::UiBuilder::new().max_rect(list).layout(Layout::top_down(Align::Min))); + let scrolled = + egui::ScrollArea::vertical() + .id_salt("docs-rail") + .auto_shrink(false) + .show(&mut area, |ui| { + ui.spacing_mut().item_spacing.y = gap::LINE; + if view.query.trim().is_empty() { contents(ui, state, id) } else { results(ui, state, view) } + }); asked = asked.or(scrolled.inner); let site = Rect::from_min_max(pos2(whole.left(), whole.bottom() - FOOTER), whole.max); @@ -220,11 +188,7 @@ fn site_of(language: Language) -> &'static str { /// Enter opens the first answer. fn search(ui: &mut Ui, state: &AppState, view: &mut View) -> Option { let tr = |key| i18n::translate(state.language, key, &[]); - let (name, hint, clear) = ( - tr(keys::docs::SEARCH), - tr(keys::docs::SEARCH_HINT), - tr(keys::docs::CLEAR), - ); + let (name, hint, clear) = (tr(keys::docs::SEARCH), tr(keys::docs::SEARCH_HINT), tr(keys::docs::CLEAR)); let searched = SearchField::new(&mut view.query, &name, "docs-search") .hint(&hint) .clear(&clear, "docs-search-clear") @@ -236,8 +200,7 @@ fn search(ui: &mut Ui, state: &AppState, view: &mut View) -> Option { view.hits = help::search_docs(state.language, &view.query); view.searched.clone_from(&view.query); } - let entered = - searched.field.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); + let entered = searched.field.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)); let first = view.hits.first().filter(|_| entered)?; let went = went_to(first); view.query.clear(); @@ -255,32 +218,16 @@ fn contents(ui: &mut Ui, state: &AppState, reading: &str) -> Option { let mut asked = None; for group in &help::docs_index().groups { let name = group.name.of(language); - let words = widgets::text( - ui, - name, - font::META, - 600.0, - FontFamily::Proportional, - p.text_2, - ); + let words = widgets::text(ui, name, font::META, 600.0, FontFamily::Proportional, p.text_2); let size = vec2(ui.available_width(), words.size().y + gap::GROUPS); let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, name)); - let at = pos2( - rect.left() + gap::SNUG, - rect.bottom() - words.size().y - gap::LINE, - ); + let at = pos2(rect.left() + gap::SNUG, rect.bottom() - words.size().y - gap::LINE); ui.painter().galley(at, words, p.text_2); for entry in &group.pages { let on = entry.id == reading; let name = entry.name.of(language); - if row( - ui, - name, - &format!("docs-page-{}", entry.id), - Some(&entry.id), - on, - ) { + if row(ui, name, &format!("docs-page-{}", entry.id), Some(&entry.id), on) { asked = Some(Go::Page(&entry.id, None)); } if on && let Some(page) = help::docs_page(state.language, &entry.id) { @@ -319,17 +266,13 @@ fn row(ui: &mut Ui, name: &str, author_id: &str, page: Option<&str>, on: bool) - ); let rect = response.rect; if on { - ui.painter() - .rect_filled(rect, corner, p.amber_fill.gamma_multiply(0.12)); + ui.painter().rect_filled(rect, corner, p.amber_fill.gamma_multiply(0.12)); } else if response.hovered() { ui.painter().rect_filled(rect, corner, p.bg_2); } let left = rect.left() + gap::CONTROLS; if let Some(id) = page { - let square = Rect::from_center_size( - pos2(left + SQUARE / 2.0, rect.center().y), - Vec2::splat(SQUARE), - ); + let square = Rect::from_center_size(pos2(left + SQUARE / 2.0, rect.center().y), Vec2::splat(SQUARE)); ui.painter() .rect_filled(square, CornerRadius::same(radius::MARK), swatch(p, id)); } @@ -339,19 +282,9 @@ fn row(ui: &mut Ui, name: &str, author_id: &str, page: Option<&str>, on: bool) - (_, _, true) => p.text_1, _ => p.text_2, }; - let size = if page.is_some() { - font::BODY - } else { - font::LABEL - }; + let size = if page.is_some() { font::BODY } else { font::LABEL }; let left = left + SQUARE + gap::INSET; - let words = widgets::one_line( - ui, - name, - (size, 400.0), - ink, - rect.right() - left - gap::TIGHT, - ); + let words = widgets::one_line(ui, name, (size, 400.0), ink, rect.right() - left - gap::TIGHT); let at = pos2(left, rect.center().y - words.size().y / 2.0); ui.painter().galley(at, words, ink); response.clicked() @@ -412,9 +345,7 @@ fn result(ui: &mut Ui, hit: &Hit) -> bool { fn reader(ui: &mut Ui, state: &AppState, id: &'static str, view: &mut View) -> Option { let page = help::docs_page(state.language, id)?; - let mut area = egui::ScrollArea::vertical() - .id_salt("docs-page") - .auto_shrink(false); + let mut area = egui::ScrollArea::vertical().id_salt("docs-page").auto_shrink(false); if view.shown != Some(id) { area = area.vertical_scroll_offset(0.0); view.shown = Some(id); diff --git a/crates/ui/src/titlebar/about_menu/docs/page.rs b/crates/ui/src/titlebar/about_menu/docs/page.rs index a933d8a95..887b6d1bf 100644 --- a/crates/ui/src/titlebar/about_menu/docs/page.rs +++ b/crates/ui/src/titlebar/about_menu/docs/page.rs @@ -2,8 +2,8 @@ use egui::text::LayoutJob; use egui::{ - Align, Color32, CornerRadius, FontFamily, FontId, Layout, Role, Sense, Stroke, StrokeKind, - TextFormat, Ui, Vec2, WidgetInfo, pos2, vec2, + Align, Color32, CornerRadius, FontFamily, FontId, Layout, Role, Sense, Stroke, StrokeKind, TextFormat, + Ui, Vec2, WidgetInfo, pos2, vec2, }; use engine::docs::model::{Block, Inline, Page, Shortcut, Target, Tone}; use i18n::keys; @@ -50,11 +50,7 @@ fn title(ui: &mut Ui, state: &AppState, page: &Page) { let p = palette(ui.ctx()); heading(ui, &page.title, font::DISPLAY, "docs-title"); ui.add_space(gap::CONTROLS); - let style = Style { - size: font::SUBTITLE, - weight: 400.0, - colour: p.text_1, - }; + let style = Style { size: font::SUBTITLE, weight: 400.0, colour: p.text_1 }; let summary = [Inline::Text(page.summary.clone())]; let width = ui.available_width(); let laid = lay(ui, &summary, style, width, &state.settings.bindings); @@ -73,22 +69,13 @@ fn heading(ui: &mut Ui, words: &str, size: f32, author_id: &str) -> egui::Respon response } -fn draw( - ui: &mut Ui, - state: &AppState, - block: &'static Block, - section: &mut Option, -) -> Option { +fn draw(ui: &mut Ui, state: &AppState, block: &'static Block, section: &mut Option) -> Option { let p = palette(ui.ctx()); let bindings = &state.settings.bindings; match block { Block::Paragraph(runs) => go(paragraph(ui, runs, Style::body(p), bindings)), Block::Heading { level, id, text } => { - let size = if *level == 2 { - font::HEADING - } else { - font::SUBTITLE - }; + let size = if *level == 2 { font::HEADING } else { font::SUBTITLE }; let response = heading(ui, text, size, "docs-section"); if section.as_deref() == Some(id) { let seen = response.rect.expand2(vec2(0.0, gap::PANEL)); @@ -99,11 +86,7 @@ fn draw( } Block::List { ordered, items } => list(ui, state, *ordered, items), Block::Note { tone, text } => note(ui, state, *tone, text), - Block::Code { - title, - language, - text, - } => code(ui, state, title, language, text), + Block::Code { title, language, text } => code(ui, state, title, language, text), Block::Shortcuts { title, rows } => { framed(ui, title, |ui| shortcuts(ui, state, rows)); None @@ -142,8 +125,7 @@ fn list(ui: &mut Ui, state: &AppState, ordered: bool, items: &[Vec]) -> let number = format!("{}.", at + 1); let font = FontId::proportional(style.size); let place = pos2(rect.left() + MARK - gap::SNUG, line); - ui.painter() - .text(place, egui::Align2::RIGHT_CENTER, number, font, p.text_2); + ui.painter().text(place, egui::Align2::RIGHT_CENTER, number, font, p.text_2); } else { let centre = pos2(rect.left() + MARK / 2.0, line); ui.painter().circle_filled(centre, 2.5, p.text_2); @@ -172,10 +154,7 @@ fn note(ui: &mut Ui, state: &AppState, tone: Tone, runs: &[Inline]) -> Option>]) -> Option { let p = palette(ui.ctx()); let bindings = &state.settings.bindings; - let titles: Vec<_> = head - .iter() - .map(|title| vec![Inline::Text(title.clone())]) - .collect(); - let named = Style { - size: font::LABEL, - weight: 600.0, - colour: p.text_2, - }; + let titles: Vec<_> = head.iter().map(|title| vec![Inline::Text(title.clone())]).collect(); + let named = Style { size: font::LABEL, weight: 600.0, colour: p.text_2 }; let natural = |cells: &[Vec], style| -> Vec { cells .iter() @@ -289,9 +254,7 @@ fn columns(wanted: &[f32], room: f32) -> Vec { let mut over = widths.iter().sum::() - inside; while over > 0.5 { let widest = widths.iter().copied().fold(0.0, f32::max); - let wide: Vec<_> = (0..widths.len()) - .filter(|at| widths[*at] > widest - 0.5) - .collect(); + let wide: Vec<_> = (0..widths.len()).filter(|at| widths[*at] > widest - 0.5).collect(); let next = widths .iter() .copied() @@ -317,13 +280,7 @@ fn count(columns: usize) -> f32 { columns as f32 } -fn line( - ui: &mut Ui, - state: &AppState, - cells: &[Vec], - style: Style, - widths: &[f32], -) -> Option { +fn line(ui: &mut Ui, state: &AppState, cells: &[Vec], style: Style, widths: &[f32]) -> Option { let laid: Vec<_> = cells .iter() .zip(widths) @@ -347,18 +304,14 @@ fn code(ui: &mut Ui, state: &AppState, title: &str, language: &str, source: &str let mut asked = None; framed(ui, title, |ui| { let top = ui.max_rect().right_top() + vec2(-CELL.x, gap::SNUG); - let bar = - egui::Rect::from_min_max(pos2(ui.max_rect().left(), top.y), top + vec2(0.0, 24.0)); + let bar = egui::Rect::from_min_max(pos2(ui.max_rect().left(), top.y), top + vec2(0.0, 24.0)); let mut end = ui.new_child( egui::UiBuilder::new() .max_rect(bar) .layout(Layout::right_to_left(Align::Center)), ); let label = i18n::translate(state.language, keys::docs::COPY, &[]); - if IconButton::new(Icon::Copy, &label, "docs-copy") - .show(&mut end) - .clicked() - { + if IconButton::new(Icon::Copy, &label, "docs-copy").show(&mut end).clicked() { asked = Some(Go::Copy(source.to_owned())); } if !language.is_empty() { @@ -431,30 +384,18 @@ fn card(ui: &mut Ui, state: &AppState, id: &'static str, width: f32) -> bool { corner, ); let rect = response.rect; - let edge = if response.hovered() { - p.line - } else { - p.line_soft - }; - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(gap::HAIRLINE, edge), - StrokeKind::Inside, - ); - let square = egui::Rect::from_min_size( - rect.min + vec2(gap::GROUPS, gap::GROUPS + 4.0), - Vec2::splat(SQUARE), - ); + let edge = if response.hovered() { p.line } else { p.line_soft }; + ui.painter() + .rect(rect, corner, p.bg_2, Stroke::new(gap::HAIRLINE, edge), StrokeKind::Inside); + let square = + egui::Rect::from_min_size(rect.min + vec2(gap::GROUPS, gap::GROUPS + 4.0), Vec2::splat(SQUARE)); ui.painter() .rect_filled(square, CornerRadius::same(radius::MARK), swatch(p, id)); let left = square.right() + gap::CONTROLS; let inside = rect.right() - left - gap::GROUPS; let name = widgets::one_line(ui, &page.title, (font::READING, 600.0), p.text_0, inside); let under = rect.top() + gap::GROUPS + name.size().y + gap::TIGHT; - ui.painter() - .galley(pos2(left, rect.top() + gap::GROUPS), name, p.text_0); + ui.painter().galley(pos2(left, rect.top() + gap::GROUPS), name, p.text_0); about(ui, &page.summary, (pos2(left, under), inside), p.text_1); response.clicked() } @@ -472,27 +413,17 @@ fn about(ui: &Ui, words: &str, (at, width): (egui::Pos2, f32), ink: Color32) { fn pager(ui: &mut Ui, state: &AppState, page: &Page) -> Option { let entries: Vec<_> = help::docs_index().pages().collect(); let at = entries.iter().position(|entry| entry.id == page.id)?; - let name = |at: usize| { - entries - .get(at) - .map(|entry| entry.name.of(state.language.code())) - }; + let name = |at: usize| entries.get(at).map(|entry| entry.name.of(state.language.code())); let mut asked = None; ui.horizontal(|ui| { if let Some((before, label)) = at.checked_sub(1).and_then(|at| Some((at, name(at)?))) - && Button::new(label, "docs-previous") - .icon(Icon::ArrowLeft) - .show(ui) - .clicked() + && Button::new(label, "docs-previous").icon(Icon::ArrowLeft).show(ui).clicked() { asked = Some(Go::Page(entries[before].id.as_str(), None)); } ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if let Some(label) = name(at + 1) - && Button::new(label, "docs-next") - .icon(Icon::ArrowRight) - .show(ui) - .clicked() + && Button::new(label, "docs-next").icon(Icon::ArrowRight).show(ui).clicked() { asked = Some(Go::Page(entries[at + 1].id.as_str(), None)); } diff --git a/crates/ui/src/titlebar/about_menu/docs/text.rs b/crates/ui/src/titlebar/about_menu/docs/text.rs index 00f098888..fa58700e8 100644 --- a/crates/ui/src/titlebar/about_menu/docs/text.rs +++ b/crates/ui/src/titlebar/about_menu/docs/text.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use egui::text::{CCursor, LayoutJob}; use egui::{ - Align, Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Role, Sense, Stroke, - StrokeKind, TextFormat, Ui, Vec2, WidgetInfo, vec2, + Align, Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Role, Sense, Stroke, StrokeKind, + TextFormat, Ui, Vec2, WidgetInfo, vec2, }; use engine::docs::model::{Inline, Target, text_of}; @@ -31,11 +31,7 @@ pub(super) struct Style { impl Style { pub(super) fn body(p: &Palette) -> Self { - Self { - size: font::READING, - weight: 400.0, - colour: p.text_1, - } + Self { size: font::READING, weight: 400.0, colour: p.text_1 } } } @@ -62,13 +58,7 @@ pub(super) fn lay<'a>( writer.run(run, bindings); } writer.job.wrap.max_width = width; - let Writer { - job, - caps, - arrows, - links, - .. - } = writer; + let Writer { job, caps, arrows, links, .. } = writer; Laid { galley: ui.fonts_mut(|fonts| fonts.layout_job(job)), style, @@ -116,8 +106,7 @@ impl<'a> Laid<'a> { ); } } - ui.painter() - .galley(at, Arc::clone(&self.galley), self.style.colour); + ui.painter().galley(at, Arc::clone(&self.galley), self.style.colour); for (range, icon, ink) in &self.arrows { for rect in self.rects(range, at) { let side = rect.width().min(font::READING); @@ -139,11 +128,7 @@ impl<'a> Laid<'a> { for (row, rect) in rects.iter().enumerate() { let salt = ("docs-link", range.start, row, at.y.to_bits()); // One stop of Tab per link, over the first row it takes. - let sense = if rect == first { - Sense::click() - } else { - Sense::CLICK - }; + let sense = if rect == first { Sense::click() } else { Sense::CLICK }; let link = widgets::region(ui, *rect, salt, sense); if rect == first { link.widget_info(|| WidgetInfo::labeled(Role::Link, true, *text)); @@ -173,11 +158,7 @@ impl<'a> Laid<'a> { if from < to { // A cursor between two rows is read at the end of the first one. let x = |at: usize| self.galley.pos_from_cursor(CCursor::new(at)).left(); - let left = if from == start { - row.rect().left() - } else { - x(from) - }; + let left = if from == start { row.rect().left() } else { x(from) }; let right = if to == end { row.rect().right() } else { x(to) }; let rect = Rect::from_x_y_ranges(left..=right, row.min_y()..=row.max_y()); rects.push(rect.translate(at.to_vec2())); @@ -246,10 +227,7 @@ impl<'a> Writer<'a> { valign: Align::Center, ..self.format(self.style.weight, self.palette.text_0) }; - let between = TextFormat { - font_id: FontId::proportional(font::BADGE), - ..cap.clone() - }; + let between = TextFormat { font_id: FontId::proportional(font::BADGE), ..cap.clone() }; for (at, key) in keys.iter().enumerate() { if at > 0 { self.write("\u{a0}", &between); @@ -299,10 +277,7 @@ pub(super) fn held(keys: &[String], bindings: &Bindings) -> Vec { let shipped = keys.join("+"); shortcuts::every() .find(|action| keys.len() > 1 && action.fallback == shipped) - .map_or_else( - || keys.to_vec(), - |action| bindings.of(action).split('+').map(str::to_owned).collect(), - ) + .map_or_else(|| keys.to_vec(), |action| bindings.of(action).split('+').map(str::to_owned).collect()) } #[cfg(test)] @@ -313,11 +288,7 @@ mod tests { fn a_combination_moved_in_the_preferences_is_the_one_shown() { let keys = |text: &str| -> Vec { text.split(' ').map(str::to_owned).collect() }; let mut bindings = Bindings::default(); - assert_eq!( - held(&keys("Ctrl Alt P"), &bindings), - keys("Ctrl Alt P"), - "nothing moved" - ); + assert_eq!(held(&keys("Ctrl Alt P"), &bindings), keys("Ctrl Alt P"), "nothing moved"); let palette = shortcuts::every() .find(|action| action.id == shortcuts::PALETTE) diff --git a/crates/ui/src/titlebar/about_menu/mod.rs b/crates/ui/src/titlebar/about_menu/mod.rs index 67b292159..5f996c2b8 100644 --- a/crates/ui/src/titlebar/about_menu/mod.rs +++ b/crates/ui/src/titlebar/about_menu/mod.rs @@ -7,9 +7,7 @@ mod sheet; mod whats_new; use crate::theme::tokens::{font, gap}; -use egui::{ - Align, FontFamily, Id, Layout, Popup, PopupCloseBehavior, Rect, Sense, Stroke, Ui, Vec2, -}; +use egui::{Align, FontFamily, Id, Layout, Popup, PopupCloseBehavior, Rect, Sense, Stroke, Ui, Vec2}; use engine::app_info::METADATA; use i18n::{Message, keys}; @@ -71,10 +69,7 @@ pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut .frame(widgets::menu_frame(ui.ctx())) .close_behavior(PopupCloseBehavior::CloseOnClickOutside) .show(|ui| widgets::fitted_menu(ui, anchor.rect.width(), |ui| entries(ui, state, actions))); - let answered = matches!( - state.updates.check_state(), - CheckState::UpToDate | CheckState::Failed - ); + let answered = matches!(state.updates.check_state(), CheckState::UpToDate | CheckState::Failed); if shown.is_none() && answered { actions.push(Asked::Menu(Action::Update(Ask::ForgetCheck))); } @@ -99,24 +94,9 @@ fn entries(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.close(); } }; - entry( - ui, - &tr(keys::about::WHATS_NEW), - "about-whats-new", - Panel::WhatsNew, - ); - entry( - ui, - &tr(keys::about::DOCUMENTATION), - "about-documentation", - Panel::Docs(docs::FIRST), - ); - entry( - ui, - &tr(keys::about::SHORTCUTS), - "about-shortcuts", - Panel::Sheet, - ); + entry(ui, &tr(keys::about::WHATS_NEW), "about-whats-new", Panel::WhatsNew); + entry(ui, &tr(keys::about::DOCUMENTATION), "about-documentation", Panel::Docs(docs::FIRST)); + entry(ui, &tr(keys::about::SHORTCUTS), "about-shortcuts", Panel::Sheet); super::separator(ui); entry(ui, &about, "about-about", Panel::About); widgets::menu_arrows(ui, &ids); @@ -164,9 +144,7 @@ fn check_entry(ui: &mut Ui, state: &AppState, actions: &mut Actions) -> Id { let said = match state.updates.check_state() { CheckState::Idle => None, CheckState::Checking => Some(Message::new(keys::about::CHECKING)), - CheckState::UpToDate => { - Some(Message::new(keys::about::UP_TO_DATE).with("app", METADATA.name)) - } + CheckState::UpToDate => Some(Message::new(keys::about::UP_TO_DATE).with("app", METADATA.name)), CheckState::Failed => Some(Message::new(keys::about::CHECK_FAILED)), }; if let Some(said) = said { @@ -180,12 +158,7 @@ fn check_entry(ui: &mut Ui, state: &AppState, actions: &mut Actions) -> Id { row.id } -pub(super) fn panels( - ctx: &egui::Context, - state: &AppState, - view: &mut View, - actions: &mut Actions, -) { +pub(super) fn panels(ctx: &egui::Context, state: &AppState, view: &mut View, actions: &mut Actions) { let Some(panel) = view.panel else { return; }; @@ -214,14 +187,7 @@ fn framed( let whole = ui.max_rect(); let line = Stroke::new(1.0, p.line_soft); let bottom = whole.bottom() - FOOTER; - let words = widgets::text( - ui, - title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); let at = egui::pos2(whole.left() + 20.0, whole.top() + 16.0); let height = words.size().y; let heading = ui.allocate_rect(Rect::from_min_size(at, words.size()), Sense::hover()); @@ -234,20 +200,12 @@ fn framed( whole.width() - 40.0, ); let top = at.y + height + 4.0 + under.size().y + 12.0; - ui.painter() - .galley(at + Vec2::new(0.0, height + 4.0), under, p.text_2); + ui.painter().galley(at + Vec2::new(0.0, height + 4.0), under, p.text_2); ui.painter().hline(whole.x_range(), top, line); ui.painter().hline(whole.x_range(), bottom, line); - let room = Rect::from_min_max( - egui::pos2(whole.left(), top), - egui::pos2(whole.right(), bottom), - ); - let mut page = ui.new_child( - egui::UiBuilder::new() - .max_rect(room) - .layout(Layout::top_down(Align::Min)), - ); + let room = Rect::from_min_max(egui::pos2(whole.left(), top), egui::pos2(whole.right(), bottom)); + let mut page = ui.new_child(egui::UiBuilder::new().max_rect(room).layout(Layout::top_down(Align::Min))); egui::ScrollArea::vertical() .id_salt("about-panel-body") .auto_shrink(false) diff --git a/crates/ui/src/titlebar/about_menu/sheet.rs b/crates/ui/src/titlebar/about_menu/sheet.rs index eb5f71720..fe32865f0 100644 --- a/crates/ui/src/titlebar/about_menu/sheet.rs +++ b/crates/ui/src/titlebar/about_menu/sheet.rs @@ -18,12 +18,8 @@ pub(super) fn show(ctx: &egui::Context, state: &AppState, _actions: &mut Actions let language = state.language; let tr = |key: Key| i18n::translate(language, key, &[]); let cross = tr(keys::shortcuts::CLOSE); - let shown = widgets::framed_dialog( - ctx, - &state.dialogs, - (super::id(), (&cross, "sheet-close")), - SIZE, - |ui| { + let shown = + widgets::framed_dialog(ctx, &state.dialogs, (super::id(), (&cross, "sheet-close")), SIZE, |ui| { let (title, subtitle) = (tr(keys::shortcuts::TITLE), tr(keys::shortcuts::SUBTITLE)); framed( ui, @@ -37,8 +33,7 @@ pub(super) fn show(ctx: &egui::Context, state: &AppState, _actions: &mut Actions ui.label(hint); }, ); - }, - ); + }); shown.is_some_and(|shown| shown.should_close()) } @@ -47,18 +42,9 @@ fn body(ui: &mut Ui, state: &AppState) { let p = palette(ui.ctx()); for group in shortcut_sheet::sheet() { let title = i18n::translate(language, group.title(), &[]).to_uppercase(); - let words = widgets::text( - ui, - &title, - font::META, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, heading) = ui.allocate_exact_size( - Vec2::new(ui.available_width(), words.size().y + 8.0), - Sense::hover(), - ); + let words = widgets::text(ui, &title, font::META, 600.0, FontFamily::Proportional, p.text_2); + let (rect, heading) = + ui.allocate_exact_size(Vec2::new(ui.available_width(), words.size().y + 8.0), Sense::hover()); ui.painter().galley(rect.min, words, p.text_2); widgets::address(ui, &heading, "shortcut-group"); for row in &group.rows { @@ -75,16 +61,9 @@ fn line(ui: &mut Ui, state: &AppState, row: &SheetRow) { ui.horizontal(|ui| { ui.set_min_height(24.0); let room = (ui.available_width() - 220.0).max(120.0); - ui.allocate_ui_with_layout( - Vec2::new(room, 22.0), - Layout::left_to_right(Align::Center), - |ui| { - ui.add( - egui::Label::new(RichText::new(label).size(font::BODY).color(p.text_1)) - .truncate(), - ); - }, - ); + ui.allocate_ui_with_layout(Vec2::new(room, 22.0), Layout::left_to_right(Align::Center), |ui| { + ui.add(egui::Label::new(RichText::new(label).size(font::BODY).color(p.text_1)).truncate()); + }); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.spacing_mut().item_spacing.x = gap::TIGHT; for (at, cap) in caps.iter().rev().enumerate() { diff --git a/crates/ui/src/titlebar/about_menu/whats_new.rs b/crates/ui/src/titlebar/about_menu/whats_new.rs index 67dce946c..7e3fee1ae 100644 --- a/crates/ui/src/titlebar/about_menu/whats_new.rs +++ b/crates/ui/src/titlebar/about_menu/whats_new.rs @@ -22,21 +22,11 @@ pub(super) fn show(ctx: &egui::Context, state: &AppState, actions: &mut Actions) let language = state.language; let tr = |key: Key| i18n::translate(language, key, &[]); let cross = tr(keys::whats_new::CLOSE); - let shown = widgets::framed_dialog( - ctx, - &state.dialogs, - (super::id(), (&cross, "news-close")), - SIZE, - |ui| { + let shown = + widgets::framed_dialog(ctx, &state.dialogs, (super::id(), (&cross, "news-close")), SIZE, |ui| { let (title, subtitle) = (tr(keys::whats_new::TITLE), tr(keys::whats_new::SUBTITLE)); - framed( - ui, - (&title, &subtitle), - |ui| body(ui, state), - |ui| footer(ui, actions), - ); - }, - ); + framed(ui, (&title, &subtitle), |ui| body(ui, state), |ui| footer(ui, actions)); + }); shown.is_some_and(|shown| shown.should_close()) } @@ -73,12 +63,7 @@ fn release(ui: &mut Ui, release: &ChangelogRelease, language: Language) { ); widgets::address(ui, &version, "news-version"); if let Some(date) = &release.date { - ui.label( - RichText::new(date) - .size(font::CONTROL) - .monospace() - .color(p.text_2), - ); + ui.label(RichText::new(date).size(font::CONTROL).monospace().color(p.text_2)); } if release.version == VERSION { let installed = i18n::translate(language, keys::whats_new::INSTALLED, &[]); @@ -92,11 +77,7 @@ fn release(ui: &mut Ui, release: &ChangelogRelease, language: Language) { fn footer(ui: &mut Ui, actions: &mut Actions) { let url = format!("{}/releases", METADATA.repository); let label = url.trim_start_matches("https://"); - if Button::new(label, "news-releases") - .icon(Icon::Link) - .show(ui) - .clicked() - { + if Button::new(label, "news-releases").icon(Icon::Link).show(ui).clicked() { actions.push(Asked::Menu(Action::OpenLink(url.clone()))); } } diff --git a/crates/ui/src/titlebar/area_switch.rs b/crates/ui/src/titlebar/area_switch.rs index 095ed0548..dca6e07ac 100644 --- a/crates/ui/src/titlebar/area_switch.rs +++ b/crates/ui/src/titlebar/area_switch.rs @@ -2,9 +2,7 @@ //! while the rail is put away, since nothing else then leads to the other areas. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - CornerRadius, FontFamily, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2, -}; +use egui::{CornerRadius, FontFamily, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, pos2}; use i18n::{Key, Language, Message, keys}; use crate::action::{Action as Asked, Actions, AppAction}; @@ -113,20 +111,12 @@ pub(crate) fn rail(ui: &mut Ui, current: Area, language: Language, actions: &mut let on = area == current; let colour = ink(ui, &response, on); let rect = response.rect; - let glyph = Rect::from_center_size( - pos2(rect.center().x, rect.top() + 14.0), - Vec2::splat(16.0), - ); + let glyph = + Rect::from_center_size(pos2(rect.center().x, rect.top() + 14.0), Vec2::splat(16.0)); icons::paint(ui, glyph, icon, colour); let weight = if on { 600.0 } else { 400.0 }; - let words = widgets::text( - ui, - &name, - font::META, - weight, - FontFamily::Proportional, - colour, - ); + let words = + widgets::text(ui, &name, font::META, weight, FontFamily::Proportional, colour); let at = pos2(rect.center().x - words.size().x / 2.0, rect.top() + 26.0); ui.painter().galley(at, words, colour); } diff --git a/crates/ui/src/titlebar/file_menu.rs b/crates/ui/src/titlebar/file_menu.rs index fb51809d2..b12b1c75e 100644 --- a/crates/ui/src/titlebar/file_menu.rs +++ b/crates/ui/src/titlebar/file_menu.rs @@ -18,12 +18,7 @@ pub(super) struct View { } /// The menu's control, for what it opens to give the focus back to. -pub(super) fn show( - ui: &mut Ui, - state: &AppState, - view: &mut View, - actions: &mut Actions, -) -> egui::Id { +pub(super) fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) -> egui::Id { let label = i18n::translate(state.language, keys::file::MENU_LABEL, &[]); let anchor = super::menu_trigger(ui, &label, "file-menu"); let shown = Popup::menu(&anchor) @@ -53,24 +48,9 @@ fn entries(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions let rows = [ (keys::file::IMPORT, "import", None, Action::Import), (keys::file::EXPORT_ALL, "exportAll", None, Action::ExportAll), - ( - keys::file::EXPORT_SPACE, - "exportSpace", - space, - Action::ExportSpace, - ), - ( - keys::file::EXPORT_SELECTION, - "exportSelection", - checked, - Action::ExportSelection, - ), - ( - keys::file::COPY_MARKDOWN, - "copyMarkdown", - checked, - Action::CopyMarkdown, - ), + (keys::file::EXPORT_SPACE, "exportSpace", space, Action::ExportSpace), + (keys::file::EXPORT_SELECTION, "exportSelection", checked, Action::ExportSelection), + (keys::file::COPY_MARKDOWN, "copyMarkdown", checked, Action::CopyMarkdown), ]; let mut ids = Vec::with_capacity(rows.len() + 3); for (key, entry, waiting, action) in rows { @@ -88,23 +68,13 @@ fn entries(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions } } super::separator(ui); - let row = super::menu_option( - ui, - &tr(keys::libraries::MENU_ENTRY), - "file-libraries", - Tone::Plain, - ); + let row = super::menu_option(ui, &tr(keys::libraries::MENU_ENTRY), "file-libraries", Tone::Plain); ids.push(row.id); if row.clicked() { actions.push(Asked::Menu(Action::OpenLibraries)); ui.close(); } - let row = super::menu_option( - ui, - &tr(keys::file::PREFERENCES), - "file-preferences", - Tone::Plain, - ); + let row = super::menu_option(ui, &tr(keys::file::PREFERENCES), "file-preferences", Tone::Plain); ids.push(row.id); if row.clicked() { actions.push(Asked::Menu(Action::OpenPreferences)); @@ -113,20 +83,12 @@ fn entries(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions let quit = if view.confirming_quit { tr(keys::file::QUIT_CONFIRM) } else { - Message::new(keys::file::QUIT) - .with("app", METADATA.name) - .text(state.language) + Message::new(keys::file::QUIT).with("app", METADATA.name).text(state.language) }; // Quitting loses nothing: red only while it asks, not at rest. - let tone = if view.confirming_quit { - Tone::Asking - } else { - Tone::Plain - }; + let tone = if view.confirming_quit { Tone::Asking } else { Tone::Plain }; let row = super::menu_option(ui, &quit, "file-quit", tone); - let elsewhere = ui - .memory(egui::Memory::focused) - .is_some_and(|focused| ids.contains(&focused)); + let elsewhere = ui.memory(egui::Memory::focused).is_some_and(|focused| ids.contains(&focused)); ids.push(row.id); if row.clicked() { if view.confirming_quit { diff --git a/crates/ui/src/titlebar/libraries.rs b/crates/ui/src/titlebar/libraries.rs index d94ef8df2..7fe841b6e 100644 --- a/crates/ui/src/titlebar/libraries.rs +++ b/crates/ui/src/titlebar/libraries.rs @@ -40,15 +40,9 @@ pub(crate) fn id() -> Id { pub(super) fn show(ctx: &egui::Context, state: &AppState, view: &mut View, actions: &mut Actions) { let cross = i18n::translate(state.language, keys::libraries::CLOSE, &[]); - let shown = widgets::dialog( - ctx, - &state.dialogs, - (id(), (&cross, "libraries-close")), - WIDTH, - |ui| { - body(ui, state, view, actions); - }, - ); + let shown = widgets::dialog(ctx, &state.dialogs, (id(), (&cross, "libraries-close")), WIDTH, |ui| { + body(ui, state, view, actions); + }); // Escape takes back a name being typed before it closes anything. if shown.is_some_and(|shown| shown.should_close()) && view.renaming.take().is_none() { actions.push(Asked::Menu(Action::Libraries(Ask::Close))); @@ -72,12 +66,7 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { ui.painter().galley(rect.min, title, p.text_0); widgets::address(ui, &heading, "libraries-dialog"); ui.add( - egui::Label::new( - RichText::new(tr(keys::libraries::LEAD)) - .size(font::CONTROL) - .color(p.text_2), - ) - .wrap(), + egui::Label::new(RichText::new(tr(keys::libraries::LEAD)).size(font::CONTROL).color(p.text_2)).wrap(), ); rule(ui); let several = state.libraries.libraries().len() > 1; @@ -123,11 +112,7 @@ fn creating(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Action }); let name = view.new_name.trim().to_owned(); let ready = !name.is_empty() && !state.libraries.is_working(); - if Button::new(&create, "library-create") - .enabled(ready) - .show(ui) - .clicked() - { + if Button::new(&create, "library-create").enabled(ready).show(ui).clicked() { actions.push(Asked::Menu(Action::Libraries(Ask::Create(name)))); } } @@ -196,13 +181,7 @@ fn name(ui: &mut Ui, entry: &LibraryEntry, open: bool, language: Language) { } } -fn renaming( - ui: &mut Ui, - entry: &LibraryEntry, - language: Language, - view: &mut View, - actions: &mut Actions, -) { +fn renaming(ui: &mut Ui, entry: &LibraryEntry, language: Language, view: &mut View, actions: &mut Actions) { let label = i18n::translate(language, keys::libraries::RENAME, &[]); ui.scope(|ui| { ui.set_width(220.0); @@ -244,14 +223,11 @@ fn confirm(ui: &mut Ui, state: &AppState, entry: &LibraryEntry, actions: &mut Ac { actions.push(Asked::Menu(Action::Libraries(Ask::KeepIt))); } - if Button::new( - &tr(keys::libraries::CONFIRM_DELETE_ACTION), - "library-confirm-delete", - ) - .kind(Kind::Destructive) - .enabled(!state.libraries.is_working()) - .show(ui) - .clicked() + if Button::new(&tr(keys::libraries::CONFIRM_DELETE_ACTION), "library-confirm-delete") + .kind(Kind::Destructive) + .enabled(!state.libraries.is_working()) + .show(ui) + .clicked() { actions.push(Asked::Menu(Action::Libraries(Ask::ConfirmDelete))); } diff --git a/crates/ui/src/titlebar/mod.rs b/crates/ui/src/titlebar/mod.rs index 5e0b3d20b..2398b044c 100644 --- a/crates/ui/src/titlebar/mod.rs +++ b/crates/ui/src/titlebar/mod.rs @@ -123,11 +123,8 @@ pub(crate) fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut let p = palette(ui.ctx()); let bar = ui.max_rect(); ui.painter().rect_filled(bar, CornerRadius::ZERO, p.bg_0); - ui.painter().hline( - bar.x_range(), - bar.bottom() - 0.5, - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .hline(bar.x_range(), bar.bottom() - 0.5, Stroke::new(1.0, p.line_soft)); let empty = window::empty_space(ui, bar); if window::dimmed(ui.ctx()) { ui.multiply_opacity(0.5); @@ -161,37 +158,19 @@ pub(crate) fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut window::follow_the_empty_space(ui.ctx(), &empty, actions); // Centred on the window, not on what the two groups leave between them. - let title = widgets::text( - ui, - METADATA.name, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let title = widgets::text(ui, METADATA.name, font::LABEL, 400.0, FontFamily::Proportional, p.text_2); let at = bar.center() - title.size() / 2.0; ui.painter().galley(at, title, p.text_2); } /// What the menus open, over everything else. -pub(crate) fn dialogs( - ctx: &egui::Context, - state: &AppState, - view: &mut View, - actions: &mut Actions, -) { +pub(crate) fn dialogs(ctx: &egui::Context, state: &AppState, view: &mut View, actions: &mut Actions) { crate::banners::update_prompt::show(ctx, state, &mut view.update, actions); about_menu::panels(ctx, state, &mut view.about, actions); libraries::show(ctx, state, &mut view.libraries, actions); preferences::show(ctx, state, &mut view.preferences, actions); if let Some(request) = state.transfer.prompt() { - let asked = prompt::show( - ctx, - &state.dialogs, - &request, - &mut view.prompt, - state.language, - ); + let asked = prompt::show(ctx, &state.dialogs, &request, &mut view.prompt, state.language); if let Some(answer) = asked { // Whatever the answer: nothing typed outlives the question. view.prompt = PromptView::default(); @@ -204,14 +183,7 @@ pub(crate) fn dialogs( /// A menu's control: its name and a chevron, `bg-2` under the pointer or while it is open. fn menu_trigger(ui: &mut Ui, label: &str, author_id: &str) -> egui::Response { let p = palette(ui.ctx()); - let probe = widgets::text( - ui, - label, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let probe = widgets::text(ui, label, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); let corner = CornerRadius::same(radius::CONTROL); let size = Vec2::new(probe.size().x + 29.0, 24.0); let response = widgets::interact( @@ -228,18 +200,8 @@ fn menu_trigger(ui: &mut Ui, label: &str, author_id: &str) -> egui::Response { ui.painter().rect_filled(response.rect, corner, p.bg_2); } let ink = if lit { p.text_0 } else { p.text_2 }; - let words = widgets::text( - ui, - label, - font::CONTROL, - 400.0, - FontFamily::Proportional, - ink, - ); - let at = egui::pos2( - response.rect.left() + 8.0, - response.rect.center().y - words.size().y / 2.0, - ); + let words = widgets::text(ui, label, font::CONTROL, 400.0, FontFamily::Proportional, ink); + let at = egui::pos2(response.rect.left() + 8.0, response.rect.center().y - words.size().y / 2.0); ui.painter().galley(at, words, ink); let glyph = Rect::from_center_size( egui::pos2(response.rect.right() - 10.0, response.rect.center().y), @@ -275,8 +237,7 @@ fn menu_option(ui: &mut Ui, label: &str, author_id: &str, tone: Tone) -> egui::R ui.painter().rect_filled(response.rect, corner, p.bg_3); } if tone == Tone::Asking { - ui.painter() - .rect_filled(response.rect, corner, p.red.gamma_multiply(0.12)); + ui.painter().rect_filled(response.rect, corner, p.red.gamma_multiply(0.12)); } let ink = match tone { Tone::Asking => p.red, @@ -286,10 +247,7 @@ fn menu_option(ui: &mut Ui, label: &str, author_id: &str, tone: Tone) -> egui::R }; let words = widgets::text(ui, label, font::BODY, 400.0, FontFamily::Proportional, ink); widgets::menu_needs(ui, 20.0 + words.size().x); - let at = egui::pos2( - response.rect.left() + 10.0, - response.rect.center().y - words.size().y / 2.0, - ); + let at = egui::pos2(response.rect.left() + 10.0, response.rect.center().y - words.size().y / 2.0); ui.painter().galley(at, words, ink); response } @@ -298,15 +256,13 @@ fn menu_option(ui: &mut Ui, label: &str, author_id: &str, tone: Tone) -> egui::R fn rule(ui: &mut Ui) { let line = palette(ui.ctx()).line_soft; let (rect, _) = ui.allocate_exact_size(Vec2::new(gap::TIGHT, 18.0), Sense::hover()); - ui.painter() - .vline(rect.center().x, rect.y_range(), Stroke::new(1.0, line)); + ui.painter().vline(rect.center().x, rect.y_range(), Stroke::new(1.0, line)); } fn separator(ui: &mut Ui) { let line = palette(ui.ctx()).line_soft; let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 7.0), Sense::hover()); - ui.painter() - .hline(rect.x_range(), rect.center().y, Stroke::new(1.0, line)); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, line)); } /// One gesture, two themes: the icon and the label both name what it switches **to**. @@ -338,11 +294,7 @@ fn theme_toggle(ui: &mut Ui, language: Language, actions: &mut Actions) { Stroke::new(1.0, p.line_soft), StrokeKind::Inside, ); - let ink = if response.hovered() { - p.text_1 - } else { - p.text_2 - }; + let ink = if response.hovered() { p.text_1 } else { p.text_2 }; let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(13.0)); icons::paint(ui, glyph, icon, ink); if response.clicked() { diff --git a/crates/ui/src/titlebar/preferences/general.rs b/crates/ui/src/titlebar/preferences/general.rs index d5ff9d0c5..7127313d2 100644 --- a/crates/ui/src/titlebar/preferences/general.rs +++ b/crates/ui/src/titlebar/preferences/general.rs @@ -65,10 +65,8 @@ fn appearance(ui: &mut Ui, language: Language, settings: &mut Settings) { (LocaleChoice::Fr, tr(keys::locale::FR)), (LocaleChoice::En, tr(keys::locale::EN)), ]; - let locales: Vec<(LocaleChoice, &str)> = locales - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let locales: Vec<(LocaleChoice, &str)> = + locales.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); let label = tr(keys::settings::appearance::LANGUAGE); row(ui, &label, |ui| { ChoiceMenu::new(&label, "setting-locale", &locales).show(ui, &mut settings.locale); @@ -78,24 +76,17 @@ fn appearance(ui: &mut Ui, language: Language, settings: &mut Settings) { (Appearance::Dark, tr(keys::settings::theme::DARK)), (Appearance::Light, tr(keys::settings::theme::LIGHT)), ]; - let themes: Vec<(Appearance, &str)> = themes - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let themes: Vec<(Appearance, &str)> = + themes.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); row(ui, &tr(keys::settings::appearance::THEME), |ui| { Segmented::new(&themes, "setting-theme").show(ui, &mut settings.theme); }); let densities = [ - ( - Density::Comfortable, - tr(keys::settings::density::COMFORTABLE), - ), + (Density::Comfortable, tr(keys::settings::density::COMFORTABLE)), (Density::Compact, tr(keys::settings::density::COMPACT)), ]; - let densities: Vec<(Density, &str)> = densities - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let densities: Vec<(Density, &str)> = + densities.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); row(ui, &tr(keys::settings::appearance::DENSITY), |ui| { Segmented::new(&densities, "setting-density").show(ui, &mut settings.density); }); @@ -105,21 +96,12 @@ fn appearance(ui: &mut Ui, language: Language, settings: &mut Settings) { fn cards(ui: &mut Ui, language: Language, lines: &mut PreviewLines) { use keys::settings::cards; group(ui, language, cards::TITLE); - let counts: Vec<(PreviewLines, &str)> = PreviewLines::ALL - .iter() - .map(|lines| (*lines, lines.as_str())) - .collect(); - row( - ui, - &i18n::translate(language, cards::PREVIEW_LINES, &[]), - |ui| { - Segmented::new(&counts, "setting-preview-lines").show(ui, lines); - }, - ); - note( - ui, - &i18n::translate(language, cards::PREVIEW_LINES_HINT, &[]), - ); + let counts: Vec<(PreviewLines, &str)> = + PreviewLines::ALL.iter().map(|lines| (*lines, lines.as_str())).collect(); + row(ui, &i18n::translate(language, cards::PREVIEW_LINES, &[]), |ui| { + Segmented::new(&counts, "setting-preview-lines").show(ui, lines); + }); + note(ui, &i18n::translate(language, cards::PREVIEW_LINES_HINT, &[])); } fn editor(ui: &mut Ui, language: Language, settings: &mut Settings) { @@ -128,46 +110,26 @@ fn editor(ui: &mut Ui, language: Language, settings: &mut Settings) { let kinds = [ (NoteKind::Note, tr(keys::settings::note_kind::NOTE)), (NoteKind::Snippet, tr(keys::settings::note_kind::SNIPPET)), - ( - NoteKind::Checklist, - tr(keys::settings::note_kind::CHECKLIST), - ), + (NoteKind::Checklist, tr(keys::settings::note_kind::CHECKLIST)), (NoteKind::Calc, tr(keys::settings::note_kind::CALC)), ]; - let kinds: Vec<(NoteKind, &str)> = kinds - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let kinds: Vec<(NoteKind, &str)> = kinds.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); row(ui, &tr(keys::settings::editor::DEFAULT_KIND), |ui| { Segmented::new(&kinds, "setting-note-kind").show(ui, &mut settings.default_note_kind); }); let indents = [ (IndentChoice::Language, tr(keys::settings::indent::LANGUAGE)), - ( - IndentChoice::TwoSpaces, - tr(keys::settings::indent::TWO_SPACES), - ), - ( - IndentChoice::FourSpaces, - tr(keys::settings::indent::FOUR_SPACES), - ), + (IndentChoice::TwoSpaces, tr(keys::settings::indent::TWO_SPACES)), + (IndentChoice::FourSpaces, tr(keys::settings::indent::FOUR_SPACES)), (IndentChoice::Tab, tr(keys::settings::indent::TAB)), ]; - let indents: Vec<(IndentChoice, &str)> = indents - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let indents: Vec<(IndentChoice, &str)> = + indents.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); let label = tr(keys::settings::editor::INDENT); row(ui, &label, |ui| { ChoiceMenu::new(&label, "setting-indent", &indents).show(ui, &mut settings.code_indent); }); - switch_row( - ui, - language, - keys::settings::editor::WRAP, - "setting-code-wrap", - &mut settings.code_wrap, - ); + switch_row(ui, language, keys::settings::editor::WRAP, "setting-code-wrap", &mut settings.code_wrap); } fn calculation(ui: &mut Ui, language: Language, settings: &mut Settings) { @@ -182,16 +144,12 @@ fn calculation(ui: &mut Ui, language: Language, settings: &mut Settings) { })); let label = tr(keys::settings::calc::DECIMALS); row(ui, &label, |ui| { - ChoiceMenu::new(&label, "setting-calc-decimals", &decimals) - .show(ui, &mut settings.calc_decimals); + ChoiceMenu::new(&label, "setting-calc-decimals", &decimals).show(ui, &mut settings.calc_decimals); }); let formats = number_formats(language); - let names: Vec<(usize, &str)> = formats - .iter() - .enumerate() - .map(|(at, (_, name))| (at, name.as_str())) - .collect(); + let names: Vec<(usize, &str)> = + formats.iter().enumerate().map(|(at, (_, name))| (at, name.as_str())).collect(); let mut chosen = formats .iter() .position(|(id, _)| *id == settings.calc_number_format) @@ -200,19 +158,14 @@ fn calculation(ui: &mut Ui, language: Language, settings: &mut Settings) { row(ui, &label, |ui| { ChoiceMenu::new(&label, "setting-calc-number-format", &names).show(ui, &mut chosen); }); - formats[chosen] - .0 - .clone_into(&mut settings.calc_number_format); + formats[chosen].0.clone_into(&mut settings.calc_number_format); let dates = [ (CalcDate::Numeric, tr(keys::settings::calc::dates::NUMERIC)), (CalcDate::Short, tr(keys::settings::calc::dates::SHORT)), (CalcDate::Long, tr(keys::settings::calc::dates::LONG)), ]; - let dates: Vec<(CalcDate, &str)> = dates - .iter() - .map(|(choice, name)| (*choice, name.as_str())) - .collect(); + let dates: Vec<(CalcDate, &str)> = dates.iter().map(|(choice, name)| (*choice, name.as_str())).collect(); row(ui, &tr(keys::settings::calc::DATE_FORMAT), |ui| { Segmented::new(&dates, "setting-calc-date-format").show(ui, &mut settings.calc_date_format); }); @@ -224,10 +177,8 @@ fn number_formats(language: Language) -> Vec<(&'static str, String)> { let name = i18n::translate(language, keys::settings::calc::LANGUAGE, &[]); let mut formats = vec![(CALC_LANGUAGE, format!("{name} · {own}"))]; formats.extend(NUMBER_FORMATS.iter().map(|format| { - let name = i18n::Key::find(&format!("settings.calc.locales.{}", format.id)).map_or_else( - || format.id.to_owned(), - |key| i18n::translate(language, key, &[]), - ); + let name = i18n::Key::find(&format!("settings.calc.locales.{}", format.id)) + .map_or_else(|| format.id.to_owned(), |key| i18n::translate(language, key, &[])); let sample = crate::notes::calc::sample(SAMPLE, format.id, language); (format.id, format!("{name} · {sample}")) })); @@ -251,22 +202,9 @@ fn behaviour(ui: &mut Ui, language: Language, tray_shown: bool, settings: &mut S "setting-minimize-to-tray", &mut settings.minimize_to_tray, ); - switch_row( - ui, - language, - behavior::CLOSE_TO_TRAY, - "setting-close-to-tray", - &mut settings.close_to_tray, - ); - let said = if tray_shown { - behavior::TRAY_NOTE - } else { - behavior::NO_TRAY_NOTE - }; - note( - ui, - &Message::new(said).with("app", METADATA.name).text(language), - ); + switch_row(ui, language, behavior::CLOSE_TO_TRAY, "setting-close-to-tray", &mut settings.close_to_tray); + let said = if tray_shown { behavior::TRAY_NOTE } else { behavior::NO_TRAY_NOTE }; + note(ui, &Message::new(said).with("app", METADATA.name).text(language)); } fn notifications(ui: &mut Ui, language: Language, settings: &mut Settings) { @@ -299,16 +237,9 @@ fn notifications(ui: &mut Ui, language: Language, settings: &mut Settings) { .text(language); let undo = i18n::translate(language, notifications::UPDATE_SKIPPED_FORGET, &[]); ui.horizontal(|ui| { - let words = ui.label( - RichText::new(said) - .size(font::CONTROL) - .color(palette(ui.ctx()).text_2), - ); + let words = ui.label(RichText::new(said).size(font::CONTROL).color(palette(ui.ctx()).text_2)); widgets::address(ui, &words, "setting-skipped-update"); - if widgets::Button::new(&undo, "setting-forget-skipped") - .show(ui) - .clicked() - { + if widgets::Button::new(&undo, "setting-forget-skipped").show(ui).clicked() { settings.skipped_update.clear(); } }); @@ -318,18 +249,9 @@ pub(super) fn group(ui: &mut Ui, language: Language, title: Key) { let p = palette(ui.ctx()); ui.add_space(gap::INSET); let title = i18n::translate(language, title, &[]).to_uppercase(); - let words = widgets::text( - ui, - &title, - font::META, - 600.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, _) = ui.allocate_exact_size( - Vec2::new(ui.available_width(), words.size().y + 8.0), - Sense::hover(), - ); + let words = widgets::text(ui, &title, font::META, 600.0, FontFamily::Proportional, p.text_2); + let (rect, _) = + ui.allocate_exact_size(Vec2::new(ui.available_width(), words.size().y + 8.0), Sense::hover()); ui.painter().galley(rect.min, words, p.text_2); } @@ -346,27 +268,15 @@ pub(super) fn row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui)) { // layout's centre. let room = ui.max_rect().shrink2(Vec2::new(0.0, (ROW - CONTROL) / 2.0)); let reading = Layout::right_to_left(Align::Min); - ui.scope_builder( - egui::UiBuilder::new().max_rect(room).layout(reading), - control, - ); + ui.scope_builder(egui::UiBuilder::new().max_rect(room).layout(reading), control); }, ); let rect = shown.response.rect; - ui.painter().hline( - rect.x_range(), - rect.bottom() - 0.5, - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.line_soft)); } -pub(super) fn switch_row( - ui: &mut Ui, - language: Language, - label: Key, - author_id: &str, - on: &mut bool, -) { +pub(super) fn switch_row(ui: &mut Ui, language: Language, label: Key, author_id: &str, on: &mut bool) { let label = i18n::translate(language, label, &[]); row(ui, &label, |ui| { widgets::switch(ui, &label, author_id, on, true); @@ -375,12 +285,5 @@ pub(super) fn switch_row( pub(super) fn note(ui: &mut Ui, said: &str) { ui.add_space(gap::SNUG); - ui.add( - egui::Label::new( - RichText::new(said) - .size(font::CONTROL) - .color(palette(ui.ctx()).text_2), - ) - .wrap(), - ); + ui.add(egui::Label::new(RichText::new(said).size(font::CONTROL).color(palette(ui.ctx()).text_2)).wrap()); } diff --git a/crates/ui/src/titlebar/preferences/mod.rs b/crates/ui/src/titlebar/preferences/mod.rs index abc3ea2e5..c05e830b2 100644 --- a/crates/ui/src/titlebar/preferences/mod.rs +++ b/crates/ui/src/titlebar/preferences/mod.rs @@ -65,18 +65,10 @@ impl Page { /// what protects the library and its copies, then the corpus's own variables. const ALL: [(Self, Key, &'static str); 5] = [ (Self::General, keys::settings::pages::GENERAL, "general"), - ( - Self::Shortcuts, - keys::settings::pages::SHORTCUTS, - "shortcuts", - ), + (Self::Shortcuts, keys::settings::pages::SHORTCUTS, "shortcuts"), (Self::Security, keys::settings::pages::SECURITY, "security"), (Self::Backups, keys::settings::pages::BACKUPS, "backups"), - ( - Self::Variables, - keys::settings::pages::VARIABLES, - "variables", - ), + (Self::Variables, keys::settings::pages::VARIABLES, "variables"), ]; } @@ -102,10 +94,7 @@ impl View { } pub(super) fn open(&mut self, settings: &Settings) { - *self = Self { - draft: Some(SettingsDraft::open(settings.clone())), - ..Self::default() - }; + *self = Self { draft: Some(SettingsDraft::open(settings.clone())), ..Self::default() }; } pub(super) fn previewed(&self) -> Option { @@ -122,10 +111,7 @@ impl View { } pub(super) fn changed_variables(&self, stored: Option<&[Variable]>) -> Option> { - self.variables - .as_ref() - .filter(|rows| Some(rows.as_slice()) != stored) - .cloned() + self.variables.as_ref().filter(|rows| Some(rows.as_slice()) != stored).cloned() } pub(super) fn take_phrases(&mut self) -> (Zeroizing, Zeroizing) { @@ -147,15 +133,9 @@ pub(crate) fn id() -> Id { pub(super) fn show(ctx: &egui::Context, state: &AppState, view: &mut View, actions: &mut Actions) { view.shortcuts.listens_for_a_global_key = false; let cross = i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]); - let shown = widgets::framed_dialog( - ctx, - &state.dialogs, - (id(), (&cross, "settings-cross")), - SIZE, - |ui| { - body(ui, state, view, actions); - }, - ); + let shown = widgets::framed_dialog(ctx, &state.dialogs, (id(), (&cross, "settings-cross")), SIZE, |ui| { + body(ui, state, view, actions); + }); security::dialog(ctx, state, view, actions); if !shown.is_some_and(|shown| shown.should_close()) { return; @@ -172,18 +152,8 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { let whole = ui.max_rect(); let language = state.language; let title = i18n::translate(language, keys::settings::TITLE, &[]); - let words = widgets::text( - ui, - &title, - font::TITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); - let at = egui::pos2( - whole.left() + 20.0, - whole.top() + (HEADER - words.size().y) / 2.0, - ); + let words = widgets::text(ui, &title, font::TITLE, 600.0, FontFamily::Proportional, p.text_0); + let at = egui::pos2(whole.left() + 20.0, whole.top() + (HEADER - words.size().y) / 2.0); let heading = ui.allocate_rect(Rect::from_min_size(at, words.size()), Sense::hover()); ui.painter().galley(at, words, p.text_0); heading.widget_info(|| egui::WidgetInfo::labeled(Role::Heading, true, &title)); @@ -194,10 +164,7 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { ui.painter().hline(whole.x_range(), top, line); ui.painter().hline(whole.x_range(), bottom, line); - let rail = Rect::from_min_max( - egui::pos2(whole.left(), top), - egui::pos2(whole.left() + RAIL, bottom), - ); + let rail = Rect::from_min_max(egui::pos2(whole.left(), top), egui::pos2(whole.left() + RAIL, bottom)); ui.painter().rect_filled(rail, CornerRadius::ZERO, p.bg_0); ui.painter().vline(rail.right(), rail.y_range(), line); let mut pages = ui.new_child( @@ -207,37 +174,21 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { ); pages_rail(&mut pages, state, view); - let content = Rect::from_min_max( - egui::pos2(rail.right(), top), - egui::pos2(whole.right(), bottom), - ); - let mut page = ui.new_child( - egui::UiBuilder::new() - .max_rect(content) - .layout(Layout::top_down(Align::Min)), - ); + let content = Rect::from_min_max(egui::pos2(rail.right(), top), egui::pos2(whole.right(), bottom)); + let mut page = + ui.new_child(egui::UiBuilder::new().max_rect(content).layout(Layout::top_down(Align::Min))); let area = egui::ScrollArea::vertical() .id_salt("settings-content") .auto_shrink(false) .show(&mut page, |ui| { egui::Frame::new() - .inner_margin(egui::Margin { - left: 20, - right: 20, - top: 16, - bottom: 20, - }) + .inner_margin(egui::Margin { left: 20, right: 20, top: 16, bottom: 20 }) .show(ui, |ui| { ui.set_width(ui.available_width()); current_page(ui, state, view, actions); }); }); - let region = widgets::region( - ui, - area.inner_rect, - "settings-content-region", - Sense::hover(), - ); + let region = widgets::region(ui, area.inner_rect, "settings-content-region", Sense::hover()); // A place on screen for the scenarios to scroll over: a node with no role has none. region.widget_info(|| egui::WidgetInfo::labeled(Role::ScrollView, true, &title)); widgets::address(ui, ®ion, "settings-content"); @@ -287,10 +238,7 @@ fn pages_rail(ui: &mut Ui, state: &AppState, view: &mut View) { p.text_1 }; let words = widgets::text(ui, &name, font::BODY, 400.0, FontFamily::Proportional, ink); - let at = egui::pos2( - response.rect.left() + 10.0, - response.rect.center().y - words.size().y / 2.0, - ); + let at = egui::pos2(response.rect.left() + 10.0, response.rect.center().y - words.size().y / 2.0); ui.painter().galley(at, words, ink); if response.clicked() { view.page = page; @@ -305,14 +253,7 @@ fn current_page(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Ac .find(|(page, ..)| *page == view.page) .unwrap_or(Page::ALL[0]); let name = i18n::translate(state.language, name, &[]); - let words = widgets::text( - ui, - &name, - font::READING, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let words = widgets::text(ui, &name, font::READING, 600.0, FontFamily::Proportional, p.text_0); let (rect, _) = ui.allocate_exact_size(words.size(), Sense::hover()); ui.painter().galley(rect.min, words, p.text_0); ui.add_space(gap::BLOCKS); @@ -369,10 +310,7 @@ fn buttons(ui: &mut Ui, state: &AppState, view: &View, actions: &mut Actions) { { ask(Ask::Apply); } - if Button::new(&tr(keys::settings::CANCEL), "settings-cancel") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::settings::CANCEL), "settings-cancel").show(ui).clicked() { ask(Ask::Discard); } }); diff --git a/crates/ui/src/titlebar/preferences/security.rs b/crates/ui/src/titlebar/preferences/security.rs index d295296ed..786bc5621 100644 --- a/crates/ui/src/titlebar/preferences/security.rs +++ b/crates/ui/src/titlebar/preferences/security.rs @@ -39,18 +39,13 @@ impl ChangeView { } fn can_submit(&self) -> bool { - !self.current.is_empty() - && length(&self.next) >= MINIMUM_LENGTH - && *self.confirmation == *self.next + !self.current.is_empty() && length(&self.next) >= MINIMUM_LENGTH && *self.confirmation == *self.next } /// The two phrases, the three fields left empty: nothing typed outlives the attempt. pub(super) fn take(&mut self) -> (Zeroizing, Zeroizing) { self.confirmation = Zeroizing::new(String::new()); - ( - passphrase::take(&mut self.current), - passphrase::take(&mut self.next), - ) + (passphrase::take(&mut self.current), passphrase::take(&mut self.next)) } } @@ -130,13 +125,7 @@ fn copies(ui: &mut Ui, state: &AppState, reveal: &mut bool, actions: &mut Action } } -fn copy_row( - ui: &mut Ui, - state: &AppState, - copy: &Backup, - reveal: &mut bool, - actions: &mut Actions, -) { +fn copy_row(ui: &mut Ui, state: &AppState, copy: &Backup, reveal: &mut bool, actions: &mut Actions) { let language = state.language; let p = palette(ui.ctx()); let when = i18n::time::relative(copy.taken_at, state.clock.now()).text(language); @@ -144,12 +133,7 @@ fn copy_row( let shown = ui.horizontal(|ui| { ui.set_min_height(36.0); ui.label(RichText::new(when).size(font::BODY).color(p.text_1)); - let words = ui.label( - RichText::new(detail) - .size(font::META) - .monospace() - .color(p.text_2), - ); + let words = ui.label(RichText::new(detail).size(font::META).monospace().color(p.text_2)); widgets::address(ui, &words, "backup-detail"); ui.with_layout(Layout::right_to_left(egui::Align::Center), |ui| { if !copy.openable { @@ -169,13 +153,7 @@ fn copy_row( } /// The trigger gives way to a sentence naming what will happen, and the confirm sits elsewhere. -fn confirm_restore( - ui: &mut Ui, - state: &AppState, - copy: &Backup, - reveal: &mut bool, - actions: &mut Actions, -) { +fn confirm_restore(ui: &mut Ui, state: &AppState, copy: &Backup, reveal: &mut bool, actions: &mut Actions) { let language = state.language; let p = palette(ui.ctx()); let tr = |key: Key| i18n::translate(language, key, &[]); @@ -188,17 +166,10 @@ fn confirm_restore( let answers = ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let mut ask = |ask| actions.push(Asked::Menu(Action::Preferences(ask))); - if Button::new(&tr(keys::backups::CANCEL), "backup-cancel") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::backups::CANCEL), "backup-cancel").show(ui).clicked() { ask(Ask::KeepLibrary); } - let action = if working { - keys::backups::RESTORING - } else { - keys::backups::CONFIRM_RESTORE - }; + let action = if working { keys::backups::RESTORING } else { keys::backups::CONFIRM_RESTORE }; if Button::new(&tr(action), "backup-confirm-restore") .kind(Kind::Destructive) .enabled(!working) @@ -230,12 +201,7 @@ fn human_size(bytes: u64, language: Language) -> String { .text(language) } -pub(super) fn dialog( - ctx: &egui::Context, - state: &AppState, - view: &mut View, - actions: &mut Actions, -) { +pub(super) fn dialog(ctx: &egui::Context, state: &AppState, view: &mut View, actions: &mut Actions) { let working = state.security.is_changing(); let cross = i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]); let shown = widgets::dialog( @@ -267,20 +233,10 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut ChangeView, actions: &mut Acti ); widgets::address(ui, &heading, "change-passphrase"); ui.add( - egui::Label::new( - RichText::new(tr(security::DIALOG_LEAD)) - .size(font::LABEL) - .color(p.text_2), - ) - .wrap(), + egui::Label::new(RichText::new(tr(security::DIALOG_LEAD)).size(font::LABEL).color(p.text_2)).wrap(), ); let copies = ui.add( - egui::Label::new( - RichText::new(tr(security::COPIES_NOTE)) - .size(font::CONTROL) - .color(p.text_2), - ) - .wrap(), + egui::Label::new(RichText::new(tr(security::COPIES_NOTE)).size(font::CONTROL).color(p.text_2)).wrap(), ); widgets::address(ui, &copies, "change-passphrase-copies"); let mut submitted = false; @@ -297,19 +253,12 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut ChangeView, actions: &mut Acti field.request_focus(); } submitted |= typed.submitted; - let (_, typed) = phrase_field( - ui, - (&tr(security::NEXT), "change-passphrase-next"), - &mut view.next, - (false, working), - ); + let (_, typed) = + phrase_field(ui, (&tr(security::NEXT), "change-passphrase-next"), &mut view.next, (false, working)); submitted |= typed.submitted; let (_, typed) = phrase_field( ui, - ( - &tr(keys::vault::CONFIRMATION), - "change-passphrase-confirmation", - ), + (&tr(keys::vault::CONFIRMATION), "change-passphrase-confirmation"), &mut view.confirmation, (false, working), ); @@ -321,11 +270,7 @@ fn body(ui: &mut Ui, state: &AppState, view: &mut ChangeView, actions: &mut Acti let mut ask = |ask| actions.push(Asked::Menu(Action::Preferences(ask))); ui.with_layout(Layout::right_to_left(egui::Align::Center), |ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; - let action = if working { - security::CHANGING - } else { - security::CHANGE - }; + let action = if working { security::CHANGING } else { security::CHANGE }; let submit = Button::new(&tr(action), "change-passphrase-submit") .kind(Kind::Filled) .enabled(ready) diff --git a/crates/ui/src/titlebar/preferences/shortcuts.rs b/crates/ui/src/titlebar/preferences/shortcuts.rs index a060c4744..f8926dae0 100644 --- a/crates/ui/src/titlebar/preferences/shortcuts.rs +++ b/crates/ui/src/titlebar/preferences/shortcuts.rs @@ -3,9 +3,7 @@ //! Escape stops the listening without closing the panel, which the next one does. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - CornerRadius, Event, EventFilter, FontFamily, Key, RichText, Role, Sense, Stroke, Ui, Vec2, -}; +use egui::{CornerRadius, Event, EventFilter, FontFamily, Key, RichText, Role, Sense, Stroke, Ui, Vec2}; use i18n::{Key as Text, Language, Message, keys}; use super::general::{group, note, row}; @@ -46,16 +44,8 @@ pub(super) fn page(ui: &mut Ui, state: &AppState, settings: &mut Settings, view: }; let sections = [ (Scope::Global, keys::shortcuts::groups::GLOBAL, global_note), - ( - Scope::Canvas, - keys::shortcuts::groups::CANVAS, - words::CANVAS_NOTE, - ), - ( - Scope::Areas, - keys::shortcuts::groups::AREAS, - words::AREAS_NOTE, - ), + (Scope::Canvas, keys::shortcuts::groups::CANVAS, words::CANVAS_NOTE), + (Scope::Areas, keys::shortcuts::groups::AREAS, words::AREAS_NOTE), ]; for (scope, title, said) in sections { group(ui, language, title); @@ -95,9 +85,7 @@ fn held_elsewhere(ui: &mut Ui, state: &AppState, action: Rebindable, settings: & let said = Message::new(keys::settings::shortcuts::HELD_ELSEWHERE) .with("accelerator", accelerator) .text(state.language); - let words = RichText::new(said) - .size(font::CONTROL) - .color(palette(ui.ctx()).red); + let words = RichText::new(said).size(font::CONTROL).color(palette(ui.ctx()).red); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, &format!("shortcut-held-{}", action.id)); } @@ -111,20 +99,12 @@ fn conflict(ui: &mut Ui, language: Language, accelerator: &str, actions: &[Rebin .with("accelerator", accelerator) .with("actions", names.join(", ")) .text(language); - let words = RichText::new(said) - .size(font::LABEL) - .color(palette(ui.ctx()).red); + let words = RichText::new(said).size(font::LABEL).color(palette(ui.ctx()).red); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, "shortcut-conflict"); } -fn line( - ui: &mut Ui, - language: Language, - action: Rebindable, - settings: &mut Settings, - view: &mut View, -) { +fn line(ui: &mut Ui, language: Language, action: Rebindable, settings: &mut Settings, view: &mut View) { let label = i18n::translate(language, action.label, &[]); let reset = i18n::translate(language, keys::settings::shortcuts::RESET, &[]); row(ui, &label, |ui| { @@ -140,9 +120,7 @@ fn line( let refused = view.refusal.as_ref().filter(|(id, _)| *id == action.id); if let Some((_, refused)) = refused { let said = explain(refused, language); - let words = RichText::new(said) - .size(font::CONTROL) - .color(palette(ui.ctx()).red); + let words = RichText::new(said).size(font::CONTROL).color(palette(ui.ctx()).red); let shown = ui.add(egui::Label::new(words).wrap()); widgets::address(ui, &shown, &format!("shortcut-error-{}", action.id)); } @@ -173,33 +151,16 @@ fn field(ui: &mut Ui, label: &str, action: Rebindable, bindings: &mut Bindings, if listening { // ⚠️ egui drops the focus on Escape before anything is drawn: the field would never see // it, and the panel would close on the first one. - let keeps = EventFilter { - tab: false, - horizontal_arrows: true, - vertical_arrows: true, - escape: true, - }; + let keeps = EventFilter { tab: false, horizontal_arrows: true, vertical_arrows: true, escape: true }; ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, keeps)); view.listens_for_a_global_key |= action.scope == Scope::Global; listen(ui, action, bindings, view); } let edge = if listening { p.amber_edge } else { p.line }; - ui.painter().rect( - response.rect, - corner, - p.bg_1, - Stroke::new(1.0, edge), - egui::StrokeKind::Inside, - ); + ui.painter() + .rect(response.rect, corner, p.bg_1, Stroke::new(1.0, edge), egui::StrokeKind::Inside); let text = bindings.of(action); - let words = widgets::text( - ui, - text, - font::CONTROL, - 600.0, - FontFamily::Monospace, - p.amber_text, - ); + let words = widgets::text(ui, text, font::CONTROL, 600.0, FontFamily::Monospace, p.amber_text); let at = response.rect.center() - words.size() / 2.0; ui.painter().galley(at, words, p.amber_text); } @@ -208,28 +169,19 @@ fn field(ui: &mut Ui, label: &str, action: Rebindable, bindings: &mut Bindings, fn listen(ui: &Ui, action: Rebindable, bindings: &mut Bindings, view: &mut View) { ui.input_mut(|input| { input.events.retain(|event| { - let Event::Key { - key, - physical_key, - pressed: true, - modifiers, - .. - } = event - else { + let Event::Key { key, physical_key, pressed: true, modifiers, .. } = event else { return true; }; match key { Key::Tab => return true, Key::Escape => view.stopped = Some(action.id), - _ => { - match shortcuts::capture(action, (*key, *physical_key), *modifiers, bindings) { - Ok(accelerator) => { - bindings.set(action, accelerator); - view.refusal = None; - } - Err(refused) => view.refusal = Some((action.id, refused)), + _ => match shortcuts::capture(action, (*key, *physical_key), *modifiers, bindings) { + Ok(accelerator) => { + bindings.set(action, accelerator); + view.refusal = None; } - } + Err(refused) => view.refusal = Some((action.id, refused)), + }, } false }); @@ -278,8 +230,7 @@ mod tests { state.global_keys = GlobalKeys::with(system); let mut settings = state.settings.clone(); let mut view = View::default(); - let mut harness = - crate::testing::harness().build_ui(|ui| page(ui, &state, &mut settings, &mut view)); + let mut harness = crate::testing::harness().build_ui(|ui| page(ui, &state, &mut settings, &mut view)); harness.run(); crate::testing::painted(&harness) } @@ -290,10 +241,7 @@ mod tests { for name in ["palette", "capture", "new-note"] { let command = format!(" --action {name}"); - assert!( - painted.iter().any(|text| text.ends_with(&command)), - "{command} in {painted:?}" - ); + assert!(painted.iter().any(|text| text.ends_with(&command)), "{command} in {painted:?}"); } } diff --git a/crates/ui/src/titlebar/preferences/variables.rs b/crates/ui/src/titlebar/preferences/variables.rs index 1ae03b1cc..515af8f2c 100644 --- a/crates/ui/src/titlebar/preferences/variables.rs +++ b/crates/ui/src/titlebar/preferences/variables.rs @@ -21,25 +21,21 @@ pub(super) fn page(ui: &mut Ui, state: &AppState, rows: &mut Option::to_vec)); } - let intro = RichText::new(tr(variables::INTRO)) - .size(font::LABEL) - .color(p.text_2); + let intro = RichText::new(tr(variables::INTRO)).size(font::LABEL).color(p.text_2); ui.add(egui::Label::new(intro).wrap()); ui.add_space(gap::INSET); let Some(rows) = rows else { return; }; if rows.is_empty() { - let none = RichText::new(tr(variables::EMPTY)) - .size(font::LABEL) - .color(p.text_2); + let none = RichText::new(tr(variables::EMPTY)).size(font::LABEL).color(p.text_2); ui.label(none); } let mut removed = None; let twice = duplicates(rows); for (at, row) in rows.iter_mut().enumerate() { - let rejected = (!row.name.is_empty() && !api::notes::is_field_name(&row.name)) - || twice.contains(&row.name); + let rejected = + (!row.name.is_empty() && !api::notes::is_field_name(&row.name)) || twice.contains(&row.name); ui.push_id(at, |ui| { if line(ui, state, row, rejected) { removed = Some(at); @@ -65,9 +61,7 @@ pub(super) fn page(ui: &mut Ui, state: &AppState, rows: &mut Option bo let p = palette(ui.ctx()); let shown = ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::SNUG; - let brace = |text: &str| { - RichText::new(text) - .size(font::BODY) - .monospace() - .color(p.text_2) - }; + let brace = |text: &str| RichText::new(text).size(font::BODY).monospace().color(p.text_2); ui.label(brace("{{")); let (name, placeholder) = (tr(variables::NAME), tr(variables::NAME_PLACEHOLDER)); ui.scope(|ui| { @@ -105,18 +94,9 @@ fn line(ui: &mut Ui, state: &AppState, row: &mut Variable, rejected: bool) -> bo .show(ui); }); let label = Message::new(variables::REMOVE) - .with( - "name", - if row.name.is_empty() { - "—" - } else { - &row.name - }, - ) + .with("name", if row.name.is_empty() { "—" } else { &row.name }) .text(language); - IconButton::new(Icon::X, &label, "variable-remove") - .show(ui) - .clicked() + IconButton::new(Icon::X, &label, "variable-remove").show(ui).clicked() }); widgets::address(ui, &shown.response, "variable-row"); shown.inner diff --git a/crates/ui/src/titlebar/window.rs b/crates/ui/src/titlebar/window.rs index 00c935206..4f5e53d13 100644 --- a/crates/ui/src/titlebar/window.rs +++ b/crates/ui/src/titlebar/window.rs @@ -150,11 +150,8 @@ fn control(ui: &mut Ui, (icon, label): (Icon, &str), author_id: &str, closes: bo (p.bg_2, towards(p.text_1, p.text_0, hover)) }; if hover > 0.0 { - ui.painter().rect_filled( - response.rect, - CornerRadius::ZERO, - fill.gamma_multiply(hover), - ); + ui.painter() + .rect_filled(response.rect, CornerRadius::ZERO, fill.gamma_multiply(hover)); } let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(14.0)); icons::paint(ui, glyph, icon, ink); @@ -165,34 +162,16 @@ fn control(ui: &mut Ui, (icon, label): (Icon, &str), author_id: &str, closes: bo fn zones(screen: Rect) -> [(ResizeDirection, Rect); 8] { let (left, right, top, bottom) = (screen.left(), screen.right(), screen.top(), screen.bottom()); let along = |x: [f32; 2], y: [f32; 2]| Rect::from_min_max(pos2(x[0], y[0]), pos2(x[1], y[1])); - let (inner_x, inner_y) = ( - [left + CORNER, right - CORNER], - [top + CORNER, bottom - CORNER], - ); + let (inner_x, inner_y) = ([left + CORNER, right - CORNER], [top + CORNER, bottom - CORNER]); [ (ResizeDirection::North, along(inner_x, [top, top + EDGE])), - ( - ResizeDirection::South, - along(inner_x, [bottom - EDGE, bottom]), - ), + (ResizeDirection::South, along(inner_x, [bottom - EDGE, bottom])), (ResizeDirection::West, along([left, left + EDGE], inner_y)), (ResizeDirection::East, along([right - EDGE, right], inner_y)), - ( - ResizeDirection::NorthWest, - along([left, left + CORNER], [top, top + CORNER]), - ), - ( - ResizeDirection::NorthEast, - along([right - CORNER, right], [top, top + CORNER]), - ), - ( - ResizeDirection::SouthWest, - along([left, left + CORNER], [bottom - CORNER, bottom]), - ), - ( - ResizeDirection::SouthEast, - along([right - CORNER, right], [bottom - CORNER, bottom]), - ), + (ResizeDirection::NorthWest, along([left, left + CORNER], [top, top + CORNER])), + (ResizeDirection::NorthEast, along([right - CORNER, right], [top, top + CORNER])), + (ResizeDirection::SouthWest, along([left, left + CORNER], [bottom - CORNER, bottom])), + (ResizeDirection::SouthEast, along([right - CORNER, right], [bottom - CORNER, bottom])), ] } diff --git a/crates/ui/src/tools/catalogue.rs b/crates/ui/src/tools/catalogue.rs index 55ec25e05..f84f9c7a3 100644 --- a/crates/ui/src/tools/catalogue.rs +++ b/crates/ui/src/tools/catalogue.rs @@ -57,15 +57,8 @@ pub enum Category { } impl Category { - pub const ALL: [Self; 7] = [ - Self::Text, - Self::Crypto, - Self::Encode, - Self::Generate, - Self::Time, - Self::Calc, - Self::Reference, - ]; + pub const ALL: [Self; 7] = + [Self::Text, Self::Crypto, Self::Encode, Self::Generate, Self::Time, Self::Calc, Self::Reference]; pub fn id(self) -> &'static str { match self { @@ -126,22 +119,11 @@ pub struct NoteInput { } /// A todo list gives its Markdown, as copying it does. -const ANY_NOTE: NoteInput = NoteInput { - kinds: &[], - languages: &[], -}; -const JSON_SNIPPET: NoteInput = NoteInput { - kinds: &[NoteKind::Snippet], - languages: &[NoteLanguage::Json], -}; +const ANY_NOTE: NoteInput = NoteInput { kinds: &[], languages: &[] }; +const JSON_SNIPPET: NoteInput = NoteInput { kinds: &[NoteKind::Snippet], languages: &[NoteLanguage::Json] }; const STRUCTURED_SNIPPET: NoteInput = NoteInput { kinds: &[NoteKind::Snippet], - languages: &[ - NoteLanguage::Json, - NoteLanguage::Yml, - NoteLanguage::Toml, - NoteLanguage::Xml, - ], + languages: &[NoteLanguage::Json, NoteLanguage::Yml, NoteLanguage::Toml, NoteLanguage::Xml], }; /// Its name and its line are the keys `tools..name` and `tools..description`. @@ -192,13 +174,7 @@ const fn reference( keywords: &'static [&'static str], make: fn() -> Box, ) -> ToolEntry { - ToolEntry { - id, - category: Category::Reference, - keywords, - from_note: &[], - make, - } + ToolEntry { id, category: Category::Reference, keywords, from_note: &[], make } } type BuildTable = fn(Language) -> reference::Table; @@ -266,18 +242,14 @@ pub static TOOLS: [ToolEntry; 32] = [ ToolEntry { id: "diff", category: Category::Text, - keywords: &[ - "diff", "compare", "patch", "diff -u", "unified", "json", "rfc 6902", - ], + keywords: &["diff", "compare", "patch", "diff -u", "unified", "json", "rfc 6902"], from_note: &[("text", ANY_NOTE), ("structured", STRUCTURED_SNIPPET)], make: diff::make, }, ToolEntry { id: "hash", category: Category::Crypto, - keywords: &[ - "md5", "sha1", "sha256", "sha512", "sha3", "hmac", "digest", "checksum", "webhook", - ], + keywords: &["md5", "sha1", "sha256", "sha512", "sha3", "hmac", "digest", "checksum", "webhook"], from_note: &[("text", ANY_NOTE)], make: hash::make, }, @@ -310,31 +282,14 @@ pub static TOOLS: [ToolEntry; 32] = [ ToolEntry { id: "jwt", category: Category::Crypto, - keywords: &[ - "jwt", - "json web token", - "bearer", - "hs256", - "claims", - "exp", - "token", - ], + keywords: &["jwt", "json web token", "bearer", "hs256", "claims", "exp", "token"], from_note: &[], make: jwt::make, }, ToolEntry { id: "url-codec", category: Category::Encode, - keywords: &[ - "url", - "uri", - "query", - "querystring", - "percent", - "encodeURIComponent", - "escape", - "parse", - ], + keywords: &["url", "uri", "query", "querystring", "percent", "encodeURIComponent", "escape", "parse"], from_note: &[("text", ANY_NOTE)], make: url_codec::make, }, @@ -406,41 +361,21 @@ pub static TOOLS: [ToolEntry; 32] = [ ToolEntry { id: "qr", category: Category::Generate, - keywords: &[ - "qr", "qr code", "qrcode", "wifi", "vcard", "mailto", "svg", "png", "barcode", - ], + keywords: &["qr", "qr code", "qrcode", "wifi", "vcard", "mailto", "svg", "png", "barcode"], from_note: &[("text", ANY_NOTE)], make: qr::make, }, ToolEntry { id: "dates", category: Category::Time, - keywords: &[ - "timestamp", - "unix", - "epoch", - "iso 8601", - "rfc 3339", - "rfc 2822", - "date", - "now", - ], + keywords: &["timestamp", "unix", "epoch", "iso 8601", "rfc 3339", "rfc 2822", "date", "now"], from_note: &[], make: dates::make, }, ToolEntry { id: "zones", category: Category::Time, - keywords: &[ - "timezone", - "time zone", - "tz", - "iana", - "utc", - "gmt", - "dst", - "offset", - ], + keywords: &["timezone", "time zone", "tz", "iana", "utc", "gmt", "dst", "offset"], from_note: &[], make: zones::make, }, @@ -454,18 +389,14 @@ pub static TOOLS: [ToolEntry; 32] = [ ToolEntry { id: "sizes", category: Category::Calc, - keywords: &[ - "byte", "octet", "kb", "mb", "gb", "kib", "mib", "gib", "bit", "mbit", "size", - ], + keywords: &["byte", "octet", "kb", "mb", "gb", "kib", "mib", "gib", "bit", "mbit", "size"], from_note: &[], make: sizes::make, }, ToolEntry { id: "permissions", category: Category::Calc, - keywords: &[ - "chmod", "umask", "rwx", "octal", "setuid", "setgid", "sticky", "ls -l", - ], + keywords: &["chmod", "umask", "rwx", "octal", "setuid", "setgid", "sticky", "ls -l"], from_note: &[], make: permissions::make, }, @@ -517,114 +448,53 @@ pub static TOOLS: [ToolEntry; 32] = [ }, reference( "http-status", - &[ - "http", "status", "statut", "code", "rfc 9110", "404", "500", "redirect", "nginx", - ], + &["http", "status", "statut", "code", "rfc 9110", "404", "500", "redirect", "nginx"], http_status::make, ), reference( "http-headers", - &[ - "header", - "en-tête", - "cors", - "csp", - "hsts", - "cookie", - "cache-control", - "content-type", - ], + &["header", "en-tête", "cors", "csp", "hsts", "cookie", "cache-control", "content-type"], http_headers::make, ), reference( "mime-types", - &[ - "mime", - "media type", - "content-type", - "extension", - "json", - "png", - "pdf", - ], + &["mime", "media type", "content-type", "extension", "json", "png", "pdf"], mime_types::make, ), reference( "ports", - &[ - "port", - "tcp", - "udp", - "iana", - "ssh", - "postgresql", - "redis", - "firewall", - "pare-feu", - ], + &["port", "tcp", "udp", "iana", "ssh", "postgresql", "redis", "firewall", "pare-feu"], ports::make, ), reference( "signals", - &[ - "signal", "kill", "sigterm", "sigkill", "sighup", "sigint", "posix", "trap", - ], + &["signal", "kill", "sigterm", "sigkill", "sighup", "sigint", "posix", "trap"], signals::make, ), reference( "ascii", - &[ - "ascii", - "character", - "caractère", - "code", - "hex", - "control", - "newline", - "escape", - ], + &["ascii", "character", "caractère", "code", "hex", "control", "newline", "escape"], ascii::make, ), reference( "regex-sheet", - &[ - "regex", - "regexp", - "expression régulière", - "pcre", - "lookbehind", - "lookahead", - "cheat sheet", - ], + &["regex", "regexp", "expression régulière", "pcre", "lookbehind", "lookahead", "cheat sheet"], regex_sheet::make, ), reference( "markdown-sheet", - &[ - "markdown", - "md", - "gfm", - "commonmark", - "readme", - "cheat sheet", - ], + &["markdown", "md", "gfm", "commonmark", "readme", "cheat sheet"], markdown_sheet::make, ), reference( "mustache-sheet", - &[ - "mustache", - "handlebars", - "template", - "gabarit", - "{{", - "partial", - "cheat sheet", - ], + &["mustache", "handlebars", "template", "gabarit", "{{", "partial", "cheat sheet"], mustache_sheet::make, ), ]; +#[cfg(test)] +mod answers_tests; #[cfg(test)] mod calc_tests; #[cfg(test)] diff --git a/crates/ui/src/tools/catalogue/answers_tests.rs b/crates/ui/src/tools/catalogue/answers_tests.rs new file mode 100644 index 000000000..613f1e21a --- /dev/null +++ b/crates/ui/src/tools/catalogue/answers_tests.rs @@ -0,0 +1,776 @@ +//! What each tool answers, case by case: what is typed, what is pressed, and the line that says it. + +use std::sync::Arc; + +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use platform::dialog::{Fixed, NoDialog}; + +use super::text_tests::{click, has, opened, output_values, type_in, value_of, waits_for}; +use crate::notes::bench::{Bench, settle}; +use crate::testing::painted; + +enum Do { + /// Into the field of that id. + Type(&'static str, &'static str), + Press(&'static str), +} +use Do::{Press, Type}; + +/// The tool with each thing done, and the line of that id on screen. +#[track_caller] +fn says(tool: &str, done: &[Do], id: &str) -> Harness<'static, Bench> { + let mut harness = opened(tool); + // The whole page: what is below the window is not drawn. + harness.set_size(egui::vec2(1_300.0, 3_000.0)); + settle(&mut harness); + for each in done { + match each { + Type(field, text) => type_in(&mut harness, field, text), + Press(control) => click(&mut harness, control), + } + } + waits_for(&mut harness, &format!("{tool} says {id}"), |harness| has(harness, id)); + for text in painted(&harness) { + assert!(!text.contains("{{") && !text.starts_with("tools."), "{tool}: {text}"); + } + harness +} + +fn saying(harness: &Harness<'_, Bench>, id: &str, part: &str) { + let said = value_of(harness, id); + assert!(said.contains(part), "{id}: {said:?} lacks {part:?}"); +} + +// Base64 + +#[test] +fn a_text_is_written_in_its_six_encodings_with_what_it_weighs() { + let harness = says("base64", &[Type("base64-input", "Café")], "base64-encodings"); + let values = output_values(&harness); + + for value in ["Q2Fmw6k=", "Q2Fmw6k", "INQWNQ5J", "43 61 66 c3 a9", "67 97 102 195 169"] { + assert!(values.iter().any(|shown| shown == value), "{value} in {values:?}"); + } + saying(&harness, "base64-facts", "é"); +} + +#[test] +fn hexadecimal_is_spaced_and_lowercase_unless_asked() { + let harness = says( + "base64", + &[Type("base64-input", "Café"), Press("base64-spaced"), Press("base64-uppercase")], + "base64-encodings", + ); + + assert!(output_values(&harness).iter().any(|value| value == "436166C3A9")); +} + +#[test] +fn what_is_decoded_says_how_it_was_read() { + let harness = + says("base64", &[Press("base64-direction-1"), Type("base64-input", "Q2Fmw6k=")], "base64-output"); + saying(&harness, "base64-output", "Café"); + assert!(has(&harness, "base64-reading")); + + let harness = says( + "base64", + &[Press("base64-direction-1"), Type("base64-input", "data:text/plain;base64,Q2Fmw6k=")], + "base64-output", + ); + saying(&harness, "base64-reading", "text/plain"); +} + +#[test] +fn what_does_not_decode_says_where() { + for (typed, reading) in [ + ("Q2F*w6k=", "base64-reading-choice-1"), + ("4x", "base64-reading-choice-4"), + ("012", "base64-reading-choice-5"), + ] { + let harness = says( + "base64", + &[Press("base64-direction-1"), Type("base64-input", typed), Press(reading)], + "base64-problem", + ); + assert!(!value_of(&harness, "base64-problem").is_empty()); + } +} + +#[test] +fn bytes_that_are_no_text_are_offered_as_a_file() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("decoded.bin"); + let mut harness = + says("base64", &[Press("base64-direction-1"), Type("base64-input", "/wD+AQ==")], "base64-binary"); + harness.state_mut().state.dialog = Arc::new(NoDialog); + click(&mut harness, "base64-save-file"); + harness.state_mut().state.dialog = Arc::new(Fixed(file.clone())); + assert!(!file.exists()); + + click(&mut harness, "base64-save-file"); + waits_for(&mut harness, "the file is written", |_| file.exists()); + settle(&mut harness); + assert_eq!(std::fs::read(&file).unwrap(), [0xff, 0x00, 0xfe, 0x01]); +} + +#[test] +fn a_file_is_read_as_its_two_base64() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("cafe.txt"); + std::fs::write(&file, "Café").unwrap(); + let mut harness = opened("base64"); + harness.state_mut().state.dialog = Arc::new(Fixed(file)); + click(&mut harness, "base64-source-1"); + click(&mut harness, "base64-pick-file"); + waits_for(&mut harness, "the file is read", |harness| has(harness, "base64-file")); + + saying(&harness, "base64-file", "cafe.txt"); + assert_eq!(output_values(&harness), ["Q2Fmw6k=", "Q2Fmw6k"]); +} + +#[test] +fn a_file_that_is_not_there_says_so() { + let mut harness = opened("base64"); + harness.state_mut().state.dialog = Arc::new(Fixed("no-such-file.bin".into())); + click(&mut harness, "base64-source-1"); + click(&mut harness, "base64-pick-file"); + + waits_for(&mut harness, "it is refused", |harness| has(harness, "base64-file-problem")); +} + +#[test] +fn a_picture_decoded_is_shown_with_its_size() { + // A 1 × 1 GIF. + let gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; + let mut harness = + says("base64", &[Press("base64-direction-1"), Type("base64-input", gif)], "base64-image-facts"); + saying(&harness, "base64-image-facts", "GIF · 1 × 1 px"); + waits_for(&mut harness, "it is drawn", |harness| has(harness, "base64-image-picture")); +} + +// Cron + +#[test] +fn each_expression_is_read_in_words() { + for expression in [ + "* * * * * *", + "*/10 * * * * *", + "5,20 * * * *", + "0 * * * *", + "0 */4 * * *", + "0 2 1-15/2 * *", + "0 2 L * *", + "0 2 15W * *", + "0 2 * * 5L", + "0 2 * * 5#2", + "0 2 1 1,7 *", + "0 2 10 3 *", + ] { + let harness = says("cron", &[Type("cron-input", expression)], "cron-sentence"); + assert!(value_of(&harness, "cron-sentence").chars().count() > 8, "{expression}"); + } +} + +#[test] +fn a_shortcut_is_expanded_and_a_reboot_has_no_time() { + let harness = says("cron", &[Type("cron-input", "@daily")], "cron-expanded"); + saying(&harness, "cron-expanded", "0 0 * * *"); + says("cron", &[Type("cron-input", "@reboot")], "cron-reboot"); +} + +#[test] +fn a_day_of_the_month_and_of_the_week_are_either_one() { + says("cron", &[Type("cron-input", "0 2 1 * 1")], "cron-either-day"); +} + +#[test] +fn a_date_asked_of_a_schedule_is_answered_with_the_nearest_runs() { + let harness = says( + "cron", + &[Type("cron-input", "0 2 * * *"), Type("cron-check", "2026-10-14 03:00")], + "cron-nearest-after", + ); + saying(&harness, "cron-nearest-before", "2026-10-14 02:00"); + saying(&harness, "cron-nearest-after", "2026-10-15 02:00"); + says("cron", &[Type("cron-input", "0 2 * * *"), Type("cron-check", "soon")], "cron-verdict"); +} + +#[test] +fn a_window_is_counted_or_says_why_not() { + let window = + |from, until| [Type("cron-input", "0 2 * * *"), Type("cron-from", from), Type("cron-until", until)]; + let harness = says("cron", &window("2026-10-01", "2026-10-31"), "cron-window-count"); + saying(&harness, "cron-window-count", "30"); + for (from, until) in [("soon", "2026-10-31"), ("2026-10-31", "2026-10-01"), ("2026-10-01", "2126-10-01")] + { + says("cron", &window(from, until), "cron-window-problem"); + } +} + +#[test] +fn a_long_window_lists_its_first_and_last_runs() { + let harness = says( + "cron", + &[Type("cron-input", "0 * * * *"), Type("cron-from", "2026-10-01"), Type("cron-until", "2026-10-31")], + "cron-window-gap", + ); + assert!(has(&harness, "cron-run")); +} + +#[test] +fn an_expression_that_never_runs_says_so() { + says("cron", &[Type("cron-input", "0 0 30 2 *")], "cron-no-runs"); +} + +#[test] +fn a_zone_is_found_chosen_and_left_for_the_local_one() { + let mut harness = says( + "cron", + &[Type("cron-input", "0 2 * * *"), Type("cron-zone-search", "auckland")], + "cron-zone-found-Pacific/Auckland", + ); + click(&mut harness, "cron-zone-found-Pacific/Auckland"); + waits_for(&mut harness, "it is chosen", |harness| has(harness, "cron-zone-local")); + click(&mut harness, "cron-zone-local"); + assert!(!has(&harness, "cron-zone-local")); +} + +// Dates and durations + +#[test] +fn a_gap_is_measured_or_says_why_not() { + let gap = |from, to| [Type("dates-from", from), Type("dates-to", to)]; + says("dates", &gap("2026-10-14 10:00", "2026-10-16 12:30"), "dates-gap-calendar"); + says("dates", &gap("2026-10-16", "2026-10-14"), "dates-gap-negative"); + says("dates", &gap("soon", "2026-10-14"), "dates-gap-problem"); +} + +#[test] +fn now_is_put_where_a_gap_ends() { + let mut harness = opened("dates"); + type_in(&mut harness, "dates-from", "2026-01-01"); + click(&mut harness, "dates-to-now"); + + assert!(!value_of(&harness, "dates-to").is_empty()); +} + +#[test] +fn a_duration_is_read_or_says_why_not() { + says("dates", &[Type("dates-duration", "PT1H30M")], "dates-duration-read"); + says("dates", &[Type("dates-duration", "1h 30m")], "dates-duration-read"); + says("dates", &[Type("dates-duration", "P1M")], "dates-no-totals"); + says("dates", &[Type("dates-duration", "1 furlong")], "dates-duration-problem"); +} + +#[test] +fn a_date_that_does_not_read_says_so() { + for typed in ["the day before", "2026-13-45"] { + says("dates", &[Type("dates-input", typed)], "dates-problem"); + } +} + +// Time zones + +#[test] +fn zones_are_added_found_by_their_city_and_removed() { + let mut harness = says( + "zones", + &[Type("zones-input", "2026-10-14 10:00"), Type("zones-search", "auckland")], + "zones-found-Pacific/Auckland", + ); + click(&mut harness, "zones-found-Pacific/Auckland"); + waits_for(&mut harness, "it is a row", |harness| has(harness, "zones-remove-Pacific/Auckland")); + click(&mut harness, "zones-remove-Pacific/Auckland"); + assert!(!has(&harness, "zones-remove-Pacific/Auckland")); + says("zones", &[Type("zones-search", "zzzzz")], "zones-no-match"); +} + +#[test] +fn a_time_that_does_not_read_says_so() { + says("zones", &[Type("zones-input", "half past")], "zones-problem"); +} + +// Hashes + +#[test] +fn a_digest_says_what_it_could_be() { + for digest in [ + "d41d8cd98f00b204e9800998ecf8427e", + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824", + "abc", + "not a digest at all", + "LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=", + ] { + says("hash", &[Type("hash-expected", digest)], "hash-shape"); + } +} + +#[test] +fn a_digest_that_is_not_the_text_s_says_so() { + let digest = "d41d8cd98f00b204e9800998ecf8427e"; + let harness = says("hash", &[Type("hash-input", "hello"), Type("hash-expected", digest)], "hash-verdict"); + assert!(!value_of(&harness, "hash-verdict").contains("MD5 matches")); +} + +#[test] +fn a_file_is_hashed_and_one_that_is_not_there_says_so() { + let directory = tempfile::tempdir().unwrap(); + let file = directory.path().join("hello.txt"); + std::fs::write(&file, "hello").unwrap(); + let mut harness = opened("hash"); + harness.state_mut().state.dialog = Arc::new(Fixed(file)); + click(&mut harness, "hash-source-1"); + click(&mut harness, "hash-pick-file"); + waits_for(&mut harness, "it is hashed", |harness| has(harness, "hash-results")); + let sha256 = "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"; + assert!(output_values(&harness).iter().any(|value| value == sha256)); + + harness.state_mut().state.dialog = Arc::new(Fixed("no-such-file.txt".into())); + click(&mut harness, "hash-pick-file"); + waits_for(&mut harness, "it is refused", |harness| has(harness, "hash-problem")); +} + +// Checks + +#[test] +fn each_iban_says_what_is_wrong_with_it() { + for (iban, part) in [ + ("FR76 3000 6000 0112 3456 7890 189", ""), + ("FR77 3000 6000 0112 3456 7890 189", "76"), + ("FR76 3000 6000 0112", "27"), + ("FR76 30!0", ""), + ("ZZ68 5390 0754 7034", "ZZ"), + ("DE89 3704 0044 0532 0130 00", ""), + ("GB82 WEST 1234 5698 7654 32", ""), + ] { + let mut harness = opened("checks"); + type_in(&mut harness, "checks-input", iban); + waits_for(&mut harness, iban, |harness| { + has(harness, "checks-verdict") || has(harness, "checks-problem") + }); + assert!(painted(&harness).iter().any(|text| text.contains(part)), "{iban}"); + } +} + +#[test] +fn a_number_is_checked_by_luhn_or_says_why_not() { + for (number, id) in [ + ("4539 1488 0343 6467", "checks-verdict"), + ("4539 1488 0343 6468", "checks-verdict"), + ("7", "checks-problem"), + ("4539x1488", "checks-problem"), + ] { + says("checks", &[Press("checks-kind-1"), Type("checks-input", number)], id); + } +} + +// Networks + +#[test] +fn a_network_of_either_family_is_described() { + for network in + ["10.0.0.0/8", "192.168.1.17/29", "203.0.113.0/27", "2001:db8::/32", "fe80::1/64", "10.0.0.1"] + { + says("cidr", &[Type("cidr-network", network)], "cidr-facts"); + } + says("cidr", &[Type("cidr-network", "300.0.0.0/8")], "cidr-problem"); +} + +#[test] +fn an_address_is_in_a_network_or_out_of_it() { + for address in ["10.1.2.3", "192.168.0.1", "not an address"] { + says("cidr", &[Type("cidr-network", "10.0.0.0/8"), Type("cidr-member", address)], "cidr-membership"); + } +} + +#[test] +fn a_network_is_split_and_the_rest_counted() { + let mut harness = says("cidr", &[Type("cidr-network", "10.0.0.0/8")], "cidr-split-choice-11"); + click(&mut harness, "cidr-split-choice-11"); + waits_for(&mut harness, "it is split", |harness| { + painted(harness).iter().any(|text| text.contains("10.32.0.0/11")) + }); +} + +#[test] +fn a_plan_says_what_has_no_room_and_what_does_not_read() { + let plan = "web 100 +huge 100000 +nothing"; + let harness = + says("cidr", &[Type("cidr-network", "10.0.0.0/24"), Type("cidr-plan", plan)], "cidr-plan-lines"); + assert!(painted(&harness).iter().any(|text| text.contains("10.0.0.0/25"))); + assert!(painted(&harness).iter().any(|text| text.contains("nothing"))); +} + +#[test] +fn a_list_of_networks_is_summed_and_what_does_not_read_is_named() { + let list = "10.0.0.0/25 +10.0.0.128/25 +abc"; + let harness = + says("cidr", &[Type("cidr-network", "10.0.0.0/8"), Type("cidr-list", list)], "cidr-list-unreadable"); + saying(&harness, "cidr-list-unreadable", "abc"); + assert!(painted(&harness).iter().any(|text| text.contains("10.0.0.0/24"))); +} + +// Differences + +#[test] +fn two_texts_are_compared_by_lines_words_or_characters() { + for granularity in ["text-diff-granularity-0", "text-diff-granularity-1", "text-diff-granularity-2"] { + let harness = says( + "diff", + &[ + Type("text-diff-a", "one two\nthree"), + Type("text-diff-b", "one too\nthree\nfour"), + Press(granularity), + ], + "text-diff-added", + ); + assert!(has(&harness, "text-diff-removed")); + } +} + +#[test] +fn a_difference_reads_side_by_side_or_as_one() { + let harness = says( + "diff", + &[Type("text-diff-a", "one\ntwo"), Type("text-diff-b", "one\nthree"), Press("text-diff-layout-1")], + "text-diff-unified", + ); + let lines: Vec = harness + .query_all_by(|node| node.author_id() == Some("text-diff-unified-line")) + .filter_map(|node| node.accesskit_node().label()) + .collect(); + assert!(lines.contains(&"-two".to_owned()) && lines.contains(&"+three".to_owned()), "{lines:?}"); +} + +#[test] +fn what_is_ignored_leaves_two_texts_identical() { + says( + "diff", + &[ + Type("text-diff-a", "One two"), + Type("text-diff-b", "one two"), + Press("text-diff-ignore-case"), + Press("text-diff-ignore-whitespace"), + ], + "text-diff-identical", + ); +} + +#[test] +fn two_documents_are_offered_as_values_and_a_text_as_text() { + let mut harness = says( + "diff", + &[Type("text-diff-a", r#"{"a": 1}"#), Type("text-diff-b", r#"{"a": 2}"#)], + "text-diff-json", + ); + click(&mut harness, "text-diff-as-values"); + waits_for(&mut harness, "compared as values", |harness| has(harness, "structured-diff-modified")); + + let mut harness = says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", "just words"), + Type("structured-diff-b", "other words"), + ], + "structured-diff-not-structured-a", + ); + click(&mut harness, "structured-diff-as-text-a"); + waits_for(&mut harness, "compared as texts", |harness| has(harness, "text-diff-rows")); +} + +#[test] +fn values_are_compared_key_by_key_in_any_format() { + for (a, b) in [ + (r#"{"a": 1, "c": {"d": 1}}"#, r#"{"a": 2, "e": {"f": 1}}"#), + (r#"{"a": [1, 2]}"#, r#"{"a": null}"#), + (r#"{"b": [1, 2]}"#, r#"{"b": [2, 1]}"#), + ("a: 1\nb: two\n", "a: 1\nb: three\nc: 4\n"), + ("a = 1\n[t]\nb = 2\n", "a = 1\n[t]\nb = 3\n"), + ("1", "2"), + ] { + says( + "diff", + &[Press("diff-mode-1"), Type("structured-diff-a", a), Type("structured-diff-b", b)], + "structured-diff-change", + ); + } +} + +#[test] +fn a_change_of_values_is_shown_where_it_is() { + let mut harness = says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1, "b": 2}"#), + Type("structured-diff-b", r#"{"a": 1, "b": 3}"#), + ], + "structured-diff-change", + ); + harness + .query_all_by(|node| node.author_id() == Some("structured-diff-change")) + .next() + .unwrap() + .click(); + settle(&mut harness); + click(&mut harness, "structured-diff-layout-1"); + assert!(has(&harness, "structured-diff-line")); +} + +#[test] +fn values_that_do_not_read_or_do_not_differ_say_so() { + says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1"#), + Type("structured-diff-b", r#"{"a": 1}"#), + ], + "structured-diff-unreadable-a", + ); + says( + "diff", + &[ + Press("diff-mode-1"), + Type("structured-diff-a", r#"{"a": 1}"#), + Type("structured-diff-b", r#"{ "a":1 }"#), + ], + "structured-diff-identical", + ); +} + +// The others + +#[test] +fn a_size_or_a_transfer_that_does_not_read_says_so() { + says("sizes", &[Type("sizes-input", "12 parsecs")], "sizes-problem"); + says("sizes", &[Type("sizes-input", "1536 KiB")], "sizes-results"); +} + +#[test] +fn permissions_are_read_from_either_notation_or_refused() { + says("permissions", &[Type("permissions-symbolic", "rwxz")], "permissions-problem"); + says("permissions", &[Type("permissions-umask", "9")], "permissions-umask-problem"); + says("permissions", &[], "permissions-umask-result"); +} + +#[test] +fn a_document_that_does_not_convert_says_so() { + says("convert", &[Type("convert-input", r#"{"a": "#)], "convert-unreadable"); +} + +#[test] +fn a_token_that_is_no_token_says_so() { + says("jwt", &[Type("jwt-token", "not.a.token")], "jwt-problem"); +} + +#[test] +fn a_url_that_does_not_read_says_so() { + says("url-codec", &[Press("url-tab-1"), Type("url-parser-input", "http://")], "url-parser-problem"); +} + +/// What was shown of it goes with it, and nothing is left for the next opening. +#[test] +fn a_tool_cleared_has_nothing_typed_left() { + for (tool, fields) in [ + ("base64", vec!["base64-input"]), + ("cron", vec!["cron-input"]), + ("dates", vec!["dates-input"]), + ("checks", vec!["checks-input"]), + ("cidr", vec!["cidr-network"]), + ("diff", vec!["text-diff-a", "text-diff-b"]), + ("hash", vec!["hash-input"]), + ("jwt", vec!["jwt-token"]), + ("url-codec", vec!["url-codec-decoded", "url-codec-encoded"]), + ("convert", vec!["convert-input"]), + ("text-stats", vec!["text-stats-input"]), + ] { + let mut harness = opened(tool); + click(&mut harness, "tool-sample"); + waits_for(&mut harness, tool, |harness| !value_of(harness, fields[0]).is_empty()); + click(&mut harness, "tool-clear"); + for field in fields { + assert_eq!(value_of(&harness, field), "", "{tool} {field}"); + } + } +} + +/// New York's, whatever the machine's own zone. +fn in_new_york(text: &str, id: &str) -> Harness<'static, Bench> { + let here = "zones-type-in-America/New_York"; + let mut harness = says("zones", &[Type("zones-input", "2026-07-01 12:00")], "zones-row"); + if !has(&harness, here) { + type_in(&mut harness, "zones-search", "new york"); + waits_for(&mut harness, "it is found", |harness| has(harness, "zones-found-America/New_York")); + click(&mut harness, "zones-found-America/New_York"); + waits_for(&mut harness, "it is a row", |harness| has(harness, here)); + } + click(&mut harness, here); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + let field = |harness: &Harness<'_, Bench>| value_of(harness, "zones-input"); + harness.get_by(|node| node.author_id() == Some("zones-input")).focus(); + harness.step(); + harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + harness.step(); + type_in(&mut harness, "zones-input", text); + assert_eq!(field(&harness), text); + waits_for(&mut harness, text, |harness| has(harness, id)); + harness +} + +#[test] +fn a_time_the_clocks_repeated_is_one_of_two() { + let mut harness = in_new_york("2026-11-01 01:30", "zones-reading-1"); + click(&mut harness, "zones-reading-1"); + waits_for(&mut harness, "the second is taken", |harness| { + let second = harness.get_by(|node| node.author_id() == Some("zones-reading-1")); + second.accesskit_node().toggled() == Some(egui::accesskit::Toggled::True) + }); +} + +#[test] +fn a_time_the_clocks_skipped_says_so() { + let harness = in_new_york("2026-03-08 02:30", "zones-problem"); + + saying(&harness, "zones-problem", "America/New_York"); +} + +#[test] +fn now_is_put_where_a_time_is_typed() { + let mut harness = opened("zones"); + click(&mut harness, "zones-now"); + waits_for(&mut harness, "a time is there", |harness| !value_of(harness, "zones-input").is_empty()); +} + +#[test] +fn a_negative_or_endless_size_says_so() { + for text in ["-12 KB", "99999999999999999999999999999999999999 YB"] { + says("sizes", &[Type("sizes-input", text)], "sizes-problem"); + } +} + +/// Named by its field, so the wrong one is the one corrected. +#[test] +fn each_thing_wrong_with_a_transfer_is_said() { + for (size, rate) in [("lots", "100"), ("1", "fast"), ("-1", "100"), ("1", "0"), ("1", "-2")] { + says("sizes", &[Type("transfer-size", size), Type("transfer-rate", rate)], "transfer-problem"); + } +} + +#[test] +fn each_form_of_a_code_is_encoded() { + for (kind, fields) in [ + ( + "qr-kind-3", + [("qr-to", "ada@example.test"), ("qr-subject", "Hello"), ("qr-body", "Body"), ("qr-to", "x")], + ), + ( + "qr-kind-4", + [ + ("qr-name", "Ada Lovelace"), + ("qr-phone", "+33 1 02 03 04 05"), + ("qr-email", "ada@example.test"), + ("qr-organisation", "Analytical"), + ], + ), + ] { + let mut done = vec![Press(kind)]; + done.extend(fields.map(|(field, text)| Type(field, text))); + says("qr", &done, "qr-facts"); + } +} + +#[test] +fn an_identifier_is_recognised_or_said_not_to_be() { + for (text, id) in [ + ("0190163d-8694-739b-aea5-966c26f8ad91", "identifiers-facts"), + ("00000000-0000-0000-0000-000000000000", "identifiers-facts"), + ("507f1f77bcf86cd799439011", "identifiers-facts"), + ("01ARZ3NDEKTSV4RRFFQ69G5FAV", "identifiers-facts"), + ("8ZZZZZZZZZZZZZZZZZZZZZZZZZ", "identifiers-out-of-range"), + ("V1StGXR8_Z5jdHi6B-myT", "identifiers-possible"), + ("no id at all !", "identifiers-unrecognised"), + ] { + says("identifiers", &[Type("identifiers-checked", text)], id); + } +} + +#[test] +fn how_many_are_drawn_goes_by_one_within_its_bounds() { + let mut harness = opened("identifiers"); + let count = |harness: &Harness<'_, Bench>| value_of(harness, "identifiers-count"); + assert_eq!(count(&harness), "5"); + click(&mut harness, "identifiers-more"); + assert_eq!(count(&harness), "6"); + for _ in 0..8 { + click(&mut harness, "identifiers-fewer"); + } + assert_eq!(count(&harness), "1"); +} + +#[test] +fn another_draw_gives_other_identifiers() { + let mut harness = opened("identifiers"); + waits_for(&mut harness, "they are drawn", |harness| has(harness, "identifiers-list")); + let ids = |harness: &Harness<'_, Bench>| { + painted(harness) + .into_iter() + .filter(|text| text.len() == 36 && text.matches('-').count() == 4) + .collect::>() + }; + let before = ids(&harness); + assert_eq!(before.len(), 5, "{before:?}"); + click(&mut harness, "identifiers-generate"); + waits_for(&mut harness, "others are drawn", |harness| { + let now = ids(harness); + now.len() == 5 && now != before + }); +} + +/// Every tool that offers an example can be cleared of it. +#[test] +fn a_sample_is_gone_once_its_tool_is_cleared() { + for entry in &super::TOOLS { + let mut tool = (entry.make)(); + if !tool.has_sample() { + continue; + } + tool.sample(i18n::Language::En); + tool.clear(); + assert!(tool.result(i18n::Language::En).is_none(), "{}", entry.id); + } +} + +/// Copied in once, where the tool says a note can fill it. +#[test] +fn a_note_is_taken_in_wherever_a_tool_offers_to() { + for entry in &super::TOOLS { + for (slot, _) in entry.from_note { + let mut tool = (entry.make)(); + let note = crate::tools::PickedNote { + title: "Standup".to_owned(), + content: "picked from a note".to_owned(), + language: None, + }; + tool.imported(slot, ¬e); + let mut harness = opened(entry.id); + harness.set_size(egui::vec2(1_300.0, 3_000.0)); + harness.state_mut().state.tools_view.put(entry.id, tool); + settle(&mut harness); + if entry.id == "qr" { + click(&mut harness, "qr-kind-0"); + } + assert!( + painted(&harness).iter().any(|text| text.contains("picked from a note")), + "{} {slot}", + entry.id + ); + } + } +} diff --git a/crates/ui/src/tools/catalogue/ascii.rs b/crates/ui/src/tools/catalogue/ascii.rs index 00f285c7b..4ca56aac6 100644 --- a/crates/ui/src/tools/catalogue/ascii.rs +++ b/crates/ui/src/tools/catalogue/ascii.rs @@ -12,12 +12,7 @@ const DELETE: u32 = 127; const GROUPS: [&str; 5] = ["control", "punctuation", "digits", "upper", "lower"]; /// The abbreviation, the standard's own name, the usual escape, and what else it is searched by. -struct Control( - &'static str, - &'static str, - &'static str, - &'static [&'static str], -); +struct Control(&'static str, &'static str, &'static str, &'static [&'static str]); const CONTROLS: [Control; 32] = [ Control("NUL", "Null", "\\0", &[]), @@ -96,9 +91,7 @@ fn code_in(query: &str) -> Option { let hexadecimal = lower.len() == 2 && lower.bytes().all(|it| it.is_ascii_hexdigit()) && lower.bytes().any(|it| it.is_ascii_alphabetic()); - hexadecimal - .then(|| u32::from_str_radix(&lower, 16).ok()) - .flatten() + hexadecimal.then(|| u32::from_str_radix(&lower, 16).ok()).flatten() } /// One character is that character, case and all, or a one-digit code: « A » is 65 alone, « 6 » @@ -125,21 +118,13 @@ fn row(code: u32, language: Language) -> ReferenceRow { }; let name = control.map_or_else(|| said.clone(), |it| it.1.to_owned()); let name = Cell::text(name); - let name = if control.is_some() { - name.below(said.clone()) - } else { - name - }; + let name = if control.is_some() { name.below(said.clone()) } else { name }; let cells = vec![ Cell::mono(code.to_string()), Cell::mono(format!("{code:02X}")), Cell::mono(format!("{code:03o}")), Cell::mono(format!("{code:08b}")), - if control.is_some() { - Cell::chips(vec![shown.clone()]) - } else { - Cell::mono(shown.clone()) - }, + if control.is_some() { Cell::chips(vec![shown.clone()]) } else { Cell::mono(shown.clone()) }, name, Cell::mono(control.map_or("", |it| it.2)), Cell::mono(ctrl.clone()), @@ -150,23 +135,11 @@ fn row(code: u32, language: Language) -> ReferenceRow { searched.extend([control.0, control.1, control.2]); searched.extend(control.3); } - let what = if code == SPACE { - said.clone() - } else { - shown.clone() - }; + let what = if code == SPACE { said.clone() } else { shown.clone() }; let title = format!("{shown} ({code})"); - let said_as = if said.is_empty() { - control.map_or("", |it| it.1) - } else { - said.as_str() - }; + let said_as = if said.is_empty() { control.map_or("", |it| it.1) } else { said.as_str() }; let hexadecimal = format!("0x{code:02X}"); - let line = if said_as.is_empty() { - hexadecimal - } else { - format!("{said_as} · {hexadecimal}") - }; + let line = if said_as.is_empty() { hexadecimal } else { format!("{said_as} · {hexadecimal}") }; let mut row = ReferenceRow::new(code.to_string(), group, cells) .searched_by(searched) .found_as(title, line); @@ -176,10 +149,7 @@ fn row(code: u32, language: Language) -> ReferenceRow { pub(crate) fn table(language: Language) -> Table { let tr = |id: &str| word(language, &format!("tools.ascii.columns.{id}")); - let column = |id: &str, share| Column { - label: tr(id), - share, - }; + let column = |id: &str, share| Column { label: tr(id), share }; Table { rows: (0..128).map(|code| row(code, language)).collect(), groups: GROUPS diff --git a/crates/ui/src/tools/catalogue/base64.rs b/crates/ui/src/tools/catalogue/base64.rs index 0b92c0891..ea9762509 100644 --- a/crates/ui/src/tools/catalogue/base64.rs +++ b/crates/ui/src/tools/catalogue/base64.rs @@ -7,8 +7,8 @@ use std::sync::Arc; use egui::{ColorImage, TextureHandle, TextureOptions, Ui, Vec2}; use engine::notes::language::Language as NoteLanguage; use engine::tools::bases::{ - Base64FileAnswer, ByteEncoding, DecodeAnswer, DecodeRequest, DecodedBytes, DecodedImage, - EncodeRequest, Encodings, ImagePreview, SavedBytes, + Base64FileAnswer, ByteEncoding, DecodeAnswer, DecodeRequest, DecodedBytes, DecodedImage, EncodeRequest, + Encodings, ImagePreview, SavedBytes, }; use engine::tools::image::ImageFormat; use i18n::{Language, Message, keys}; @@ -19,8 +19,8 @@ use crate::backend::Pending; use crate::tools::live::{Live, Turn}; use crate::tools::ui::note_picker::PickedNote; use crate::tools::ui::{ - CopyValue, ResultRow, card, check, columns, hint, named, note_import, problem, result_rows, - section_head, section_title, text_area, + CopyValue, ResultRow, card, check, columns, hint, named, note_import, problem, result_rows, section_head, + section_title, text_area, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, Segmented, address}; @@ -49,10 +49,7 @@ enum Asked { Saving(Pending), } -#[expect( - clippy::struct_excessive_bools, - reason = "two options, two buttons pressed" -)] +#[expect(clippy::struct_excessive_bools, reason = "two options, two buttons pressed")] pub(super) struct Base64Tool { direction: Direction, source: Source, @@ -126,12 +123,9 @@ impl Base64Tool { fn rows(&self) -> Vec<(&'static str, &str)> { if self.source == Source::File { return match self.encoded_file.value() { - Some(Base64FileAnswer::Encoded { - base64, base64_url, .. - }) => vec![ - ("base64", base64.as_str()), - ("base64Url", base64_url.as_str()), - ], + Some(Base64FileAnswer::Encoded { base64, base64_url, .. }) => { + vec![("base64", base64.as_str()), ("base64Url", base64_url.as_str())] + } _ => Vec::new(), }; } @@ -151,15 +145,10 @@ impl Base64Tool { use keys::tools::base64::{directions, sources}; let language = drawn.language; let tr = |key| i18n::translate(language, key, &[]); - let options = [ - (Direction::Encode, tr(directions::ENCODE)), - (Direction::Decode, tr(directions::DECODE)), - ]; + let options = + [(Direction::Encode, tr(directions::ENCODE)), (Direction::Decode, tr(directions::DECODE))]; let options = options.each_ref().map(|(id, name)| (*id, name.as_str())); - let origins = [ - (Source::Text, tr(sources::TEXT)), - (Source::File, tr(sources::FILE)), - ]; + let origins = [(Source::Text, tr(sources::TEXT)), (Source::File, tr(sources::FILE))]; let origins = origins.each_ref().map(|(id, name)| (*id, name.as_str())); let (direction, source) = (&mut self.direction, &mut self.source); section_head(ui, &tr(keys::tools::INPUT), |ui| { @@ -350,9 +339,7 @@ impl Base64Tool { address(ui, &label, "base64-output"); } DecodedBytes::Binary { bytes, preview } => { - let words = Message::new(keys::tools::base64::BINARY) - .with("count", *bytes) - .text(language); + let words = Message::new(keys::tools::base64::BINARY).with("count", *bytes).text(language); let said = hint(ui, &words); address(ui, &said, "base64-binary"); let shown = egui::RichText::new(preview).font(egui::FontId::monospace(font::LABEL)); @@ -362,11 +349,7 @@ impl Base64Tool { self.wants_save = true; } } - DecodedBytes::Invalid { - problem: reason, - at, - character, - } => { + DecodedBytes::Invalid { problem: reason, at, character } => { let words = invalid_words(language, *reason, *at, character.as_deref()); problem(ui, &words, "base64-problem"); } @@ -419,10 +402,7 @@ impl Base64Tool { } if std::mem::take(&mut self.wants_save) { let format = self.decoded.value().and_then(|it| it.image.as_ref()); - let name = format!( - "decoded.{}", - format.map_or("bin", |it| extension(it.format)) - ); + let name = format!("decoded.{}", format.map_or("bin", |it| extension(it.format))); let dialog = Arc::clone(turn.dialog); let pending = turn.backend.compute(move |_| Ok(dialog.save(&name))); self.asked = Some(Asked::Destination(pending)); @@ -442,10 +422,7 @@ impl Base64Tool { let Some(answer) = pending.poll() else { return }; self.asked = None; if let Ok(Some(path)) = answer { - let request = DecodeRequest { - text: self.text.clone(), - reading: self.reading, - }; + let request = DecodeRequest { text: self.text.clone(), reading: self.reading }; let path = path.display().to_string(); let saved = api::tools::save_bytes(turn.backend, request, path); self.asked = Some(Asked::Saving(saved)); @@ -475,10 +452,7 @@ impl Base64Tool { /// The picture off the window's thread, once a frame until it is on the screen. fn follow_picture(&mut self, turn: &Turn<'_>) { let wanted = self.decoded.value().and_then(|it| match &it.image { - Some(DecodedImage { - preview: ImagePreview::Shown { data_url }, - .. - }) => Some(data_url.clone()), + Some(DecodedImage { preview: ImagePreview::Shown { data_url }, .. }) => Some(data_url.clone()), _ => None, }); let Some(wanted) = wanted else { @@ -490,9 +464,7 @@ impl Base64Tool { let asked = self.drawing.as_ref().is_some_and(|(it, _)| *it == wanted); if !current && !asked { let uri = wanted.clone(); - let pending = turn - .backend - .compute(move |_| Ok(crate::state::attachments::decode(&uri))); + let pending = turn.backend.compute(move |_| Ok(crate::state::attachments::decode(&uri))); self.drawing = Some((wanted, pending)); } if let Some((uri, pending)) = &mut self.drawing @@ -501,9 +473,7 @@ impl Base64Tool { let uri = std::mem::take(uri); self.drawing = None; if let Ok(Some(image)) = answer { - let texture = - turn.ctx - .load_texture("base64-picture", image, TextureOptions::NEAREST); + let texture = turn.ctx.load_texture("base64-picture", image, TextureOptions::NEAREST); self.picture = Some((uri, texture)); } } @@ -519,15 +489,9 @@ fn invalid_words( let (Some(at), Some(character)) = (at, character) else { return i18n::translate(language, keys::tools::base64::problems::LENGTH, &[]); }; - let path = format!( - "tools.base64.problems.{}", - json!(reason).as_str().unwrap_or_default() - ); + let path = format!("tools.base64.problems.{}", json!(reason).as_str().unwrap_or_default()); i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key) - .with("character", character) - .with("at", at + 1) - .text(language) + Message::new(key).with("character", character).with("at", at + 1).text(language) }) } @@ -538,9 +502,8 @@ fn drawn_picture(ui: &mut Ui, texture: &TextureHandle, image: &DecodedImage) { let scale = if small { 4.0 } else { 1.0 }; let room = ui.available_width(); let shown = size * scale * (room / (size.x * scale)).min(1.0); - let drawn = ui.add( - egui::Image::new((texture.id(), shown)).fit_to_exact_size(Vec2::new(shown.x, shown.y)), - ); + let drawn = + ui.add(egui::Image::new((texture.id(), shown)).fit_to_exact_size(Vec2::new(shown.x, shown.y))); address(ui, &drawn, "base64-image-picture"); } @@ -550,25 +513,13 @@ impl Tool for Base64Tool { self.adopt_files(turn); let encoding = self.direction == Direction::Encode; let text = (encoding && self.source == Source::Text && !self.text.is_empty()).then(|| { - EncodeRequest { - text: self.text.clone(), - spaced: self.spaced, - uppercase: self.uppercase, - } + EncodeRequest { text: self.text.clone(), spaced: self.spaced, uppercase: self.uppercase } }); - self.encoded_text - .update(turn, text, api::tools::encode_bytes); - let file = self - .path - .clone() - .filter(|_| encoding && self.source == Source::File); - self.encoded_file - .update(turn, file, api::tools::encode_base64_file); + self.encoded_text.update(turn, text, api::tools::encode_bytes); + let file = self.path.clone().filter(|_| encoding && self.source == Source::File); + self.encoded_file.update(turn, file, api::tools::encode_base64_file); let decoding = !encoding && !self.text.trim().is_empty(); - let request = decoding.then(|| DecodeRequest { - text: self.text.clone(), - reading: self.reading, - }); + let request = decoding.then(|| DecodeRequest { text: self.text.clone(), reading: self.reading }); self.decoded.update(turn, request, api::tools::decode_bytes); self.follow_picture(turn); } @@ -584,8 +535,7 @@ impl Tool for Base64Tool { fn result(&self, language: Language) -> Option { let tr = |key| i18n::translate(language, key, &[]); if self.direction == Direction::Decode { - let Some(DecodedBytes::Text { text, .. }) = self.decoded.value().map(|it| &it.decoded) - else { + let Some(DecodedBytes::Text { text, .. }) = self.decoded.value().map(|it| &it.decoded) else { return None; }; return Some(ToolResult { @@ -597,10 +547,7 @@ impl Tool for Base64Tool { } let rows = self.rows(); let width = rows.iter().map(|(id, _)| id.len()).max()?; - let content: Vec = rows - .iter() - .map(|(id, value)| format!("{id:width$} {value}")) - .collect(); + let content: Vec = rows.iter().map(|(id, value)| format!("{id:width$} {value}")).collect(); Some(ToolResult { title: tr(keys::tools::base64::NOTE_ENCODED), language: NoteLanguage::Txt, diff --git a/crates/ui/src/tools/catalogue/calc_tests.rs b/crates/ui/src/tools/catalogue/calc_tests.rs index 34fa2caa9..d37f4aa48 100644 --- a/crates/ui/src/tools/catalogue/calc_tests.rs +++ b/crates/ui/src/tools/catalogue/calc_tests.rs @@ -11,16 +11,11 @@ fn a_size_is_written_in_every_unit() { let mut harness = opened("sizes"); type_in(&mut harness, "sizes-input", "1 GiB"); - waits_for(&mut harness, "the size is converted", |harness| { - has(harness, "sizes-results") - }); + waits_for(&mut harness, "the size is converted", |harness| has(harness, "sizes-results")); assert!(has(&harness, "sizes-unit-in-text")); let values = output_values(&harness); - assert!( - values.iter().any(|it| it.contains("1,073,741,824")), - "{values:?}" - ); + assert!(values.iter().any(|it| it.contains("1,073,741,824")), "{values:?}"); } #[test] @@ -29,9 +24,7 @@ fn what_is_no_size_says_where_it_stops() { type_in(&mut harness, "sizes-input", "abc"); - waits_for(&mut harness, "the text is refused", |harness| { - has(harness, "sizes-problem") - }); + waits_for(&mut harness, "the text is refused", |harness| has(harness, "sizes-problem")); } #[test] @@ -40,9 +33,7 @@ fn a_transfer_is_estimated_and_compared_with_common_links() { click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the time is estimated", |harness| { - has(harness, "transfer-time") - }); + waits_for(&mut harness, "the time is estimated", |harness| has(harness, "transfer-time")); assert!(has(&harness, "transfer-connections")); } @@ -54,24 +45,12 @@ fn place(harness: &Harness<'_, Bench>, id: &str) -> egui::Rect { #[test] fn the_two_parts_of_sizes_and_of_dates_are_on_one_page() { for (tool, first, second, answers) in [ - ( - "sizes", - "sizes-input", - "transfer-size", - ["sizes-results", "transfer-time"], - ), - ( - "dates", - "dates-input", - "dates-from", - ["dates-forms", "dates-gap"], - ), + ("sizes", "sizes-input", "transfer-size", ["sizes-results", "transfer-time"]), + ("dates", "dates-input", "dates-from", ["dates-forms", "dates-gap"]), ] { let mut harness = opened(tool); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "both have answered", |harness| { - answers.iter().all(|id| has(harness, id)) - }); + waits_for(&mut harness, "both have answered", |harness| answers.iter().all(|id| has(harness, id))); assert!(place(&harness, first).right() < place(&harness, second).left()); harness.set_size(egui::vec2(800.0, 900.0)); @@ -112,25 +91,17 @@ fn an_octal_mode_is_read_and_written_as_commands() { let mut harness = opened("permissions"); type_in(&mut harness, "permissions-octal", "754"); - waits_for(&mut harness, "the mode is read", |harness| { - has(harness, "permissions-words") - }); + waits_for(&mut harness, "the mode is read", |harness| has(harness, "permissions-words")); assert_eq!(value_of(&harness, "permissions-symbolic"), "rwxr-xr--"); - assert!( - output_values(&harness) - .iter() - .any(|it| it.contains("chmod 754")) - ); + assert!(output_values(&harness).iter().any(|it| it.contains("chmod 754"))); } #[test] fn a_box_rewrites_the_mode() { let mut harness = opened("permissions"); type_in(&mut harness, "permissions-octal", "644"); - waits_for(&mut harness, "the mode is read", |harness| { - has(harness, "permissions-words") - }); + waits_for(&mut harness, "the mode is read", |harness| has(harness, "permissions-words")); click(&mut harness, "permissions-owner-execute"); @@ -143,9 +114,7 @@ fn a_mode_with_a_wrong_digit_is_refused() { type_in(&mut harness, "permissions-octal", "789"); - waits_for(&mut harness, "the mode is refused", |harness| { - has(harness, "permissions-problem") - }); + waits_for(&mut harness, "the mode is refused", |harness| has(harness, "permissions-problem")); } #[test] @@ -153,37 +122,21 @@ fn a_valid_iban_names_its_country_and_its_parts() { let mut harness = opened("checks"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the number is checked", |harness| { - has(harness, "checks-result") - }); + waits_for(&mut harness, "the number is checked", |harness| has(harness, "checks-result")); assert_eq!(value_of(&harness, "checks-verdict"), "Valid"); - assert!( - output_values(&harness) - .iter() - .any(|it| it.contains("France (FR)")) - ); + assert!(output_values(&harness).iter().any(|it| it.contains("France (FR)"))); } #[test] -fn a_wrong_card_number_gives_the_digit_it_asks_for_and_leaves_no_trace() { +fn a_wrong_card_number_is_invalid_and_never_saved_as_a_note() { let mut harness = opened("checks"); type_in(&mut harness, "checks-input", "4111111111111112"); - waits_for(&mut harness, "the number is checked", |harness| { - has(harness, "checks-result") - }); - assert_eq!(value_of(&harness, "checks-verdict"), "Invalid"); + waits_for(&mut harness, "the number is checked", |harness| has(harness, "checks-result")); + assert_eq!(value_of(&harness, "checks-verdict"), "Invalid"); assert!(!has(&harness, "tool-save-as-note")); - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("checks")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "checks-input"), ""); } #[test] @@ -191,9 +144,7 @@ fn a_block_is_described_with_what_it_holds() { let mut harness = opened("cidr"); type_in(&mut harness, "cidr-network", "192.168.1.0/24"); - waits_for(&mut harness, "the block is read", |harness| { - has(harness, "cidr-facts") - }); + waits_for(&mut harness, "the block is read", |harness| has(harness, "cidr-facts")); let values = output_values(&harness); assert!(values.contains(&"255.255.255.0".to_owned()), "{values:?}"); @@ -207,18 +158,14 @@ fn an_address_is_found_inside_or_outside_the_block() { type_in(&mut harness, "cidr-network", "192.168.1.0/24"); type_in(&mut harness, "cidr-member", "192.168.1.40"); - waits_for(&mut harness, "the address is placed", |harness| { - has(harness, "cidr-membership") - }); + waits_for(&mut harness, "the address is placed", |harness| has(harness, "cidr-membership")); } #[test] fn a_mask_chosen_becomes_the_block() { let mut harness = opened("cidr"); type_in(&mut harness, "cidr-network", "10.0.0.0/8"); - waits_for(&mut harness, "the masks are listed", |harness| { - has(harness, "cidr-masks") - }); + waits_for(&mut harness, "the masks are listed", |harness| has(harness, "cidr-masks")); click(&mut harness, "cidr-masks-row-1"); @@ -232,9 +179,7 @@ fn what_is_no_block_is_refused() { type_in(&mut harness, "cidr-network", "not a block"); - waits_for(&mut harness, "the block is refused", |harness| { - has(harness, "cidr-problem") - }); + waits_for(&mut harness, "the block is refused", |harness| has(harness, "cidr-problem")); } #[test] @@ -263,11 +208,7 @@ fn frame(harness: &mut Harness<'_, Bench>, events: Vec) { } fn press(harness: &mut Harness<'_, Bench>, id: &str) { - let pos = harness - .get_by(|node| node.author_id() == Some(id)) - .rect() - .left_center() - + egui::vec2(7.0, 0.0); + let pos = harness.get_by(|node| node.author_id() == Some(id)).rect().left_center() + egui::vec2(7.0, 0.0); let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, @@ -294,9 +235,7 @@ fn painted_ticked(harness: &Harness<'_, Bench>, id: &str) -> bool { fn a_box_clicked_is_ticked_once_and_stays_so() { let mut harness = opened("permissions"); type_in(&mut harness, "permissions-octal", "644"); - waits_for(&mut harness, "the mode is read", |harness| { - has(harness, "permissions-words") - }); + waits_for(&mut harness, "the mode is read", |harness| has(harness, "permissions-words")); assert!(!painted_ticked(&harness, "permissions-owner-execute")); press(&mut harness, "permissions-owner-execute"); @@ -315,9 +254,7 @@ fn a_box_clicked_is_ticked_once_and_stays_so() { fn two_boxes_clicked_at_once_are_both_ticked() { let mut harness = opened("permissions"); type_in(&mut harness, "permissions-octal", "600"); - waits_for(&mut harness, "the mode is read", |harness| { - has(harness, "permissions-words") - }); + waits_for(&mut harness, "the mode is read", |harness| has(harness, "permissions-words")); press(&mut harness, "permissions-group-read"); press(&mut harness, "permissions-others-read"); @@ -345,9 +282,7 @@ fn texts(harness: &Harness<'_, Bench>) -> std::collections::BTreeMap, id: &str, at: usize) -> String { - harness - .get_all_by(|node| node.author_id() == Some(id)) - .nth(at) - .unwrap() - .click(); + harness.get_all_by(|node| node.author_id() == Some(id)).nth(at).unwrap().click(); let mut text = None; for _ in 0..4 { harness.step(); @@ -440,15 +364,11 @@ fn copied(harness: &mut Harness<'_, Bench>, id: &str, at: usize) -> String { #[test] fn a_printed_number_is_copied_as_it_is_shown_or_raw() { let mut harness = opened("checks"); - waits_for(&mut harness, "numbers are drawn", |harness| { - has(harness, "checks-numbers") - }); + waits_for(&mut harness, "numbers are drawn", |harness| has(harness, "checks-numbers")); let shown = output_values(&harness)[0].clone(); assert!(shown.contains(' ')); - let first = harness - .get_all_by(|node| node.author_id() == Some("copy-raw")) - .count(); + let first = harness.get_all_by(|node| node.author_id() == Some("copy-raw")).count(); assert_eq!(first, 5, "one a number"); // « Copy all » comes before the rows. assert_eq!(copied(&mut harness, "copy-value", 1), shown); @@ -458,9 +378,7 @@ fn a_printed_number_is_copied_as_it_is_shown_or_raw() { #[test] fn the_numbers_of_an_identity_have_both_copies_and_its_email_one() { let mut harness = opened("identity"); - waits_for(&mut harness, "a person is drawn", |harness| { - has(harness, "identity-block-contact") - }); + waits_for(&mut harness, "a person is drawn", |harness| has(harness, "identity-block-contact")); let raws: Vec = harness .query_all_by(|node| node.author_id() == Some("copy-raw")) .map(|node| node.accesskit_node().label().unwrap_or_default()) @@ -469,9 +387,5 @@ fn the_numbers_of_an_identity_have_both_copies_and_its_email_one() { let wanted = format!("Copy {number}, raw"); assert!(raws.contains(&wanted), "{number}: {raws:?}"); } - assert!( - !raws - .iter() - .any(|it| it.contains("mail") || it.contains("Address")) - ); + assert!(!raws.iter().any(|it| it.contains("mail") || it.contains("Address"))); } diff --git a/crates/ui/src/tools/catalogue/case.rs b/crates/ui/src/tools/catalogue/case.rs index 7ba8c5d8e..8c24c8414 100644 --- a/crates/ui/src/tools/catalogue/case.rs +++ b/crates/ui/src/tools/catalogue/case.rs @@ -81,10 +81,7 @@ impl CaseTool { strip_accents: self.strip_accents, per_line: self.per_line, title_case_language: self.title_language, - slug: SlugOptions { - separator: self.separator, - lowercase: self.lowercase, - }, + slug: SlugOptions { separator: self.separator, lowercase: self.lowercase }, }) } @@ -125,10 +122,7 @@ impl CaseTool { return; }; let p = palette(ui.ctx()); - label( - ui, - &i18n::translate(language, keys::tools::case::WORDS, &[]), - ); + label(ui, &i18n::translate(language, keys::tools::case::WORDS, &[])); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = egui::Vec2::splat(gap::SNUG); for word in &answer.words { @@ -152,10 +146,7 @@ impl CaseTool { label(ui, &tr(keys::tools::case::SLUG)); let separators = [ (SlugSeparator::Dash, tr(keys::tools::case::separators::DASH)), - ( - SlugSeparator::Underscore, - tr(keys::tools::case::separators::UNDERSCORE), - ), + (SlugSeparator::Underscore, tr(keys::tools::case::separators::UNDERSCORE)), (SlugSeparator::Dot, tr(keys::tools::case::separators::DOT)), ]; let separators = separators.each_ref().map(|(id, name)| (*id, name.as_str())); @@ -187,10 +178,7 @@ impl CaseTool { .filter(|conversion| conversion.group == group) .map(|conversion| (shown_name(conversion.case, language), &conversion.value)) .collect(); - let rows: Vec<_> = shown - .iter() - .map(|(name, value)| ResultRow::new(name, value)) - .collect(); + let rows: Vec<_> = shown.iter().map(|(name, value)| ResultRow::new(name, value)).collect(); result_rows(ui, &rows, language); } group_title(ui, &tr(keys::tools::case::FOR_URL)); @@ -235,10 +223,7 @@ impl Tool for CaseTool { } fn result(&self, language: Language) -> Option { - let answer = self - .answer - .value() - .filter(|it| !it.conversions.is_empty())?; + let answer = self.answer.value().filter(|it| !it.conversions.is_empty())?; let mut rows: Vec<(&str, &str)> = answer .conversions .iter() @@ -256,9 +241,7 @@ impl Tool for CaseTool { let first = asked.text.trim().lines().next().unwrap_or_default().trim(); let text: String = first.chars().take(40).collect(); Some(ToolResult { - title: Message::new(keys::tools::case::NOTE_TITLE) - .with("text", text) - .text(language), + title: Message::new(keys::tools::case::NOTE_TITLE).with("text", text).text(language), language: NoteLanguage::Txt, content: content.join("\n"), warning: None, diff --git a/crates/ui/src/tools/catalogue/checks.rs b/crates/ui/src/tools/catalogue/checks.rs index 9944f11d0..c4aa618bb 100644 --- a/crates/ui/src/tools/catalogue/checks.rs +++ b/crates/ui/src/tools/catalogue/checks.rs @@ -14,8 +14,8 @@ use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - CopyValue, ResultRow, card, columns, group_title, hint, label, line, named, number_field, - paragraph, problem, result_rows, section_head, section_title, + CopyValue, ResultRow, card, columns, group_title, hint, label, line, named, number_field, paragraph, + problem, result_rows, section_head, section_title, }; use crate::tools::{Drawn, Tool}; use crate::widgets::{Button, ChoiceMenu, Kind, Segmented, TextField, address}; @@ -63,11 +63,7 @@ pub(super) fn make() -> Box { fn head(ui: &mut Ui, title: &str, valid: bool, reason: Option, language: Language) { let p = palette(ui.ctx()); - let verdict = if valid { - keys::tools::checks::VALID - } else { - keys::tools::checks::INVALID - }; + let verdict = if valid { keys::tools::checks::VALID } else { keys::tools::checks::INVALID }; let verdict = i18n::translate(language, verdict, &[]); let ink = if valid { p.green } else { p.red }; ui.add_space(gap::GROUPS); @@ -100,60 +96,34 @@ struct Luhn<'a> { fn luhn_card(ui: &mut Ui, luhn: &Luhn<'_>, language: Language) { use keys::tools::checks as words; let tr = |key| i18n::translate(language, key, &[]); - let title = if luhn.network.is_some() { - words::titles::CARD - } else { - words::titles::LUHN - }; + let title = if luhn.network.is_some() { words::titles::CARD } else { words::titles::LUHN }; let reason = (!luhn.valid).then(|| { Message::new(words::LUHN_INVALID) .with("digit", luhn.expected_last) .text(language) }); - let length = Message::new(words::DIGITS) - .with("count", luhn.length) - .text(language); - let key = if luhn.valid { - words::LUHN_KEY_RIGHT - } else { - words::LUHN_KEY_WRONG - }; - let given = luhn - .grouped - .chars() - .last() - .map(String::from) - .unwrap_or_default(); + let length = Message::new(words::DIGITS).with("count", luhn.length).text(language); + let key = if luhn.valid { words::LUHN_KEY_RIGHT } else { words::LUHN_KEY_WRONG }; + let given = luhn.grouped.chars().last().map(String::from).unwrap_or_default(); let key = Message::new(key) .with("given", given) .with("expected", luhn.expected_last) .text(language); - let network = luhn - .network - .map(|it| named(language, "tools.checks.networks", &json!(it))); - let names = ( - tr(words::LENGTH), - tr(words::KEY), - tr(words::NETWORK), - tr(words::NUMBER), - tr(words::COMPLETED), - ); + let network = luhn.network.map(|it| named(language, "tools.checks.networks", &json!(it))); + let names = + (tr(words::LENGTH), tr(words::KEY), tr(words::NETWORK), tr(words::NUMBER), tr(words::COMPLETED)); card(ui, "checks-result", |ui| { head(ui, &tr(title), luhn.valid, reason, language); group_title(ui, &tr(words::CHECKS_TITLE)); - let mut rows = vec![ - ResultRow::new(&names.0, &length).reading(), - ResultRow::new(&names.1, &key).reading(), - ]; + let mut rows = + vec![ResultRow::new(&names.0, &length).reading(), ResultRow::new(&names.1, &key).reading()]; if let Some(network) = &network { rows.push(ResultRow::new(&names.2, network).reading()); } result_rows(ui, &rows, language); group_title(ui, &tr(words::CONTENT)); - let (number, completed) = ( - api::tools::raw_number(luhn.grouped), - api::tools::raw_number(luhn.completed), - ); + let (number, completed) = + (api::tools::raw_number(luhn.grouped), api::tools::raw_number(luhn.completed)); let rows = [ ResultRow::new(&names.3, luhn.grouped).raw(&number), ResultRow::new(&names.4, luhn.completed).raw(&completed), @@ -222,14 +192,7 @@ fn iban_key(iban: &Iban<'_>, language: Language) -> String { /// What a valid IBAN holds, each by its name. fn iban_parts(verdict: &IbanVerdict, language: Language) -> Vec<(String, String)> { use keys::tools::checks as words; - let IbanVerdict::Valid { - bban, - bank, - branch, - account, - rib_key, - } = verdict - else { + let IbanVerdict::Valid { bban, bank, branch, account, rib_key } = verdict else { return Vec::new(); }; let tr = |key| i18n::translate(language, key, &[]); @@ -269,20 +232,12 @@ fn iban_card(ui: &mut Ui, iban: &Iban<'_>, language: Language) { let country = format!("{country} ({})", iban.country); let compact = api::tools::raw_number(iban.printed); let parts = iban_parts(iban.verdict, language); - let names = ( - tr(words::LENGTH), - tr(words::KEY), - tr(words::COUNTRY), - tr(words::kinds::IBAN), - tr(words::CORRECTED), - ); + let names = + (tr(words::LENGTH), tr(words::KEY), tr(words::COUNTRY), tr(words::kinds::IBAN), tr(words::CORRECTED)); card(ui, "checks-result", |ui| { head(ui, &tr(words::titles::IBAN), valid, reason, language); group_title(ui, &tr(words::CHECKS_TITLE)); - let rows = [ - ResultRow::new(&names.0, &length).reading(), - ResultRow::new(&names.1, &key).reading(), - ]; + let rows = [ResultRow::new(&names.0, &length).reading(), ResultRow::new(&names.1, &key).reading()]; result_rows(ui, &rows, language); group_title(ui, &tr(words::CONTENT)); let mut rows = vec![ResultRow::new(&names.2, &country).reading()]; @@ -303,16 +258,12 @@ fn iban_card(ui: &mut Ui, iban: &Iban<'_>, language: Language) { fn number_list(ui: &mut Ui, numbers: &[DrawnNumber], language: Language) { use keys::tools::checks as words; let count = u32::try_from(numbers.len()).unwrap_or(u32::MAX); - let counted = Message::new(words::GENERATED) - .with("count", count) - .text(language); + let counted = Message::new(words::GENERATED).with("count", count).text(language); let all: Vec<&str> = numbers.iter().map(|it| it.raw.as_str()).collect(); let all = all.join("\n"); section_head(ui, &counted, |ui| { let name = i18n::translate(language, words::GENERATED_ALL, &[]); - CopyValue::new(&all, &name, language) - .label(keys::tools::COPY_ALL) - .show(ui); + CopyValue::new(&all, &name, language).label(keys::tools::COPY_ALL).show(ui); }); let names: Vec = (1..=numbers.len()).map(|at| at.to_string()).collect(); card(ui, "checks-numbers", |ui| { @@ -335,9 +286,9 @@ fn refusal(answer: &NumbersAnswer, language: Language) -> String { }; Message::new(key).with("at", *at).text(language) } - NumbersAnswer::TooLong { digits } => Message::new(words::TOO_LONG) - .with("count", *digits) - .text(language), + NumbersAnswer::TooLong { digits } => { + Message::new(words::TOO_LONG).with("count", *digits).text(language) + } NumbersAnswer::Impossible => i18n::translate(language, words::IMPOSSIBLE, &[]), NumbersAnswer::Drawn(_) => String::new(), } @@ -370,10 +321,7 @@ impl ChecksTool { let language = drawn.language; self.intro(ui, language); self.answer_of(ui, language); - hint( - ui, - &i18n::translate(language, keys::tools::checks::FOOTNOTE, &[]), - ); + hint(ui, &i18n::translate(language, keys::tools::checks::FOOTNOTE, &[])); } fn numbers_request(&self) -> Option { @@ -385,10 +333,7 @@ impl ChecksTool { length: self.length.trim().parse().ok()?, count, }, - CheckKind::Iban => NumbersRequest::Iban { - country: self.country, - count, - }, + CheckKind::Iban => NumbersRequest::Iban { country: self.country, count }, }; Some((request, self.draw)) } @@ -399,10 +344,7 @@ impl ChecksTool { let tr = |key| i18n::translate(language, key, &[]); section_title(ui, &tr(words::GENERATE_TITLE)); hint(ui, &tr(words::GENERATE_INTRO)); - let options = [ - (CheckKind::Luhn, tr(words::kinds::LUHN)), - (CheckKind::Iban, tr(words::kinds::IBAN)), - ]; + let options = [(CheckKind::Luhn, tr(words::kinds::LUHN)), (CheckKind::Iban, tr(words::kinds::IBAN))]; let options = options.each_ref().map(|(id, name)| (*id, name.as_str())); Segmented::new(&options, "checks-generate-kind").show(ui, &mut self.drawn_kind); match self.drawn_kind { @@ -458,8 +400,7 @@ impl ChecksTool { (it, format!("{name} ({code})")) }) .collect(); - let options: Vec<(Country, &str)> = - names.iter().map(|(id, it)| (*id, it.as_str())).collect(); + let options: Vec<(Country, &str)> = names.iter().map(|(id, it)| (*id, it.as_str())).collect(); let name = i18n::translate(language, keys::tools::checks::COUNTRY, &[]); line(ui, |ui| { label(ui, &name); @@ -484,24 +425,14 @@ impl ChecksTool { use keys::tools::checks as words; match self.answer.value() { Some(CheckAnswer::Unreadable { at }) => { - let said = Message::new(words::UNREADABLE) - .with("at", *at) - .text(language); + let said = Message::new(words::UNREADABLE).with("at", *at).text(language); problem(ui, &said, "checks-problem"); } Some(CheckAnswer::TooShort) => { let said = i18n::translate(language, words::TOO_SHORT, &[]); problem(ui, &said, "checks-problem"); } - Some(CheckAnswer::Luhn { - grouped, - length, - valid, - expected_last, - completed, - network, - .. - }) => { + Some(CheckAnswer::Luhn { grouped, length, valid, expected_last, completed, network, .. }) => { let luhn = Luhn { grouped, length: *length, @@ -512,21 +443,8 @@ impl ChecksTool { }; luhn_card(ui, &luhn, language); } - Some(CheckAnswer::Iban { - country, - printed, - check_digits, - length, - verdict, - .. - }) => { - let iban = Iban { - country, - printed, - check_digits, - length: *length, - verdict, - }; + Some(CheckAnswer::Iban { country, printed, check_digits, length, verdict, .. }) => { + let iban = Iban { country, printed, check_digits, length: *length, verdict }; iban_card(ui, &iban, language); } None => { @@ -538,15 +456,12 @@ impl ChecksTool { impl Tool for ChecksTool { fn update(&mut self, turn: &mut Turn<'_>) { - let request = (!self.text.trim().is_empty()).then(|| CheckRequest { - text: self.text.clone(), - kind: self.kind, - }); + let request = + (!self.text.trim().is_empty()).then(|| CheckRequest { text: self.text.clone(), kind: self.kind }); self.answer.update(turn, request, api::tools::check_digits); let request = self.numbers_request(); - self.numbers.update(turn, request, |backend, (asked, _)| { - api::tools::draw_numbers(backend, asked) - }); + self.numbers + .update(turn, request, |backend, (asked, _)| api::tools::draw_numbers(backend, asked)); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { diff --git a/crates/ui/src/tools/catalogue/cidr.rs b/crates/ui/src/tools/catalogue/cidr.rs index 905a745d2..e910c40bc 100644 --- a/crates/ui/src/tools/catalogue/cidr.rs +++ b/crates/ui/src/tools/catalogue/cidr.rs @@ -7,9 +7,7 @@ use engine::tools::cidr::forms::ReverseDns; use engine::tools::cidr::masks::MaskRow; use engine::tools::cidr::plan::{CidrPlan, PlanLine}; use engine::tools::cidr::summary::{CidrSummary, FamilySummary}; -use engine::tools::cidr::{ - CidrAnswer, CidrBlock, CidrMembership, CidrRequest, CidrSplit, IpFamily, -}; +use engine::tools::cidr::{CidrAnswer, CidrBlock, CidrMembership, CidrRequest, CidrSplit, IpFamily}; use i18n::{Language, Message, keys}; use serde_json::json; @@ -17,8 +15,8 @@ use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - ResultRow, TextColumn, card, columns, hint, named, paragraph, problem, result_rows, - section_head, section_title, text_area, text_table, + ResultRow, TextColumn, card, columns, hint, named, paragraph, problem, result_rows, section_head, + section_title, text_area, text_table, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, Segmented, TextField, address}; @@ -107,9 +105,7 @@ fn reverse_text(reverse: &ReverseDns, language: Language) -> (String, bool) { use keys::tools::cidr::reverse as words; match reverse { ReverseDns::Record { name } => (name.clone(), true), - ReverseDns::Zones { - first, count: 1, .. - } => (first.clone(), true), + ReverseDns::Zones { first, count: 1, .. } => (first.clone(), true), ReverseDns::Zones { first, last, count } => { let text = Message::new(words::ZONES) .with("count", *count) @@ -119,9 +115,7 @@ fn reverse_text(reverse: &ReverseDns, language: Language) -> (String, bool) { (text, false) } ReverseDns::Classless { zone } => { - let text = Message::new(words::CLASSLESS) - .with("zone", zone.as_str()) - .text(language); + let text = Message::new(words::CLASSLESS).with("zone", zone.as_str()).text(language); (text, false) } } @@ -137,11 +131,7 @@ fn written_card(ui: &mut Ui, block: &CidrBlock, language: Language) { let rows = [ ResultRow::new(&names.0, &block.forms.integer), ResultRow::new(&names.1, &block.forms.expanded), - if pasted { - reverse_row - } else { - reverse_row.reading() - }, + if pasted { reverse_row } else { reverse_row.reading() }, ]; result_rows(ui, &rows, language); }); @@ -161,10 +151,7 @@ fn binary_card(ui: &mut Ui, block: &CidrBlock, language: Language) { job.wrap.max_width = ui.available_width(); let shown = ui.add(egui::Label::new(job)); address(ui, &shown, "cidr-binary"); - let path = format!( - "tools.cidr.kinds.{}", - json!(block.kind).as_str().unwrap_or_default() - ); + let path = format!("tools.cidr.kinds.{}", json!(block.kind).as_str().unwrap_or_default()); let words = i18n::Key::find(&path).map_or_else(String::new, |key| { Message::new(key) .with("range", block.range.as_deref().unwrap_or_default()) @@ -212,24 +199,13 @@ fn plan_table(ui: &mut Ui, plan: &CidrPlan, language: Language) { let tr = |key| i18n::translate(language, key, &[]); let unnamed = tr(words::UNNAMED); let name_of = |name: &str| { - if name.is_empty() { - unnamed.clone() - } else { - name.to_owned() - } + if name.is_empty() { unnamed.clone() } else { name.to_owned() } }; let rows: Vec> = plan .lines .iter() .map(|line| match line { - PlanLine::Placed { - name, - hosts, - cidr, - usable, - first, - last, - } => vec![ + PlanLine::Placed { name, hosts, cidr, usable, first, last } => vec![ name_of(name), grouped(hosts, language), cidr.clone(), @@ -244,9 +220,7 @@ fn plan_table(ui: &mut Ui, plan: &CidrPlan, language: Language) { String::new(), ], PlanLine::Unreadable { text } => vec![ - Message::new(words::UNREADABLE) - .with("text", text.as_str()) - .text(language), + Message::new(words::UNREADABLE).with("text", text.as_str()).text(language), String::new(), String::new(), String::new(), @@ -284,9 +258,8 @@ fn family_card(ui: &mut Ui, family: &FamilySummary, language: Language) { }; let count = u32::try_from(family.blocks.len()).unwrap_or(u32::MAX); let path = format!("tools.cidr.list.blocks.{}", family_id(family.family)); - let title = i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key).with("count", count).text(language) - }); + let title = i18n::Key::find(&path) + .map_or_else(String::new, |key| Message::new(key).with("count", count).text(language)); let blocks = family.blocks.join("\n"); let supernet = tr(words::SUPERNET); card(ui, "cidr-summary", |ui| { @@ -343,9 +316,7 @@ impl CidrTool { return; }; if block.normalised { - let words = Message::new(words::NORMALISED) - .with("cidr", block.cidr.as_str()) - .text(language); + let words = Message::new(words::NORMALISED).with("cidr", block.cidr.as_str()).text(language); let said = hint(ui, &words); address(ui, &said, "cidr-normalised"); } @@ -370,9 +341,7 @@ impl CidrTool { .show(ui); match self.answer.value().map(|it| &it.membership) { Some(CidrMembership::Inside { host }) => { - let words = Message::new(words::INSIDE) - .with("host", grouped(host, language)) - .text(language); + let words = Message::new(words::INSIDE).with("host", grouped(host, language)).text(language); let said = paragraph(ui, &words, (font::BODY, 500.0), p.green); address(ui, &said, "cidr-membership"); } @@ -424,21 +393,14 @@ impl CidrTool { let Some(block) = &answer.block else { return; }; - section_title( - ui, - &i18n::translate(language, keys::tools::cidr::SPLIT_TITLE, &[]), - ); + section_title(ui, &i18n::translate(language, keys::tools::cidr::SPLIT_TITLE, &[])); let mut chosen = None; ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = Vec2::splat(gap::SNUG); for prefix in &answer.split_choices { let words = format!("/{prefix}"); let id = format!("cidr-split-choice-{prefix}"); - if Button::new(&words, &id) - .armed(*prefix == split.prefix) - .show(ui) - .clicked() - { + if Button::new(&words, &id).armed(*prefix == split.prefix).show(ui).clicked() { chosen = Some(*prefix); } } @@ -489,10 +451,7 @@ impl CidrTool { cells }) .collect(); - let lit = answer - .masks - .iter() - .position(|row| row.prefix == block.prefix); + let lit = answer.masks.iter().position(|row| row.prefix == block.prefix); // Four numbers and two counts do not hold in a column: the table scrolls in its own. let picked = egui::ScrollArea::horizontal() .id_salt("cidr-masks-scroll") @@ -501,10 +460,7 @@ impl CidrTool { text_table(ui, "cidr-masks", &headers, &rows, lit) }) .inner; - if let Some(prefix) = picked - .and_then(|at| answer.masks.get(at)) - .map(|it| it.prefix) - { + if let Some(prefix) = picked.and_then(|at| answer.masks.get(at)).map(|it| it.prefix) { // On the address as it was typed, so going back finds the same block. self.network = format!("{}/{prefix}", block.typed); self.split = None; @@ -548,13 +504,7 @@ impl CidrTool { .into_iter() .flat_map(|plan| &plan.lines) .filter_map(|line| match line { - PlanLine::Placed { - name, - cidr, - first, - last, - .. - } => { + PlanLine::Placed { name, cidr, first, last, .. } => { let name = if name.is_empty() { "—" } else { name }; Some(format!("{name} : {cidr} ({first} – {last})")) } @@ -596,8 +546,7 @@ impl Tool for CidrTool { plan: self.plan.clone(), list: self.list.clone(), }; - self.answer - .update(turn, Some(request), api::tools::describe_cidr); + self.answer.update(turn, Some(request), api::tools::describe_cidr); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -613,16 +562,8 @@ impl Tool for CidrTool { let family = family_id(block.family); let name = |id: &str| say(language, &format!("tools.cidr.rows.{id}.{family}")); let mut lines = vec![block.cidr.clone()]; - lines.extend( - fact_rows(block) - .iter() - .map(|(id, value)| format!("{} : {value}", name(id))), - ); - lines.push(format!( - "{} : {}", - name("usable"), - hosts_of(block, language) - )); + lines.extend(fact_rows(block).iter().map(|(id, value)| format!("{} : {value}", name(id)))); + lines.push(format!("{} : {}", name("usable"), hosts_of(block, language))); lines.extend(self.plan_lines(language)); lines.extend(self.summary_lines(language)); Some(ToolResult { diff --git a/crates/ui/src/tools/catalogue/colour.rs b/crates/ui/src/tools/catalogue/colour.rs index 47a6cee55..436af29fb 100644 --- a/crates/ui/src/tools/catalogue/colour.rs +++ b/crates/ui/src/tools/catalogue/colour.rs @@ -5,8 +5,7 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{Color32, CornerRadius, Response, Role, Sense, Ui, Vec2, WidgetInfo}; use engine::notes::language::Language as NoteLanguage; use engine::tools::colour::{ - ColourAnswer, ColourReading, ColourRequest, Contrast, ContrastFix, Notations, TextSizes, - WcagLevel, + ColourAnswer, ColourReading, ColourRequest, Contrast, ContrastFix, Notations, TextSizes, WcagLevel, }; use i18n::{Language, Message, keys}; @@ -42,22 +41,14 @@ fn swatch_of(text: &str) -> Option { let digits = text.strip_prefix('#')?; let byte = |at: usize| u8::from_str_radix(digits.get(at..at + 2)?, 16).ok(); let alpha = if digits.len() >= 8 { byte(6)? } else { 255 }; - Some(Color32::from_rgba_unmultiplied( - byte(0)?, - byte(2)?, - byte(4)?, - alpha, - )) + Some(Color32::from_rgba_unmultiplied(byte(0)?, byte(2)?, byte(4)?, alpha)) } fn read(reading: &ColourReading) -> Option<(&Notations, &str, bool)> { match reading { - ColourReading::Read { - notations, - swatch, - out_of_gamut, - .. - } => Some((notations, swatch, *out_of_gamut)), + ColourReading::Read { notations, swatch, out_of_gamut, .. } => { + Some((notations, swatch, *out_of_gamut)) + } _ => None, } } @@ -86,8 +77,7 @@ fn pill(ui: &mut Ui, words: &str, passes: bool) -> Response { let (rect, response) = ui.allocate_exact_size(shown.size() + padding * 2.0, Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); let corner = CornerRadius::same(u8::MAX); - ui.painter() - .rect_filled(rect, corner, ink.gamma_multiply(0.15)); + ui.painter().rect_filled(rect, corner, ink.gamma_multiply(0.15)); shown.paint(ui, rect.min + padding, p.text_1); response } @@ -202,8 +192,7 @@ impl ColourTool { let Some(contrast) = answer.contrast.clone() else { return; }; - let paint = - |reading: &ColourReading| read(reading).and_then(|(_, swatch, _)| swatch_of(swatch)); + let paint = |reading: &ColourReading| read(reading).and_then(|(_, swatch, _)| swatch_of(swatch)); if let (Some(text), Some(background)) = (paint(&answer.colour), paint(&answer.against)) { sample_box(ui, (text, background), language); } @@ -226,13 +215,7 @@ impl ColourTool { ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let placeholder = tr(words::PLACEHOLDER); - field( - ui, - &mut self.colour, - &tr(words::TEXT), - "colour-text", - &placeholder, - ); + field(ui, &mut self.colour, &tr(words::TEXT), "colour-text", &placeholder); ui.vertical(|ui| { ui.add_space(gap::PAGE); let name = tr(words::SWAP); @@ -277,11 +260,7 @@ impl ColourTool { WcagLevel::Aa => words::fix::AA, WcagLevel::Aaa => words::fix::AAA, }; - if Button::new(&tr(key), "colour-fix") - .kind(Kind::Outline) - .show(ui) - .clicked() - { + if Button::new(&tr(key), "colour-fix").kind(Kind::Outline).show(ui).clicked() { self.colour.clone_from(hex); } } @@ -300,12 +279,8 @@ impl ColourTool { impl Tool for ColourTool { fn update(&mut self, turn: &mut Turn<'_>) { - let request = ColourRequest { - colour: self.colour.clone(), - against: self.against.clone(), - }; - self.answer - .update(turn, Some(request), api::tools::describe_colour); + let request = ColourRequest { colour: self.colour.clone(), against: self.against.clone() }; + self.answer.update(turn, Some(request), api::tools::describe_colour); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { diff --git a/crates/ui/src/tools/catalogue/convert.rs b/crates/ui/src/tools/catalogue/convert.rs index f516e9e6b..31a374b83 100644 --- a/crates/ui/src/tools/catalogue/convert.rs +++ b/crates/ui/src/tools/catalogue/convert.rs @@ -11,8 +11,7 @@ use crate::theme::icons::Icon; use crate::tools::live::{Live, Turn}; use crate::tools::ui::note_picker::PickedNote; use crate::tools::ui::{ - CopyValue, code_output, columns, hint, named, note_import, notice, problem, section_head, - text_area, + CopyValue, code_output, columns, hint, named, note_import, notice, problem, section_head, text_area, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{IconButton, Segmented, tooltip}; @@ -58,10 +57,7 @@ pub(super) fn make() -> Box { } fn name_of(format: DataFormat) -> &'static str { - FORMATS - .iter() - .find(|(it, _)| *it == format) - .map_or("", |(_, name)| name) + FORMATS.iter().find(|(it, _)| *it == format).map_or("", |(_, name)| name) } /// What a note keeps the result as, so it is highlighted in its own language. @@ -86,9 +82,7 @@ fn format_of(language: NoteLanguage) -> Option { /// A format is never converted to itself: the one the other side holds is not taken. fn side(ui: &mut Ui, chosen: &mut DataFormat, other: DataFormat, author_id: &str) { - Segmented::new(&FORMATS, author_id) - .taken(other) - .show(ui, chosen); + Segmented::new(&FORMATS, author_id).taken(other).show(ui, chosen); } impl ConvertTool { @@ -120,13 +114,7 @@ impl ConvertTool { }); let name = tr(keys::tools::convert::INPUT_LABEL); let placeholder = named(language, "tools.convert.placeholders", &json!(self.from)); - text_area( - ui, - &mut self.text, - (&name, "convert-input"), - &placeholder, - 16, - ); + text_area(ui, &mut self.text, (&name, "convert-input"), &placeholder, 16); note_import(ui, drawn, "text"); if let (Some(ConvertAnswer::Unreadable { line, column }), Some(asked)) = (self.answer.value(), self.answer.answered()) @@ -189,9 +177,7 @@ impl ConvertTool { return; } let count = u32::try_from(dropped.len()).unwrap_or(u32::MAX); - let head = Message::new(keys::tools::convert::DROPPED) - .with("count", count) - .text(language); + let head = Message::new(keys::tools::convert::DROPPED).with("count", count).text(language); let mut paths = dropped[..dropped.len().min(NAMED)].join(", "); if dropped.len() > NAMED { paths.push_str(", …"); diff --git a/crates/ui/src/tools/catalogue/cron.rs b/crates/ui/src/tools/catalogue/cron.rs index 98ae062c5..36d3b6bc5 100644 --- a/crates/ui/src/tools/catalogue/cron.rs +++ b/crates/ui/src/tools/catalogue/cron.rs @@ -6,9 +6,7 @@ use crate::theme::tokens::{font, gap, radius}; use chrono::{DateTime, NaiveDate, TimeDelta, Utc}; use egui::{CornerRadius, FontFamily, Pos2, Role, Sense, Stroke, Ui, Vec2, WidgetInfo}; use engine::notes::language::Language as NoteLanguage; -use engine::tools::cron::{ - CronAnswer, CronCheck, CronRequest, CronWindow, FieldReading, Run, WindowEnd, -}; +use engine::tools::cron::{CronAnswer, CronCheck, CronRequest, CronWindow, FieldReading, Run, WindowEnd}; use engine::tools::zones::ZoneEntry; use i18n::{Language, Message, keys}; use serde_json::json; @@ -60,11 +58,7 @@ fn shortcut_window(shortcut: &str, now: &Run) -> (String, String) { (at(saturday, "00:00"), at(saturday + 2, "00:00")) } _ => { - let friday = if weekday <= 5 { - 5 - weekday - } else { - 12 - weekday - }; + let friday = if weekday <= 5 { 5 - weekday } else { 12 - weekday }; (at(friday, "12:00"), at(friday, "18:00")) } } @@ -85,27 +79,16 @@ fn run_row(ui: &mut Ui, run: &Run, now: DateTime, language: Language) { let at = format!("{} {}", run.date, run.time); response.widget_info(|| WidgetInfo::labeled(Role::Row, true, &at)); address(ui, &response, "cron-run"); - ui.painter() - .hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); #[expect(clippy::cast_possible_truncation, reason = "milliseconds of a date")] let relative = DateTime::from_timestamp_millis(run.epoch_milliseconds as i64) .map(|it| i18n::time::span(it, now).text(language)); let offset = format!("UTC{}", run.offset); let cells = [ - ( - 0.0, - day_name(run.weekday, language), - FontFamily::Proportional, - p.text_2, - ), + (0.0, day_name(run.weekday, language), FontFamily::Proportional, p.text_2), (0.16, at.clone(), FontFamily::Monospace, p.text_0), (0.5, offset, FontFamily::Monospace, p.text_2), - ( - 0.68, - relative.unwrap_or_default(), - FontFamily::Proportional, - p.text_2, - ), + (0.68, relative.unwrap_or_default(), FontFamily::Proportional, p.text_2), ]; for (share, words, family, ink) in cells { let galley = widgets::text(ui, &words, font::LABEL, 400.0, family, ink); @@ -147,9 +130,7 @@ fn field_chips(ui: &mut Ui, fields: &[FieldReading], language: Language) { .font(egui::FontId::monospace(font::READING)) .color(p.text_0); ui.label(code); - let under = egui::RichText::new(&name) - .size(font::CAPTION) - .color(p.text_2); + let under = egui::RichText::new(&name).size(font::CAPTION).color(p.text_2); ui.label(under); }); }); @@ -160,10 +141,7 @@ fn field_chips(ui: &mut Ui, fields: &[FieldReading], language: Language) { fn named_field(field: &FieldReading, language: Language) -> String { let id = json!(field.field); - say( - language, - &format!("tools.cron.fields.{}.name", id.as_str().unwrap_or_default()), - ) + say(language, &format!("tools.cron.fields.{}.name", id.as_str().unwrap_or_default())) } fn window_problem(window: &CronWindow, language: Language) -> Option { @@ -172,17 +150,13 @@ fn window_problem(window: &CronWindow, language: Language) -> Option { Some(match window { CronWindow::Unreadable { end, at } => { let path = format!("tools.cron.windowProblems.unreadable.{}", end_id(end)); - i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key).with("at", *at).text(language) - }) + i18n::Key::find(&path) + .map_or_else(String::new, |key| Message::new(key).with("at", *at).text(language)) } - CronWindow::Skipped { end } => say( - language, - &format!("tools.cron.windowProblems.skipped.{}", end_id(end)), - ), - CronWindow::TooLong { years } => Message::new(words::TOO_LONG) - .with("years", *years) - .text(language), + CronWindow::Skipped { end } => { + say(language, &format!("tools.cron.windowProblems.skipped.{}", end_id(end))) + } + CronWindow::TooLong { years } => Message::new(words::TOO_LONG).with("years", *years).text(language), CronWindow::Backwards => i18n::translate(language, words::BACKWARDS, &[]), CronWindow::Counted { .. } => return None, }) @@ -203,14 +177,7 @@ fn zone_entry(ui: &mut Ui, entry: &ZoneEntry) -> egui::Response { let rect = response.rect; let fill = towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)); ui.painter().rect_filled(rect, corner, fill); - let name = widgets::text( - ui, - &entry.zone, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let name = widgets::text(ui, &entry.zone, font::BODY, 400.0, FontFamily::Proportional, p.text_0); let at = Pos2::new(rect.left() + 10.0, rect.center().y - name.size().y / 2.0); ui.painter().galley(at, name, p.text_0); response @@ -235,12 +202,7 @@ impl CronTool { let tr = |key| i18n::translate(language, key, &[]); let p = palette(ui.ctx()); match self.answer.value() { - Some(CronAnswer::Read { - expanded, - fields, - both_days, - .. - }) => { + Some(CronAnswer::Read { expanded, fields, both_days, .. }) => { if let Some(expression) = expanded { let words = Message::new(keys::tools::cron::EXPANDED) .with("expression", expression.as_str()) @@ -261,35 +223,21 @@ impl CronTool { let said = hint(ui, &tr(keys::tools::cron::REBOOT)); address(ui, &said, "cron-reboot"); } - Some(CronAnswer::Refused { - field, - token, - at, - problem: reason, - }) => { + Some(CronAnswer::Refused { field, token, at, problem: reason }) => { let field_id = json!(field); let field_id = field_id.as_str().unwrap_or_default(); let range = say(language, &format!("tools.cron.fields.{field_id}.range")); let reason_id = json!(reason); - let path = format!( - "tools.cron.problems.{}", - reason_id.as_str().unwrap_or_default() - ); + let path = format!("tools.cron.problems.{}", reason_id.as_str().unwrap_or_default()); let message = i18n::Key::find(&path).map_or_else(String::new, |key| { Message::new(key) .with("token", token.as_str()) .with("range", range) .text(language) }); - let place = Message::new(keys::tools::cron::REFUSED_AT) - .with("at", *at) - .text(language); + let place = Message::new(keys::tools::cron::REFUSED_AT).with("at", *at).text(language); let name = say(language, &format!("tools.cron.fields.{field_id}.name")); - let head = if name.is_empty() { - place - } else { - format!("{name} · {place}") - }; + let head = if name.is_empty() { place } else { format!("{name} · {place}") }; problem(ui, &format!("{head} {message}"), "cron-problem"); } Some(CronAnswer::UnknownZone { zone }) => { @@ -308,10 +256,7 @@ impl CronTool { section_title(ui, &name); let shown = match self.answer.value() { Some(CronAnswer::Read { zone, .. }) => zone.clone(), - _ => self - .zone - .clone() - .unwrap_or_else(|| tr(keys::tools::cron::ZONE_LOCAL)), + _ => self.zone.clone().unwrap_or_else(|| tr(keys::tools::cron::ZONE_LOCAL)), }; let mut back = false; ui.horizontal(|ui| { @@ -354,12 +299,7 @@ impl CronTool { ui.spacing_mut().item_spacing.x = gap::INSET; let half = (ui.available_width() - 10.0) / 2.0; for (value, key, hint_key, id) in [ - ( - &mut self.from, - keys::tools::cron::FROM, - keys::tools::cron::FROM_PLACEHOLDER, - "cron-from", - ), + (&mut self.from, keys::tools::cron::FROM, keys::tools::cron::FROM_PLACEHOLDER, "cron-from"), ( &mut self.until, keys::tools::cron::UNTIL, @@ -372,9 +312,7 @@ impl CronTool { ui.set_width(half); let name = tr(key); label(ui, &name); - TextField::new(value, &name, id) - .hint(&tr(hint_key)) - .show(ui); + TextField::new(value, &name, id).hint(&tr(hint_key)).show(ui); }); }); } @@ -422,13 +360,9 @@ impl CronTool { address(ui, &said, "cron-window-problem"); } let counted = match window { - Some(CronWindow::Counted { - from, - until, - total, - first, - last, - }) => Some((from, until, *total, first, last)), + Some(CronWindow::Counted { from, until, total, first, last }) => { + Some((from, until, *total, first, last)) + } _ => None, }; if let Some((from, until, total, _, _)) = counted { @@ -454,11 +388,7 @@ impl CronTool { let (first, last, between) = match counted { Some((_, _, total, first, last)) => { let listed = u32::try_from(first.len() + last.len()).unwrap_or(total); - let between = if last.is_empty() { - 0 - } else { - total.saturating_sub(listed) - }; + let between = if last.is_empty() { 0 } else { total.saturating_sub(listed) }; (first.as_slice(), last.as_slice(), between) } None => (runs.as_slice(), [].as_slice(), 0), @@ -492,21 +422,13 @@ impl CronTool { fn verdict(&self, ui: &mut Ui, language: Language) { let tr = |key| i18n::translate(language, key, &[]); - let Some(CronAnswer::Read { - check: Some(check), .. - }) = self.answer.value() - else { + let Some(CronAnswer::Read { check: Some(check), .. }) = self.answer.value() else { return; }; let p = palette(ui.ctx()); let at_message = |key, at: &str| Message::new(key).with("at", at).text(language); match check { - CronCheck::Checked { - matches, - at, - before, - after, - } => { + CronCheck::Checked { matches, at, before, after } => { let (key, ink) = if *matches { (keys::tools::cron::MATCHES, p.green) } else { @@ -531,9 +453,7 @@ impl CronTool { } } CronCheck::Unreadable { at } => { - let words = Message::new(keys::tools::cron::CHECK_UNREADABLE) - .with("at", *at) - .text(language); + let words = Message::new(keys::tools::cron::CHECK_UNREADABLE).with("at", *at).text(language); let said = hint(ui, &words); address(ui, &said, "cron-verdict"); } @@ -556,8 +476,7 @@ impl Tool for CronTool { }); self.answer.update(turn, request, api::tools::describe_cron); let query = (!self.query.trim().is_empty()).then(|| self.query.clone()); - self.found - .update(turn, query, api::tools::search_time_zones); + self.found.update(turn, query, api::tools::search_time_zones); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -569,17 +488,11 @@ impl Tool for CronTool { } fn result(&self, language: Language) -> Option { - let Some(CronAnswer::Read { - fields, zone, runs, .. - }) = self.answer.value() - else { + let Some(CronAnswer::Read { fields, zone, runs, .. }) = self.answer.value() else { return None; }; let expression = self.answer.answered()?.expression.trim().to_owned(); - let mut lines = vec![ - expression.clone(), - format!("{}.", sentence::of(fields, language)), - ]; + let mut lines = vec![expression.clone(), format!("{}.", sentence::of(fields, language))]; if !runs.is_empty() { lines.push(String::new()); lines.push( diff --git a/crates/ui/src/tools/catalogue/cron/sentence.rs b/crates/ui/src/tools/catalogue/cron/sentence.rs index 1d6644bd1..03b2e12d8 100644 --- a/crates/ui/src/tools/catalogue/cron/sentence.rs +++ b/crates/ui/src/tools/catalogue/cron/sentence.rs @@ -30,9 +30,7 @@ impl Speech { fn format(&self, field: CronField, value: u32) -> String { match field { CronField::Hour => self.say(&format!("{SAY}.hourValue"), vec![("hour", value.into())]), - CronField::DayOfMonth => { - self.say(&format!("{SAY}.dayValue"), vec![("day", value.into())]) - } + CronField::DayOfMonth => self.say(&format!("{SAY}.dayValue"), vec![("day", value.into())]), CronField::Month => self.say(&format!("tools.cron.months.{value}"), vec![]), CronField::DayOfWeek => self.say(&format!("tools.cron.days.{}", value % 7), vec![]), CronField::Second | CronField::Minute => value.to_string(), @@ -66,14 +64,9 @@ impl Speech { Some(match piece { Piece::Range { from, to } => self.say( &format!("{SAY}.{id}.range"), - vec![ - ("from", self.format(field, *from).into()), - ("to", self.format(field, *to).into()), - ], + vec![("from", self.format(field, *from).into()), ("to", self.format(field, *to).into())], ), - Piece::Step { step } => { - self.say(&format!("{SAY}.{id}.step"), vec![("step", (*step).into())]) - } + Piece::Step { step } => self.say(&format!("{SAY}.{id}.step"), vec![("step", (*step).into())]), Piece::SteppedRange { step, from, to } => self.say( &format!("{SAY}.{id}.steppedRange"), vec![ @@ -94,10 +87,7 @@ impl Speech { Piece::Nth { weekday, nth } => self.say( &format!("{SAY}.dayOfWeek.nth"), vec![ - ( - "nth", - self.say(&format!("tools.cron.nths.{nth}"), vec![]).into(), - ), + ("nth", self.say(&format!("tools.cron.nths.{nth}"), vec![]).into()), ("day", self.format(CronField::DayOfWeek, *weekday).into()), ], ), @@ -130,19 +120,14 @@ impl Speech { { let mut times: Vec = hour_values .iter() - .flat_map(|hour| { - minute_values - .iter() - .map(move |it| format!("{hour:02}:{it:02}")) - }) + .flat_map(|hour| minute_values.iter().map(move |it| format!("{hour:02}:{it:02}"))) .collect(); times.sort(); let count = u32::try_from(times.len()).unwrap_or(u32::MAX); let list = self.join(×); - return vec![self.say( - &format!("{SAY}.at"), - vec![("count", count.into()), ("list", list.into())], - )]; + return vec![ + self.say(&format!("{SAY}.at"), vec![("count", count.into()), ("list", list.into())]), + ]; } if minute_values.as_deref() == Some(&[0]) && hour_values.is_none() { return vec![if is_every(hours) { @@ -175,10 +160,7 @@ fn id_of(field: CronField) -> &'static str { } fn pieces_of(fields: &[FieldReading], field: CronField) -> Option<&[Piece]> { - fields - .iter() - .find(|it| it.field == field) - .map(|it| it.pieces.as_slice()) + fields.iter().find(|it| it.field == field).map(|it| it.pieces.as_slice()) } fn is_every(pieces: Option<&[Piece]>) -> bool { @@ -202,11 +184,7 @@ fn values_of(pieces: &[Piece]) -> Option> { pub(super) fn of(fields: &[FieldReading], language: Language) -> String { let speech = Speech { language }; let mut clauses = speech.time_clauses(fields); - for field in [ - CronField::DayOfMonth, - CronField::DayOfWeek, - CronField::Month, - ] { + for field in [CronField::DayOfMonth, CronField::DayOfWeek, CronField::Month] { let pieces = pieces_of(fields, field); if !is_every(pieces) { clauses.push(speech.clause(field, pieces.unwrap_or_default())); @@ -214,9 +192,9 @@ pub(super) fn of(fields: &[FieldReading], language: Language) -> String { } let sentence = clauses.join(", "); let mut letters = sentence.chars(); - letters.next().map_or_else(String::new, |first| { - first.to_uppercase().chain(letters).collect() - }) + letters + .next() + .map_or_else(String::new, |first| first.to_uppercase().chain(letters).collect()) } #[cfg(test)] @@ -256,9 +234,6 @@ mod tests { fn every_minute_says_so_with_a_capital() { let words = said("* * * * *"); - assert!( - words.chars().next().is_some_and(char::is_uppercase), - "{words}" - ); + assert!(words.chars().next().is_some_and(char::is_uppercase), "{words}"); } } diff --git a/crates/ui/src/tools/catalogue/data_tests.rs b/crates/ui/src/tools/catalogue/data_tests.rs index 6b82b96d9..75936b6c5 100644 --- a/crates/ui/src/tools/catalogue/data_tests.rs +++ b/crates/ui/src/tools/catalogue/data_tests.rs @@ -11,9 +11,7 @@ use crate::notes::bench::{Bench, settle}; fn identity_drawn() -> Harness<'static, Bench> { let mut harness = opened("identity"); click(&mut harness, "tool-action-draw"); - waits_for(&mut harness, "a person is drawn", |harness| { - has(harness, "identity-card") - }); + waits_for(&mut harness, "a person is drawn", |harness| has(harness, "identity-card")); harness } @@ -22,9 +20,7 @@ fn a_json_document_becomes_yaml_and_the_swap_brings_it_back() { let mut harness = opened("convert"); type_in(&mut harness, "convert-input", r#"{"service":"billing"}"#); - waits_for(&mut harness, "the document is converted", |harness| { - has(harness, "convert-output") - }); + waits_for(&mut harness, "the document is converted", |harness| has(harness, "convert-output")); assert!(value_of(&harness, "convert-output").contains("service: billing")); click(&mut harness, "convert-swap"); @@ -39,15 +35,11 @@ fn a_broken_document_says_where_and_a_null_is_named_when_toml_drops_it() { let mut harness = opened("convert"); type_in(&mut harness, "convert-input", "{"); - waits_for(&mut harness, "the place is said", |harness| { - has(harness, "convert-unreadable") - }); + waits_for(&mut harness, "the place is said", |harness| has(harness, "convert-unreadable")); click(&mut harness, "tool-clear"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the null is named", |harness| { - has(harness, "convert-dropped") - }); + waits_for(&mut harness, "the null is named", |harness| has(harness, "convert-dropped")); assert!(value_of(&harness, "convert-dropped").contains("telephone")); } @@ -56,15 +48,11 @@ fn a_pinned_seed_draws_the_same_documents_again() { let mut harness = opened("json-generator"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "documents are drawn", |harness| { - has(harness, "json-generator-output") - }); + waits_for(&mut harness, "documents are drawn", |harness| has(harness, "json-generator-output")); assert!(has(&harness, "json-generator-seed-used")); click(&mut harness, "json-generator-keep-seed"); - waits_for(&mut harness, "the seed is pinned", |harness| { - has(harness, "json-generator-seed-pinned") - }); + waits_for(&mut harness, "the seed is pinned", |harness| has(harness, "json-generator-seed-pinned")); let first = value_of(&harness, "json-generator-output"); click(&mut harness, "tool-action-draw"); settle(&mut harness); @@ -78,33 +66,22 @@ fn an_example_read_as_a_schema_offers_to_be_read_as_an_example() { click(&mut harness, "json-generator-source-0"); type_in(&mut harness, "json-generator-input", r#"{"name":"Ada"}"#); - waits_for(&mut harness, "the mistake is said", |harness| { - has(harness, "json-generator-as-example") - }); + waits_for(&mut harness, "the mistake is said", |harness| has(harness, "json-generator-as-example")); click(&mut harness, "json-generator-as-example"); - waits_for(&mut harness, "documents are drawn", |harness| { - has(harness, "json-generator-output") - }); + waits_for(&mut harness, "documents are drawn", |harness| has(harness, "json-generator-output")); } #[test] fn identifiers_are_drawn_and_one_pasted_is_read_back() { let mut harness = opened("identifiers"); - waits_for(&mut harness, "identifiers are drawn", |harness| { - has(harness, "identifiers-row") - }); + waits_for(&mut harness, "identifiers are drawn", |harness| has(harness, "identifiers-row")); let uuid = "0190a5f4-7e3b-7c1a-9f2e-3b4c5d6e7f80"; type_in(&mut harness, "identifiers-checked", uuid); - waits_for(&mut harness, "the identifier is read", |harness| { - has(harness, "identifiers-facts") - }); - assert!( - output_values(&harness).iter().any(|it| it.contains("2024")), - "a UUID v7 says its instant" - ); + waits_for(&mut harness, "the identifier is read", |harness| has(harness, "identifiers-facts")); + assert!(output_values(&harness).iter().any(|it| it.contains("2024")), "a UUID v7 says its instant"); } #[test] @@ -114,15 +91,11 @@ fn a_contrast_is_measured_and_its_fix_replaces_the_colour() { click(&mut harness, "tool-clear"); type_in(&mut harness, "colour-input", "#777777"); type_in(&mut harness, "colour-against", "#ffffff"); - waits_for(&mut harness, "the ratio is read", |harness| { - has(harness, "colour-ratio") - }); + waits_for(&mut harness, "the ratio is read", |harness| has(harness, "colour-ratio")); assert!(has(&harness, "colour-sample")); click(&mut harness, "colour-fix"); - waits_for(&mut harness, "the fix is taken", |harness| { - value_of(harness, "colour-input") != "#777777" - }); + waits_for(&mut harness, "the fix is taken", |harness| value_of(harness, "colour-input") != "#777777"); } #[test] @@ -135,9 +108,7 @@ fn a_word_that_is_no_colour_is_said_and_the_swap_trades_the_two() { click(&mut harness, "tool-clear"); type_in(&mut harness, "colour-input", "not a colour"); - waits_for(&mut harness, "the colour is refused", |harness| { - has(harness, "colour-invalid") - }); + waits_for(&mut harness, "the colour is refused", |harness| has(harness, "colour-invalid")); } #[test] @@ -145,9 +116,7 @@ fn a_code_is_drawn_and_a_url_without_its_scheme_is_said() { let mut harness = opened("qr"); type_in(&mut harness, "qr-url", "exemple.fr"); - waits_for(&mut harness, "the code is drawn", |harness| { - has(harness, "qr-code") - }); + waits_for(&mut harness, "the code is drawn", |harness| has(harness, "qr-code")); assert!(has(&harness, "qr-missing-scheme")); assert!(has(&harness, "qr-facts")); @@ -159,9 +128,7 @@ fn a_text_too_long_for_a_code_is_refused_with_its_size() { click(&mut harness, "qr-kind-0"); type_in(&mut harness, "qr-text", &"a".repeat(3_000)); - waits_for(&mut harness, "the refusal is said", |harness| { - has(harness, "qr-too-long") - }); + waits_for(&mut harness, "the refusal is said", |harness| has(harness, "qr-too-long")); assert!(!has(&harness, "qr-code")); } @@ -173,9 +140,7 @@ fn a_wifi_password_warns_before_a_note_keeps_it() { click(&mut harness, "qr-kind-2"); type_in(&mut harness, "qr-ssid", "Guests"); type_in(&mut harness, "qr-password", "not-a-real-one"); - waits_for(&mut harness, "the code is drawn", |harness| { - has(harness, "qr-code") - }); + waits_for(&mut harness, "the code is drawn", |harness| has(harness, "qr-code")); click(&mut harness, "tool-save-as-note"); assert!(has(&harness, "save-as-note-warning")); @@ -189,9 +154,7 @@ fn the_code_is_saved_where_the_dialog_says() { harness.state_mut().state.dialog = Arc::new(platform::dialog::Fixed(path.clone())); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the code is drawn", |harness| { - has(harness, "qr-code") - }); + waits_for(&mut harness, "the code is drawn", |harness| has(harness, "qr-code")); click(&mut harness, "qr-svg"); waits_for(&mut harness, "the file is written", |_| path.exists()); @@ -204,9 +167,7 @@ fn a_pinned_seed_brings_the_same_person_back() { let mut harness = identity_drawn(); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the sample is drawn", |harness| { - has(harness, "identity-seed-pinned") - }); + waits_for(&mut harness, "the sample is drawn", |harness| has(harness, "identity-seed-pinned")); settle(&mut harness); let surname = value_of(&harness, "identity-surname"); @@ -259,9 +220,7 @@ fn a_batch_is_written_as_a_file_of_as_many_people_as_asked() { harness.state_mut().state.dialog = Arc::new(platform::dialog::Fixed(path.clone())); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the sample is drawn", |harness| { - has(harness, "identity-seed-pinned") - }); + waits_for(&mut harness, "the sample is drawn", |harness| has(harness, "identity-seed-pinned")); settle(&mut harness); let surname = value_of(&harness, "identity-surname"); click(&mut harness, "identity-export"); @@ -270,10 +229,7 @@ fn a_batch_is_written_as_a_file_of_as_many_people_as_asked() { let written = std::fs::read_to_string(&path).unwrap(); let people: serde_json::Value = serde_json::from_str(&written).unwrap(); assert_eq!(people.as_array().unwrap().len(), 10); - assert_eq!( - people[0]["surname"].as_str().unwrap().to_uppercase(), - surname - ); + assert_eq!(people[0]["surname"].as_str().unwrap().to_uppercase(), surname); } #[test] @@ -284,10 +240,7 @@ fn the_separator_chosen_is_kept_with_the_application() { click(&mut harness, "identity-separator-1"); settle(&mut harness); - assert_eq!( - harness.state().state.tools.csv_separator(), - engine::tools::identity::CsvSeparator::Semicolon - ); + assert_eq!(harness.state().state.tools.csv_separator(), engine::tools::identity::CsvSeparator::Semicolon); } /// The count's two steps are named by what they do, not read out as signs. @@ -297,9 +250,6 @@ fn the_count_steps_are_named_in_words() { for step in ["identifiers-fewer", "identifiers-more"] { let node = harness.get_by(|node| node.author_id() == Some(step)); let name = node.accesskit_node().label().unwrap_or_default(); - assert!( - name.chars().any(char::is_alphabetic), - "{step} is read « {name} »" - ); + assert!(name.chars().any(char::is_alphabetic), "{step} is read « {name} »"); } } diff --git a/crates/ui/src/tools/catalogue/dates.rs b/crates/ui/src/tools/catalogue/dates.rs index 7e9e1ddb1..a0a2f9b6f 100644 --- a/crates/ui/src/tools/catalogue/dates.rs +++ b/crates/ui/src/tools/catalogue/dates.rs @@ -7,8 +7,8 @@ use egui::Ui; use engine::notes::language::Language as NoteLanguage; use engine::tools::dates::{InstantAnswer, InstantForms, InstantRequest, Magnitude, ReadAs}; use engine::tools::durations::{ - CalendarGap, DurationAnswer, DurationParts, DurationsAnswer, DurationsRequest, GapAnswer, - GapField, Transition, + CalendarGap, DurationAnswer, DurationParts, DurationsAnswer, DurationsRequest, GapAnswer, GapField, + Transition, }; use i18n::{Language, Message, keys}; use serde_json::{Value, json}; @@ -18,8 +18,7 @@ use crate::backend::Pending; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - ResultRow, card, columns, group_title, hint, label, named, paragraph, problem, result_rows, - section_title, + ResultRow, card, columns, group_title, hint, label, named, paragraph, problem, result_rows, section_title, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, Segmented, TextField, address}; @@ -78,10 +77,8 @@ fn long_date(epoch_milliseconds: f64, language: Language) -> Option { /// « 29 March », the date itself and no zone. fn day_of_month(date: &str, language: Language) -> String { - NaiveDate::parse_from_str(date, "%Y-%m-%d").map_or_else( - |_| date.to_owned(), - |it| i18n::format::day_month(it, language), - ) + NaiveDate::parse_from_str(date, "%Y-%m-%d") + .map_or_else(|_| date.to_owned(), |it| i18n::format::day_month(it, language)) } /// A form of the instant: the key of its name, its value, and whether it is pasted anywhere. @@ -101,10 +98,7 @@ fn groups_of( if let Some(nanos) = &forms.unix_nanoseconds { unix.push(plain("unixNanoseconds", nanos)); } - let mut formats = vec![ - plain("isoUtc", &forms.iso_utc), - plain("isoLocal", &forms.iso_local), - ]; + let mut formats = vec![plain("isoUtc", &forms.iso_utc), plain("isoLocal", &forms.iso_local)]; if let Some(rfc) = &forms.rfc2822 { formats.push(plain("rfc2822", rfc)); } @@ -114,11 +108,7 @@ fn groups_of( let words = i18n::time::span(at, now).text(language); landmarks.push(("relative", words, false)); } - let weekday = said( - language, - &format!("tools.dates.weekdays.{}", forms.weekday), - &[], - ); + let weekday = said(language, &format!("tools.dates.weekdays.{}", forms.weekday), &[]); landmarks.extend([ ("weekday", weekday, true), plain("weekDate", &forms.week_date), @@ -126,25 +116,13 @@ fn groups_of( plain("ordinalDate", &forms.ordinal_date), ("dayOfYear", forms.day_of_year.to_string(), true), ]); - [ - ("unix", unix), - ("formats", formats), - ("landmarks", landmarks), - ] + [("unix", unix), ("formats", formats), ("landmarks", landmarks)] } /// « 6 months, 22 days, 7 h 41 min ». fn spell_calendar(calendar: &CalendarGap, negative: bool, language: Language) -> String { - let dates = [ - ("years", calendar.years), - ("months", calendar.months), - ("days", calendar.days), - ]; - let clock = [ - ("hours", calendar.hours), - ("minutes", calendar.minutes), - ("seconds", calendar.seconds), - ]; + let dates = [("years", calendar.years), ("months", calendar.months), ("days", calendar.days)]; + let clock = [("hours", calendar.hours), ("minutes", calendar.minutes), ("seconds", calendar.seconds)]; let mut parts: Vec = dates .iter() .filter(|(_, count)| *count > 0) @@ -202,32 +180,17 @@ fn transition_note(transition: &Transition, total_minutes: u32, language: Langua said( language, "tools.dates.elapsed.hours", - &[ - ("hours", whole(minutes / 60, language).into()), - ("minutes", shown.into()), - ], + &[("hours", whole(minutes / 60, language).into()), ("minutes", shown.into())], ) }; let size = transition.minutes.unsigned_abs(); let difference = if size.is_multiple_of(60) { counted(language, "tools.dates.transition.hoursApart", size / 60) } else { - said( - language, - "tools.dates.transition.minutesApart", - &[("minutes", size.into())], - ) - }; - let way = if transition.forward { - "forward" - } else { - "backward" - }; - let undated = if transition.date.is_some() { - "" - } else { - "Undated" + said(language, "tools.dates.transition.minutesApart", &[("minutes", size.into())]) }; + let way = if transition.forward { "forward" } else { "backward" }; + let undated = if transition.date.is_some() { "" } else { "Undated" }; let date = transition .date .as_deref() @@ -260,14 +223,9 @@ impl DatesTool { ui.scope(|ui| { ui.set_max_width(room); let hint_words = tr(keys::tools::dates::PLACEHOLDER); - TextField::new(&mut self.text, &name, "dates-input") - .hint(&hint_words) - .show(ui); + TextField::new(&mut self.text, &name, "dates-input").hint(&hint_words).show(ui); }); - if Button::new(&tr(keys::tools::dates::NOW), "dates-now") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::tools::dates::NOW), "dates-now").show(ui).clicked() { self.wants_now = true; } }); @@ -279,14 +237,8 @@ impl DatesTool { use keys::tools::dates::magnitudes; let tr = |key| i18n::translate(language, key, &[]); let mut unix = self.magnitude.is_some(); - if let Some(InstantAnswer::Read { - read_as, - magnitude, - guessed, - local_assumed, - ambiguous, - .. - }) = self.answer.value() + if let Some(InstantAnswer::Read { read_as, magnitude, guessed, local_assumed, ambiguous, .. }) = + self.answer.value() { let read: Value = match read_as { ReadAs::Unix => json!(magnitude), @@ -321,11 +273,9 @@ impl DatesTool { Segmented::new(&options, "dates-magnitude").show(ui, &mut self.magnitude); } let refused = match self.answer.value() { - Some(InstantAnswer::Unreadable { at }) => Some( - Message::new(keys::tools::dates::UNREADABLE) - .with("at", *at) - .text(language), - ), + Some(InstantAnswer::Unreadable { at }) => { + Some(Message::new(keys::tools::dates::UNREADABLE).with("at", *at).text(language)) + } Some(InstantAnswer::Skipped) => Some(tr(keys::tools::dates::SKIPPED)), Some(InstantAnswer::OutOfRange) => Some(tr(keys::tools::dates::OUT_OF_RANGE)), _ => None, @@ -339,15 +289,12 @@ impl DatesTool { let p = palette(ui.ctx()); let Some(InstantAnswer::Read { forms, .. }) = self.answer.value() else { if self.answer.value().is_none() { - hint( - ui, - &i18n::translate(language, keys::tools::dates::EMPTY, &[]), - ); + hint(ui, &i18n::translate(language, keys::tools::dates::EMPTY, &[])); } return; }; - let heading = long_date(forms.epoch_milliseconds, language) - .unwrap_or_else(|| forms.iso_local.clone()); + let heading = + long_date(forms.epoch_milliseconds, language).unwrap_or_else(|| forms.iso_local.clone()); let zone = Message::new(keys::tools::dates::LOCAL_ZONE) .with("offset", forms.local_offset.as_str()) .text(language); @@ -362,10 +309,7 @@ impl DatesTool { paragraph(ui, &zone, (font::CONTROL, 400.0), p.text_2); }); for (group, rows) in &groups { - group_title( - ui, - &said(language, &format!("tools.dates.groups.{group}"), &[]), - ); + group_title(ui, &said(language, &format!("tools.dates.groups.{group}"), &[])); let names: Vec = rows .iter() .map(|(id, _, _)| said(language, &format!("tools.dates.rows.{id}"), &[])) @@ -390,9 +334,7 @@ impl DatesTool { let placeholder = tr(keys::tools::dates::DATE_PLACEHOLDER); let from = tr(keys::tools::dates::fields::FROM); label(ui, &from); - TextField::new(&mut self.from, &from, "dates-from") - .hint(&placeholder) - .show(ui); + TextField::new(&mut self.from, &from, "dates-from").hint(&placeholder).show(ui); let to = tr(keys::tools::dates::fields::TO); label(ui, &to); ui.horizontal(|ui| { @@ -400,22 +342,12 @@ impl DatesTool { let room = ui.available_width() - 90.0; ui.scope(|ui| { ui.set_max_width(room); - TextField::new(&mut self.to, &to, "dates-to") - .hint(&placeholder) - .show(ui); + TextField::new(&mut self.to, &to, "dates-to").hint(&placeholder).show(ui); }); - if Button::new(&tr(keys::tools::dates::NOW), "dates-to-now") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::tools::dates::NOW), "dates-to-now").show(ui).clicked() { let now = Local.from_utc_datetime(&drawn.now.naive_utc()); - self.to = format!( - "{}-{:02}-{:02} {}", - now.year(), - now.month(), - now.day(), - now.format("%H:%M") - ); + self.to = + format!("{}-{:02}-{:02} {}", now.year(), now.month(), now.day(), now.format("%H:%M")); } }); let Some(answer) = self.durations.value() else { @@ -447,24 +379,12 @@ impl DatesTool { .hint("PT1H30M") .show(ui); match self.durations.value().and_then(|it| it.duration.as_ref()) { - Some(DurationAnswer::Read { - negative, - parts, - iso, - from_words, - totals, - }) => { + Some(DurationAnswer::Read { negative, parts, iso, from_words, totals }) => { let p = palette(ui.ctx()); let words = spell_parts(parts, *negative, language); let totals_shown: Vec<(String, String, String)> = totals .iter() - .flat_map(|it| { - [ - ("seconds", it.seconds), - ("minutes", it.minutes), - ("hours", it.hours), - ] - }) + .flat_map(|it| [("seconds", it.seconds), ("minutes", it.minutes), ("hours", it.hours)]) .map(|(id, value)| { let path = format!("tools.dates.totals.{id}"); let shown = number(value, language); @@ -496,14 +416,9 @@ impl DatesTool { address(ui, &shown, "dates-no-totals"); } } - Some(DurationAnswer::Unreadable { - at, - problem: reason, - }) => { - let path = format!( - "tools.dates.durationProblems.{}", - json!(reason).as_str().unwrap_or_default() - ); + Some(DurationAnswer::Unreadable { at, problem: reason }) => { + let path = + format!("tools.dates.durationProblems.{}", json!(reason).as_str().unwrap_or_default()); let words = said(language, &path, &[("at", (*at).into())]); problem(ui, &words, "dates-duration-problem"); } @@ -582,22 +497,12 @@ fn gap_problem(answer: &GapAnswer, language: Language) -> String { said( language, &format!("tools.dates.gapProblems.{kind}"), - &[ - ("field", field_name(field, language).into()), - ("at", at.into()), - ], + &[("field", field_name(field, language).into()), ("at", at.into())], ) } fn measured(ui: &mut Ui, answer: &DurationsAnswer, language: Language) { - let Some(GapAnswer::Measured { - negative, - calendar, - elapsed, - iso, - transition, - ambiguous, - }) = &answer.gap + let Some(GapAnswer::Measured { negative, calendar, elapsed, iso, transition, ambiguous }) = &answer.gap else { return; }; @@ -622,10 +527,7 @@ fn measured(ui: &mut Ui, answer: &DurationsAnswer, language: Language) { said( language, "tools.dates.elapsed.weeks", - &[ - ("weeks", whole(elapsed.weeks, language).into()), - ("days", elapsed.week_days.into()), - ], + &[("weeks", whole(elapsed.weeks, language).into()), ("days", elapsed.week_days.into())], ), ), ( @@ -633,10 +535,7 @@ fn measured(ui: &mut Ui, answer: &DurationsAnswer, language: Language) { said( language, "tools.dates.elapsed.hours", - &[ - ("hours", whole(elapsed.total_hours, language).into()), - ("minutes", minutes.into()), - ], + &[("hours", whole(elapsed.total_hours, language).into()), ("minutes", minutes.into())], ), ), ("minutes", whole(elapsed.total_minutes, language)), @@ -697,23 +596,16 @@ impl Tool for DatesTool { self.text = now; } } - let request = (!self.text.trim().is_empty()).then(|| InstantRequest { - text: self.text.clone(), - magnitude: self.magnitude, - }); - self.answer - .update(turn, request, api::tools::describe_instant); + let request = (!self.text.trim().is_empty()) + .then(|| InstantRequest { text: self.text.clone(), magnitude: self.magnitude }); + self.answer.update(turn, request, api::tools::describe_instant); let typed = [&self.from, &self.to, &self.duration]; - let request = typed - .iter() - .any(|it| !it.trim().is_empty()) - .then(|| DurationsRequest { - from: self.from.clone(), - to: self.to.clone(), - duration: self.duration.clone(), - }); - self.durations - .update(turn, request, api::tools::measure_durations); + let request = typed.iter().any(|it| !it.trim().is_empty()).then(|| DurationsRequest { + from: self.from.clone(), + to: self.to.clone(), + duration: self.duration.clone(), + }); + self.durations.update(turn, request, api::tools::measure_durations); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { diff --git a/crates/ui/src/tools/catalogue/diff.rs b/crates/ui/src/tools/catalogue/diff.rs index 9e3f0242e..bfc99cc94 100644 --- a/crates/ui/src/tools/catalogue/diff.rs +++ b/crates/ui/src/tools/catalogue/diff.rs @@ -48,32 +48,21 @@ impl Sides { } fn put(&mut self, slot: &str, note: &PickedNote) { - let (text, name) = if slot == "a" { - (&mut self.a, &mut self.a_name) - } else { - (&mut self.b, &mut self.b_name) - }; + let (text, name) = + if slot == "a" { (&mut self.a, &mut self.a_name) } else { (&mut self.b, &mut self.b_name) }; text.clone_from(¬e.content); *name = Some(note.title.clone()); } fn name_of(&self, side: &str, language: Language) -> String { - let name = if side == "a" { - &self.a_name - } else { - &self.b_name - }; + let name = if side == "a" { &self.a_name } else { &self.b_name }; name.clone() .unwrap_or_else(|| i18n::translate(language, keys::tools::diff::PASTED, &[])) } /// « A » or the note's title, for a note's own title. fn title_of(&self, side: &str) -> String { - let name = if side == "a" { - &self.a_name - } else { - &self.b_name - }; + let name = if side == "a" { &self.a_name } else { &self.b_name }; name.clone().unwrap_or_else(|| side.to_uppercase()) } } @@ -142,11 +131,7 @@ impl Tool for DiffTool { } fn actions(&self) -> Vec { - let swap = ToolAction { - id: "swap", - label: keys::tools::diff::SWAP, - enabled: true, - }; + let swap = ToolAction { id: "swap", label: keys::tools::diff::SWAP, enabled: true }; let copy = match self.mode { Mode::Text => ToolAction { id: "copy-unified", @@ -246,25 +231,12 @@ fn cell_head(ui: &Ui, rect: Rect, kind: Kind, right: bool, number: u32) -> Rect let mark = mark_of(kind, right); if !mark.is_empty() { let mark = widgets::text(ui, mark, font::LABEL, 700.0, FontFamily::Monospace, ink); - let at = Pos2::new( - rect.left() + 10.0 - mark.size().x / 2.0, - middle - mark.size().y / 2.0, - ); + let at = Pos2::new(rect.left() + 10.0 - mark.size().x / 2.0, middle - mark.size().y / 2.0); ui.painter().galley(at, mark, ink); } let number = number.to_string(); - let number = widgets::text( - ui, - &number, - font::LABEL, - 400.0, - FontFamily::Monospace, - p.line_no, - ); - let at = Pos2::new( - rect.left() + 44.0 - number.size().x, - middle - number.size().y / 2.0, - ); + let number = widgets::text(ui, &number, font::LABEL, 400.0, FontFamily::Monospace, p.line_no); + let at = Pos2::new(rect.left() + 44.0 - number.size().x, middle - number.size().y / 2.0); ui.painter().galley(at, number, p.line_no); Rect::from_min_max(Pos2::new(rect.left() + 54.0, rect.top()), rect.max) } @@ -290,28 +262,13 @@ fn split_head(ui: &mut Ui, sides: &Sides, language: Language) { let p = palette(ui.ctx()); let width = ui.available_width(); let (rect, _) = ui.allocate_exact_size(Vec2::new(width, 34.0), Sense::hover()); - ui.painter().rect_filled( - rect, - CornerRadius { - nw: 10, - ne: 10, - ..CornerRadius::ZERO - }, - p.bg_1, - ); - ui.painter() - .hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); ui.painter() - .vline(rect.center().x, rect.y_range(), (1.0, p.line_soft)); + .rect_filled(rect, CornerRadius { nw: 10, ne: 10, ..CornerRadius::ZERO }, p.bg_1); + ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); + ui.painter().vline(rect.center().x, rect.y_range(), (1.0, p.line_soft)); for (side, left) in [("a", rect.left()), ("b", rect.center().x)] { let words = format!("{} {}", side.to_uppercase(), sides.name_of(side, language)); - let galley = widgets::one_line( - ui, - &words, - (font::LABEL, 400.0), - p.text_0, - width / 2.0 - 24.0, - ); + let galley = widgets::one_line(ui, &words, (font::LABEL, 400.0), p.text_0, width / 2.0 - 24.0); let at = Pos2::new(left + 12.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_0); } @@ -320,17 +277,12 @@ fn split_head(ui: &mut Ui, sides: &Sides, language: Language) { /// A count in its pill. fn pill(ui: &mut Ui, words: &str, hue: Color32, author_id: &str) { let galley = widgets::text(ui, words, font::CONTROL, 400.0, FontFamily::Monospace, hue); - let (rect, response) = - ui.allocate_exact_size(galley.size() + Vec2::new(20.0, 8.0), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(galley.size() + Vec2::new(20.0, 8.0), Sense::hover()); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, words)); widgets::address(ui, &response, author_id); - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::PANEL), - hue.gamma_multiply(0.14), - ); ui.painter() - .galley(rect.min + Vec2::new(10.0, 4.0), galley, hue); + .rect_filled(rect, CornerRadius::same(radius::PANEL), hue.gamma_multiply(0.14)); + ui.painter().galley(rect.min + Vec2::new(10.0, 4.0), galley, hue); } /// What a row's text would be were the two sides one above the other. diff --git a/crates/ui/src/tools/catalogue/diff/structured.rs b/crates/ui/src/tools/catalogue/diff/structured.rs index 3705308de..25d66a3ca 100644 --- a/crates/ui/src/tools/catalogue/diff/structured.rs +++ b/crates/ui/src/tools/catalogue/diff/structured.rs @@ -5,8 +5,8 @@ use egui::{CornerRadius, FontFamily, Pos2, Rect, Role, Sense, Stroke, Ui, Vec2, use engine::notes::language::Language as NoteLanguage; use engine::tools::convert::DataFormat; use engine::tools::diff::{ - JsonChange, JsonChangeKind, JsonDiffAnswer, JsonDiffCounts, JsonDiffLine, JsonDiffRequest, - JsonDiffRow, JsonDiffRowKind, JsonDiffSide, ValueSummary, + JsonChange, JsonChangeKind, JsonDiffAnswer, JsonDiffCounts, JsonDiffLine, JsonDiffRequest, JsonDiffRow, + JsonDiffRowKind, JsonDiffSide, ValueSummary, }; use i18n::{Language, Message, keys}; @@ -115,11 +115,7 @@ impl StructuredDiff { /// Both sides, and each read by its shape again: a format left chosen would misread them. pub(super) fn fill_sample(&mut self, sides: &mut Sides) { - *sides = Sides { - a: SAMPLE_A.to_owned(), - b: SAMPLE_B.to_owned(), - ..Sides::default() - }; + *sides = Sides { a: SAMPLE_A.to_owned(), b: SAMPLE_B.to_owned(), ..Sides::default() }; self.format_a = None; self.format_b = None; } @@ -150,26 +146,15 @@ impl StructuredDiff { /// What each side was read as, once Rust has said. fn read_as(&self, side: JsonDiffSide) -> Option { match self.answer.value()? { - JsonDiffAnswer::Compared { - format_a, format_b, .. - } => Some(if side == JsonDiffSide::A { - *format_a - } else { - *format_b - }), - JsonDiffAnswer::Unreadable { - side: read, format, .. - } => (*read == side).then_some(*format), + JsonDiffAnswer::Compared { format_a, format_b, .. } => { + Some(if side == JsonDiffSide::A { *format_a } else { *format_b }) + } + JsonDiffAnswer::Unreadable { side: read, format, .. } => (*read == side).then_some(*format), JsonDiffAnswer::NotStructured { .. } => None, } } - pub(super) fn ui( - &mut self, - ui: &mut Ui, - sides: &mut Sides, - drawn: &mut Drawn<'_>, - ) -> Option { + pub(super) fn ui(&mut self, ui: &mut Ui, sides: &mut Sides, drawn: &mut Drawn<'_>) -> Option { let language = drawn.language; let tr = |key| i18n::translate(language, key, &[]); let line = hint(ui, &tr(keys::tools::diff::DATA_LINE)); @@ -213,11 +198,8 @@ impl StructuredDiff { self.format_menu(ui, (slot, side), language); }); }); - let (text, title) = if slot == "a" { - (&mut sides.a, &mut sides.a_name) - } else { - (&mut sides.b, &mut sides.b_name) - }; + let (text, title) = + if slot == "a" { (&mut sides.a, &mut sides.a_name) } else { (&mut sides.b, &mut sides.b_name) }; let aloud = Message::new(keys::tools::diff::structured::INPUT_LABEL) .with("side", mark.as_str()) .text(language); @@ -243,11 +225,7 @@ impl StructuredDiff { .with("side", slot.to_uppercase()) .text(language); let id = format!("structured-diff-format-{slot}"); - let chosen = if side == JsonDiffSide::A { - &mut self.format_a - } else { - &mut self.format_b - }; + let chosen = if side == JsonDiffSide::A { &mut self.format_a } else { &mut self.format_b }; let automatic = chosen.is_none(); ChoiceMenu::new(&label, &id, &options).show(ui, chosen); if automatic && let Some(read) = self.read_as(side) { @@ -260,12 +238,7 @@ impl StructuredDiff { } /// What Rust could not make of this side. - fn about_the_side( - &self, - ui: &mut Ui, - (slot, side): (&str, JsonDiffSide), - language: Language, - ) -> bool { + fn about_the_side(&self, ui: &mut Ui, (slot, side): (&str, JsonDiffSide), language: Language) -> bool { let tr = |key| i18n::translate(language, key, &[]); match self.answer.value() { Some(JsonDiffAnswer::NotStructured { sides }) if sides.contains(&side) => { @@ -274,16 +247,9 @@ impl StructuredDiff { let said = paragraph(ui, &words, (font::BODY, 400.0), p.text_1); address(ui, &said, &format!("structured-diff-not-structured-{slot}")); let id = format!("structured-diff-as-text-{slot}"); - Button::new(&tr(keys::tools::diff::structured::AS_TEXT), &id) - .show(ui) - .clicked() + Button::new(&tr(keys::tools::diff::structured::AS_TEXT), &id).show(ui).clicked() } - Some(JsonDiffAnswer::Unreadable { - side: read, - format, - line, - column, - }) if *read == side => { + Some(JsonDiffAnswer::Unreadable { side: read, format, line, column }) if *read == side => { let words = Message::new(keys::tools::diff::structured::UNREADABLE) .with("format", format_name(*format)) .with("line", *line) @@ -300,13 +266,7 @@ impl StructuredDiff { let tr = |key| i18n::translate(language, key, &[]); let answer = self.answer.value().cloned(); let Some(JsonDiffAnswer::Compared { - changes, - counts, - rows, - rows_truncated, - format_a, - format_b, - .. + changes, counts, rows, rows_truncated, format_a, format_b, .. }) = answer else { if self.answer.value().is_none() { @@ -353,41 +313,19 @@ impl StructuredDiff { let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); let count = |key, count| Message::new(key).with("count", count).text(language); - let options = [ - (Layout::Split, tr(words::layouts::SPLIT)), - (Layout::Unified, tr(words::layouts::UNIFIED)), - ]; + let options = + [(Layout::Split, tr(words::layouts::SPLIT)), (Layout::Unified, tr(words::layouts::UNIFIED))]; let options = options.each_ref().map(|(id, name)| (*id, name.as_str())); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing.x = gap::GROUPS; - pill( - ui, - &count(words::ADDED, counts.added), - p.green, - "structured-diff-added", - ); - pill( - ui, - &count(words::REMOVED, counts.removed), - p.red, - "structured-diff-removed", - ); + pill(ui, &count(words::ADDED, counts.added), p.green, "structured-diff-added"); + pill(ui, &count(words::REMOVED, counts.removed), p.red, "structured-diff-removed"); let modified = count(words::MODIFIED, counts.modified); pill(ui, &modified, p.amber_text, "structured-diff-modified"); let order = tr(words::IGNORE_KEY_ORDER); - check( - ui, - &mut self.ignore_key_order, - &order, - "structured-diff-ignore-order", - ); + check(ui, &mut self.ignore_key_order, &order, "structured-diff-ignore-order"); let spaces = tr(words::IGNORE_WHITESPACE); - check( - ui, - &mut self.ignore_whitespace, - &spaces, - "structured-diff-ignore-spaces", - ); + check(ui, &mut self.ignore_whitespace, &spaces, "structured-diff-ignore-spaces"); Segmented::new(&options, "structured-diff-layout").show(ui, &mut self.layout); }); } @@ -455,15 +393,10 @@ fn row(ui: &mut Ui, row: &JsonDiffRow, selected: Option<&str>) { None => absent_side(ui, rect), } } - ui.painter() - .vline(rect.center().x, rect.y_range(), (1.0, p.line_soft)); + ui.painter().vline(rect.center().x, rect.y_range(), (1.0, p.line_soft)); if selected == Some(row.path.as_str()) { - ui.painter().rect_stroke( - rect, - 0.0, - Stroke::new(1.0, p.amber_edge), - egui::StrokeKind::Inside, - ); + ui.painter() + .rect_stroke(rect, 0.0, Stroke::new(1.0, p.amber_edge), egui::StrokeKind::Inside); let id = response.id.with(row.path.as_str()); if !ui.data(|data| data.get_temp::(id).unwrap_or(false)) { ui.data_mut(|data| data.insert_temp(id, true)); @@ -475,19 +408,8 @@ fn row(ui: &mut Ui, row: &JsonDiffRow, selected: Option<&str>) { fn cell(ui: &Ui, rect: Rect, kind: Kind, right: bool, line: &JsonDiffLine) { let p = palette(ui.ctx()); let code = cell_head(ui, rect, kind, right, line.number); - let ink = if kind == Kind::Same { - p.text_1 - } else { - p.text_0 - }; - let galley = widgets::text( - ui, - &line.text, - font::LABEL, - 400.0, - FontFamily::Monospace, - ink, - ); + let ink = if kind == Kind::Same { p.text_1 } else { p.text_0 }; + let galley = widgets::text(ui, &line.text, font::LABEL, 400.0, FontFamily::Monospace, ink); let at = Pos2::new(code.left(), code.center().y - galley.size().y / 2.0); ui.painter().with_clip_rect(code).galley(at, galley, ink); } @@ -539,11 +461,7 @@ fn change_row(ui: &mut Ui, change: &JsonChange, on: bool, language: Language) -> corner, ); let rect = response.rect; - let fill = if on { - p.bg_3 - } else { - towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)) - }; + let fill = if on { p.bg_3 } else { towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)) }; ui.painter().rect_filled(rect, corner, fill); let height = top.size().y; top.paint(ui, rect.min + Vec2::new(10.0, 6.0), p.text_0); diff --git a/crates/ui/src/tools/catalogue/diff/text.rs b/crates/ui/src/tools/catalogue/diff/text.rs index 28a815c24..f18d20f1c 100644 --- a/crates/ui/src/tools/catalogue/diff/text.rs +++ b/crates/ui/src/tools/catalogue/diff/text.rs @@ -34,11 +34,7 @@ const SAMPLE_B: &str = "server { "; pub(super) fn fill_sample(sides: &mut Sides) { - *sides = Sides { - a: SAMPLE_A.to_owned(), - b: SAMPLE_B.to_owned(), - ..Sides::default() - }; + *sides = Sides { a: SAMPLE_A.to_owned(), b: SAMPLE_B.to_owned(), ..Sides::default() }; } #[expect(clippy::struct_excessive_bools, reason = "each is its own option")] @@ -112,20 +108,12 @@ impl TextDiff { } /// The mode to go to, when the offer is taken. - pub(super) fn ui( - &mut self, - ui: &mut Ui, - sides: &mut Sides, - drawn: &mut Drawn<'_>, - ) -> Option { + pub(super) fn ui(&mut self, ui: &mut Ui, sides: &mut Sides, drawn: &mut Drawn<'_>) -> Option { inputs(ui, sides, drawn); self.settings(ui, drawn.language); let language = drawn.language; let Some(answer) = self.answer.value() else { - hint( - ui, - &i18n::translate(language, keys::tools::diff::text::EMPTY, &[]), - ); + hint(ui, &i18n::translate(language, keys::tools::diff::text::EMPTY, &[])); return None; }; let asked = offer(ui, answer, language); @@ -159,22 +147,10 @@ impl TextDiff { ui.spacing_mut().item_spacing.x = gap::BLOCKS; Segmented::new(&options, "text-diff-granularity").show(ui, &mut self.granularity); for (value, key, id) in [ - ( - &mut self.trailing, - ignore::TRAILING, - "text-diff-ignore-trailing", - ), - ( - &mut self.whitespace, - ignore::WHITESPACE, - "text-diff-ignore-whitespace", - ), + (&mut self.trailing, ignore::TRAILING, "text-diff-ignore-trailing"), + (&mut self.whitespace, ignore::WHITESPACE, "text-diff-ignore-whitespace"), (&mut self.case, ignore::CASE, "text-diff-ignore-case"), - ( - &mut self.endings, - ignore::ENDINGS, - "text-diff-ignore-endings", - ), + (&mut self.endings, ignore::ENDINGS, "text-diff-ignore-endings"), ] { check(ui, value, &tr(key), id); } @@ -208,23 +184,14 @@ fn input(ui: &mut Ui, sides: &mut Sides, drawn: &mut Drawn<'_>, slot: &'static s note_import_into(ui, drawn, ("text", slot), &id); }); }); - let (text, title) = if slot == "a" { - (&mut sides.a, &mut sides.a_name) - } else { - (&mut sides.b, &mut sides.b_name) - }; + let (text, title) = + if slot == "a" { (&mut sides.a, &mut sides.a_name) } else { (&mut sides.b, &mut sides.b_name) }; let side = slot.to_uppercase(); let aloud = Message::new(keys::tools::diff::text::INPUT_LABEL) .with("side", side.as_str()) .text(language); let id = format!("text-diff-{slot}"); - let typed = text_area( - ui, - text, - (&aloud, &id), - &tr(keys::tools::diff::text::PLACEHOLDER), - 6, - ); + let typed = text_area(ui, text, (&aloud, &id), &tr(keys::tools::diff::text::PLACEHOLDER), 6); if typed.changed() { *title = None; } @@ -239,19 +206,11 @@ fn offer(ui: &mut Ui, answer: &TextDiffAnswer, language: Language) -> Option (egui::Color32, egui::Color32) { fn unified(ui: &mut Ui, text: &str) { let lines: Vec<&str> = text.trim_end_matches('\n').split('\n').collect(); - rows_box( - ui, - "text-diff-unified", - super::unified_height(lines.len()), - |ui| { - virtual_list(ui, "text-diff-unified-list", ROW, lines.len(), |ui, at| { - let width = ui.available_width(); - let (rect, response) = - ui.allocate_exact_size(Vec2::new(width, ROW), Sense::hover()); - response - .widget_info(|| egui::WidgetInfo::labeled(egui::Role::Row, true, lines[at])); - address(ui, &response, "text-diff-unified-line"); - let (tint, ink) = unified_ink(lines[at], ui); - ui.painter().rect_filled(rect, 0.0, tint); - let family = egui::FontFamily::Monospace; - let galley = crate::widgets::text(ui, lines[at], font::LABEL, 400.0, family, ink); - let at = Pos2::new(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0); - ui.painter().with_clip_rect(rect).galley(at, galley, ink); - }); - }, - ); + rows_box(ui, "text-diff-unified", super::unified_height(lines.len()), |ui| { + virtual_list(ui, "text-diff-unified-list", ROW, lines.len(), |ui, at| { + let width = ui.available_width(); + let (rect, response) = ui.allocate_exact_size(Vec2::new(width, ROW), Sense::hover()); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Row, true, lines[at])); + address(ui, &response, "text-diff-unified-line"); + let (tint, ink) = unified_ink(lines[at], ui); + ui.painter().rect_filled(rect, 0.0, tint); + let family = egui::FontFamily::Monospace; + let galley = crate::widgets::text(ui, lines[at], font::LABEL, 400.0, family, ink); + let at = Pos2::new(rect.left() + 12.0, rect.center().y - galley.size().y / 2.0); + ui.painter().with_clip_rect(rect).galley(at, galley, ink); + }); + }); } diff --git a/crates/ui/src/tools/catalogue/encoding_tests.rs b/crates/ui/src/tools/catalogue/encoding_tests.rs index f26536847..3ebc2be29 100644 --- a/crates/ui/src/tools/catalogue/encoding_tests.rs +++ b/crates/ui/src/tools/catalogue/encoding_tests.rs @@ -30,9 +30,7 @@ fn a_broken_escape_is_said_where_it_is() { type_in(&mut harness, "url-codec-encoded", "100%zz"); - waits_for(&mut harness, "the escape is refused", |harness| { - has(harness, "url-codec-problem") - }); + waits_for(&mut harness, "the escape is refused", |harness| has(harness, "url-codec-problem")); } #[test] @@ -41,9 +39,7 @@ fn the_url_parser_takes_a_url_apart_and_never_reads_its_password_back() { click(&mut harness, "tool-sample"); click(&mut harness, "url-tab-1"); - waits_for(&mut harness, "the parts are shown", |harness| { - has(harness, "url-parser-parts") - }); + waits_for(&mut harness, "the parts are shown", |harness| has(harness, "url-parser-parts")); let values = output_values(&harness); assert!(values.contains(&"api.example.com".to_owned()), "{values:?}"); @@ -56,53 +52,64 @@ fn the_hash_tool_finds_the_algorithm_of_a_digest() { let mut harness = opened("hash"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the digest is matched", |harness| { - has(harness, "hash-verdict") - }); + waits_for(&mut harness, "the digest is matched", |harness| has(harness, "hash-verdict")); assert!(value_of(&harness, "hash-verdict").contains("SHA-256")); assert!(has(&harness, "hash-results")); } #[test] -fn an_hmac_key_changes_the_digests_and_goes_with_the_tool() { +fn an_hmac_key_changes_the_digests() { let mut harness = opened("hash"); type_in(&mut harness, "hash-input", "hello"); - waits_for(&mut harness, "it is hashed", |harness| { - has(harness, "hash-results") - }); + waits_for(&mut harness, "it is hashed", |harness| has(harness, "hash-results")); let plain = output_values(&harness); click(&mut harness, "hash-hmac"); type_in(&mut harness, "hash-key", "key"); - waits_for(&mut harness, "it is keyed", |harness| { - output_values(harness) != plain - }); + waits_for(&mut harness, "it is keyed", |harness| output_values(harness) != plain); +} - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("hash")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "hash-key"), ""); +/// Nothing secret outlives the tool it was typed in. +#[test] +fn a_secret_typed_goes_with_its_tool() { + for (tool, before, field) in [ + ("hash", Some("hash-hmac"), "hash-key"), + ("jwt", None, "jwt-token"), + ("jwt", None, "jwt-secret"), + ("checks", None, "checks-input"), + ] { + let mut harness = opened(tool); + if let Some(before) = before { + click(&mut harness, before); + } + type_in(&mut harness, field, "4111111111111111"); + assert!(!value_of(&harness, field).is_empty(), "{field}"); + + click(&mut harness, "tool-back"); + let bench = harness.state_mut(); + let open = crate::action::Action::Tools(crate::tools::Action::Open(tool)); + bench.state.apply(open, &egui::Context::default(), &bench.backend); + settle(&mut harness); + if let Some(before) = before + && !has(&harness, field) + { + click(&mut harness, before); + } + assert_eq!(value_of(&harness, field), "", "{field}"); + } } #[test] fn passwords_are_drawn_with_their_strength_and_kept_from_no_session() { let mut harness = opened("password"); - waits_for(&mut harness, "they are drawn", |harness| { - has(harness, "password-strength") - }); + waits_for(&mut harness, "they are drawn", |harness| has(harness, "password-strength")); let drawn = output_values(&harness); assert_eq!(drawn.len(), 5); assert_eq!(drawn[0].chars().count(), 20); click(&mut harness, "password-generate"); - waits_for(&mut harness, "others are drawn", |harness| { - output_values(harness) != drawn - }); + waits_for(&mut harness, "others are drawn", |harness| output_values(harness) != drawn); } #[test] @@ -112,31 +119,18 @@ fn no_character_set_left_is_said() { click(&mut harness, &format!("password-set-{set}")); } - waits_for(&mut harness, "nothing can be drawn", |harness| { - has(harness, "password-problem") - }); + waits_for(&mut harness, "nothing can be drawn", |harness| has(harness, "password-problem")); } #[test] -fn a_token_is_decoded_verified_and_gone_with_the_tool() { +fn a_token_is_decoded_and_its_signature_verified() { let mut harness = opened("jwt"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the token is decoded", |harness| { - has(harness, "jwt-state") - }); + waits_for(&mut harness, "the token is decoded", |harness| has(harness, "jwt-state")); assert!(value_of(&harness, "jwt-header").contains("HS256")); assert!(value_of(&harness, "jwt-payload").contains("Ada Lovelace")); assert!(value_of(&harness, "jwt-verification").contains("Valid signature.")); - - click(&mut harness, "tool-back"); - let bench = harness.state_mut(); - let open = crate::action::Action::Tools(crate::tools::Action::Open("jwt")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); - settle(&mut harness); - assert_eq!(value_of(&harness, "jwt-token"), ""); } #[test] @@ -145,9 +139,7 @@ fn a_token_that_is_none_says_why() { type_in(&mut harness, "jwt-token", "not a token"); - waits_for(&mut harness, "the token is refused", |harness| { - has(harness, "jwt-problem") - }); + waits_for(&mut harness, "the token is refused", |harness| has(harness, "jwt-problem")); } #[test] @@ -155,9 +147,7 @@ fn a_text_is_written_in_six_encodings() { let mut harness = opened("base64"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the text is encoded", |harness| { - has(harness, "base64-encodings") - }); + waits_for(&mut harness, "the text is encoded", |harness| has(harness, "base64-encodings")); let values = output_values(&harness); assert_eq!(values.len(), 6); @@ -171,9 +161,7 @@ fn an_encoding_is_recognised_and_decoded() { type_in(&mut harness, "base64-input", "Q2Fmw6k="); - waits_for(&mut harness, "the text is decoded", |harness| { - has(harness, "base64-output") - }); + waits_for(&mut harness, "the text is decoded", |harness| has(harness, "base64-output")); assert_eq!(value_of(&harness, "base64-output"), "Café"); assert!(has(&harness, "base64-reading")); } @@ -201,9 +189,7 @@ fn a_key_left_behind_is_gone_from_the_undo() { click(&mut harness, "tool-back"); let bench = harness.state_mut(); let open = crate::action::Action::Tools(crate::tools::Action::Open("hash")); - bench - .state - .apply(open, &egui::Context::default(), &bench.backend); + bench.state.apply(open, &egui::Context::default(), &bench.backend); settle(&mut harness); click(&mut harness, "hash-key"); diff --git a/crates/ui/src/tools/catalogue/hash.rs b/crates/ui/src/tools/catalogue/hash.rs index 72a7c90b6..12a2c5473 100644 --- a/crates/ui/src/tools/catalogue/hash.rs +++ b/crates/ui/src/tools/catalogue/hash.rs @@ -21,8 +21,8 @@ use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::note_picker::PickedNote; use crate::tools::ui::{ - ResultRow, card, check, columns, hint, label, named, note_import, problem, result_rows, - section_head, text_area, + ResultRow, card, check, columns, hint, label, named, note_import, problem, result_rows, section_head, + text_area, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{self, Button, Segmented, TextField, address, hovered, interact, towards}; @@ -63,10 +63,8 @@ fn is_obsolete(algorithm: HashAlgorithm) -> bool { } /// SHA-256 of `hello world`, so the check finds its algorithm. -const SAMPLE: (&str, &str) = ( - "hello world", - "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9", -); +const SAMPLE: (&str, &str) = + ("hello world", "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"); #[derive(Clone, Copy, PartialEq, Eq)] enum Source { @@ -115,10 +113,9 @@ fn shape_words(shape: &DigestShape, language: Language) -> String { use keys::tools::hash::shapes; let or = i18n::translate(language, keys::tools::hash::OR, &[]); let (key, none, count, algorithms): (Key, Key, u32, &[HashAlgorithm]) = match shape { - DigestShape::Hex { - characters, - algorithms, - } => (shapes::HEX, shapes::HEX_NONE, *characters, algorithms), + DigestShape::Hex { characters, algorithms } => { + (shapes::HEX, shapes::HEX_NONE, *characters, algorithms) + } DigestShape::Base64 { bytes, algorithms } => { (shapes::BASE64, shapes::BASE64_NONE, *bytes, algorithms) } @@ -136,9 +133,7 @@ impl HashTool { fn input_of(&self) -> Option { match self.source { Source::File => self.path.clone().map(|path| HashInput::File { path }), - Source::Text => (!self.text.is_empty()).then(|| HashInput::Text { - text: self.text.clone(), - }), + Source::Text => (!self.text.is_empty()).then(|| HashInput::Text { text: self.text.clone() }), } } @@ -162,11 +157,7 @@ impl HashTool { fn name_of(&self, algorithm: HashAlgorithm) -> &'static str { let keyed = self.answer.answered().is_some_and(|it| it.key.is_some()); - if keyed { - hmac_name(algorithm) - } else { - algorithm_name(algorithm) - } + if keyed { hmac_name(algorithm) } else { algorithm_name(algorithm) } } fn digests(&self) -> &[DigestValue] { @@ -223,19 +214,9 @@ impl HashTool { fn measure(&self, ui: &mut Ui, language: Language) { let tr = |key| i18n::translate(language, key, &[]); match self.answer.value() { - Some(HashAnswer::Hashed { - bytes, - ends_with_newline, - .. - }) => { - let count = Message::new(keys::tools::hash::BYTES) - .with("count", *bytes) - .text(language); - let utf8 = if self.source == Source::Text { - " · UTF-8" - } else { - "" - }; + Some(HashAnswer::Hashed { bytes, ends_with_newline, .. }) => { + let count = Message::new(keys::tools::hash::BYTES).with("count", *bytes).text(language); + let utf8 = if self.source == Source::Text { " · UTF-8" } else { "" }; let newline = if *ends_with_newline { tr(keys::tools::hash::WITH_NEWLINE) } else { @@ -287,24 +268,14 @@ impl HashTool { let name = tr(keys::tools::hash::VERIFY); label(ui, &name); let placeholder = tr(keys::tools::hash::EXPECTED_PLACEHOLDER); - let field = text_area( - ui, - &mut self.expected, - (&name, "hash-expected"), - &placeholder, - 2, - ); + let field = text_area(ui, &mut self.expected, (&name, "hash-expected"), &placeholder, 2); if self.expected.trim().is_empty() { return; } let p = palette(ui.ctx()); match self.answer.value() { Some(HashAnswer::Hashed { - verdict: - Some(DigestVerdict::Matches { - algorithm, - encoding, - }), + verdict: Some(DigestVerdict::Matches { algorithm, encoding }), .. }) => { let encoding = named(language, "tools.hash.encodings", &json!(encoding)); @@ -322,10 +293,7 @@ impl HashTool { let said = crate::tools::ui::pill(ui, &words, p.green); address(ui, &said, "hash-verdict"); } - Some(HashAnswer::Hashed { - verdict: Some(DigestVerdict::NoMatch { shape }), - .. - }) => { + Some(HashAnswer::Hashed { verdict: Some(DigestVerdict::NoMatch { shape }), .. }) => { let words = tr(keys::tools::hash::NO_MATCH); let said = crate::tools::ui::paragraph(ui, &words, (font::BODY, 500.0), p.red); address(ui, &said, "hash-verdict"); @@ -356,10 +324,7 @@ impl HashTool { }); let encodings = [ (DigestEncoding::Hex, tr(keys::tools::hash::encodings::HEX)), - ( - DigestEncoding::Base64, - tr(keys::tools::hash::encodings::BASE64), - ), + (DigestEncoding::Base64, tr(keys::tools::hash::encodings::BASE64)), ]; let encodings = encodings.each_ref().map(|(id, name)| (*id, name.as_str())); Segmented::new(&encodings, "hash-encoding").show(ui, &mut self.encoding); @@ -372,27 +337,19 @@ impl HashTool { fn results(&self, ui: &mut Ui, language: Language) { let digests = self.digests(); if digests.is_empty() { - hint( - ui, - &i18n::translate(language, keys::tools::hash::EMPTY, &[]), - ); + hint(ui, &i18n::translate(language, keys::tools::hash::EMPTY, &[])); return; } let matched = match self.answer.value() { - Some(HashAnswer::Hashed { - verdict: Some(DigestVerdict::Matches { algorithm, .. }), - .. - }) => Some(*algorithm), + Some(HashAnswer::Hashed { verdict: Some(DigestVerdict::Matches { algorithm, .. }), .. }) => { + Some(*algorithm) + } _ => None, }; let obsolete = i18n::translate(language, keys::tools::hash::OBSOLETE, &[]); let metas: Vec = digests .iter() - .map(|digest| { - Message::new(keys::tools::hash::BITS) - .with("count", digest.bits) - .text(language) - }) + .map(|digest| Message::new(keys::tools::hash::BITS).with("count", digest.bits).text(language)) .collect(); card(ui, "hash-results", |ui| { let rows: Vec<_> = digests @@ -415,13 +372,7 @@ impl HashTool { let chosen = &self.chosen; self.chosen = ALGORITHMS .into_iter() - .filter(|it| { - if *it == algorithm { - !on - } else { - chosen.contains(it) - } - }) + .filter(|it| if *it == algorithm { !on } else { chosen.contains(it) }) .collect(); } } @@ -443,20 +394,10 @@ fn pill(ui: &mut Ui, algorithm: HashAlgorithm, on: bool) -> egui::Response { corner, ); let rect = response.rect; - let edge = if on { - p.amber_dim - } else { - towards(p.line_soft, p.amber_dim, hovered(ui, &response)) - }; - ui.painter().rect( - rect, - corner, - p.bg_2, - Stroke::new(1.0, edge), - egui::StrokeKind::Inside, - ); + let edge = if on { p.amber_dim } else { towards(p.line_soft, p.amber_dim, hovered(ui, &response)) }; ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, ink); + .rect(rect, corner, p.bg_2, Stroke::new(1.0, edge), egui::StrokeKind::Inside); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, ink); response } @@ -488,10 +429,7 @@ impl Tool for HashTool { fn result(&self, language: Language) -> Option { let digests = self.digests(); - let width = digests - .iter() - .map(|digest| self.name_of(digest.algorithm).len()) - .max()?; + let width = digests.iter().map(|digest| self.name_of(digest.algorithm).len()).max()?; let content: Vec = digests .iter() .map(|it| format!("{:width$} {}", self.name_of(it.algorithm), it.value)) @@ -540,12 +478,7 @@ mod tests { #[test] fn leaving_drops_the_answer_that_was_keyed() { let (backend, _profile) = crate::testing::backend(); - let mut tool = HashTool { - text: "hello".to_owned(), - hmac: true, - key: "key".to_owned(), - ..fresh() - }; + let mut tool = HashTool { text: "hello".to_owned(), hmac: true, key: "key".to_owned(), ..fresh() }; for time in [0.0, 0.01] { on_a_turn(&backend, time, |turn| tool.update(turn)); backend.settle(); diff --git a/crates/ui/src/tools/catalogue/http_headers.rs b/crates/ui/src/tools/catalogue/http_headers.rs index 8cc704ab0..a67eac2b7 100644 --- a/crates/ui/src/tools/catalogue/http_headers.rs +++ b/crates/ui/src/tools/catalogue/http_headers.rs @@ -31,18 +31,9 @@ fn row(header: &Value, language: Language) -> ReferenceRow { let (name, group) = (text(header, "name"), text(header, "group")); let (example, by) = (text(header, "example"), text(header, "by")); let lower = name.to_lowercase(); - let does = word( - language, - &format!("tools.http-headers.words.headers.{lower}"), - ); + let does = word(language, &format!("tools.http-headers.words.headers.{lower}")); let heading = word(language, &format!("tools.http-headers.groups.{group}")); - let direction = word( - language, - &format!( - "tools.http-headers.directions.{}", - text(header, "direction") - ), - ); + let direction = word(language, &format!("tools.http-headers.directions.{}", text(header, "direction"))); let tags: Vec = [ (header["security"] == true).then(|| tr(words::SECURITY)), (header["deprecated"] == true).then(|| tr(words::DEPRECATED)), @@ -54,12 +45,7 @@ fn row(header: &Value, language: Language) -> ReferenceRow { if !tags.is_empty() { named = named.below(tags.join(" · ")); } - let cells = vec![ - named, - Cell::text(direction), - Cell::text(does.clone()).below(example), - Cell::text(by), - ]; + let cells = vec![named, Cell::text(direction), Cell::text(does.clone()).below(example), Cell::text(by)]; ReferenceRow::new(name, group, cells) .searched_by([name, &does, example, by, &heading]) .found_as(name, does) @@ -72,12 +58,7 @@ pub(crate) fn table(language: Language) -> Table { columns: columns_of( language, "tools.http-headers.columns", - &[ - ("name", Some(0.31)), - ("direction", Some(0.11)), - ("does", None), - ("by", Some(0.16)), - ], + &[("name", Some(0.31)), ("direction", Some(0.11)), ("does", None), ("by", Some(0.16))], ), caption: keys::tools::http_headers::NAME, placeholder: keys::tools::http_headers::PLACEHOLDER, diff --git a/crates/ui/src/tools/catalogue/http_status.rs b/crates/ui/src/tools/catalogue/http_status.rs index fe223d76a..866726940 100644 --- a/crates/ui/src/tools/catalogue/http_status.rs +++ b/crates/ui/src/tools/catalogue/http_status.rs @@ -72,12 +72,7 @@ const STATUSES: [Status; 78] = [ (494, "Request Header Too Large", "nginx", Some("unofficial")), (495, "SSL Certificate Error", "nginx", Some("unofficial")), (496, "SSL Certificate Required", "nginx", Some("unofficial")), - ( - 497, - "HTTP Request Sent to HTTPS Port", - "nginx", - Some("unofficial"), - ), + (497, "HTTP Request Sent to HTTPS Port", "nginx", Some("unofficial")), (499, "Client Closed Request", "nginx", Some("unofficial")), (500, "Internal Server Error", "RFC 9110", None), (501, "Not Implemented", "RFC 9110", None), @@ -88,46 +83,16 @@ const STATUSES: [Status; 78] = [ (506, "Variant Also Negotiates", "RFC 2295", None), (507, "Insufficient Storage", "RFC 4918", None), (508, "Loop Detected", "RFC 5842", None), - ( - 509, - "Bandwidth Limit Exceeded", - "Apache", - Some("unofficial"), - ), + (509, "Bandwidth Limit Exceeded", "Apache", Some("unofficial")), (510, "Not Extended", "RFC 2774", Some("obsolete")), (511, "Network Authentication Required", "RFC 6585", None), - ( - 520, - "Web Server Returned an Unknown Error", - "Cloudflare", - Some("unofficial"), - ), + (520, "Web Server Returned an Unknown Error", "Cloudflare", Some("unofficial")), (521, "Web Server Is Down", "Cloudflare", Some("unofficial")), - ( - 522, - "Connection Timed Out", - "Cloudflare", - Some("unofficial"), - ), - ( - 523, - "Origin Is Unreachable", - "Cloudflare", - Some("unofficial"), - ), + (522, "Connection Timed Out", "Cloudflare", Some("unofficial")), + (523, "Origin Is Unreachable", "Cloudflare", Some("unofficial")), (524, "A Timeout Occurred", "Cloudflare", Some("unofficial")), - ( - 525, - "SSL Handshake Failed", - "Cloudflare", - Some("unofficial"), - ), - ( - 526, - "Invalid SSL Certificate", - "Cloudflare", - Some("unofficial"), - ), + (525, "SSL Handshake Failed", "Cloudflare", Some("unofficial")), + (526, "Invalid SSL Certificate", "Cloudflare", Some("unofficial")), ]; /// The code in the hue of its class. @@ -145,21 +110,12 @@ fn class_cell(key: &str, code: u32) -> Cell { fn row((code, name, by, standing): Status, language: Language) -> ReferenceRow { let group = format!("{}xx", code / 100); let key = code.to_string(); - let meaning = word( - language, - &format!("tools.http-status.words.codes.{code}.meaning"), - ); - let usage = word( - language, - &format!("tools.http-status.words.codes.{code}.use"), - ); + let meaning = word(language, &format!("tools.http-status.words.codes.{code}.meaning")); + let usage = word(language, &format!("tools.http-status.words.codes.{code}.use")); let heading = word(language, &format!("tools.http-status.groups.{group}")); let mut named = Cell::text(name); if let Some(standing) = standing { - named = named.tag(word( - language, - &format!("tools.http-status.standing.{standing}"), - )); + named = named.tag(word(language, &format!("tools.http-status.standing.{standing}"))); } let mut said = Cell::text(meaning.clone()); if !usage.is_empty() { @@ -180,12 +136,7 @@ pub(crate) fn table(language: Language) -> Table { columns: columns_of( language, "tools.http-status.columns", - &[ - ("code", Some(0.07)), - ("name", Some(0.27)), - ("meaning", None), - ("by", Some(0.13)), - ], + &[("code", Some(0.07)), ("name", Some(0.27)), ("meaning", None), ("by", Some(0.13))], ), caption: keys::tools::http_status::NAME, placeholder: keys::tools::http_status::PLACEHOLDER, diff --git a/crates/ui/src/tools/catalogue/identifiers.rs b/crates/ui/src/tools/catalogue/identifiers.rs index 70b41181f..49ec285cb 100644 --- a/crates/ui/src/tools/catalogue/identifiers.rs +++ b/crates/ui/src/tools/catalogue/identifiers.rs @@ -5,9 +5,7 @@ use chrono::{DateTime, Local, Utc}; use egui::text::LayoutJob; use egui::{Key, Modifiers, Role, Sense, TextFormat, Ui, Vec2, WidgetInfo}; use engine::notes::language::Language as NoteLanguage; -use engine::tools::identifiers::{ - IdInspection, IdKind, IdentifiersRequest, NanoAlphabet, RandomPart, -}; +use engine::tools::identifiers::{IdInspection, IdKind, IdentifiersRequest, NanoAlphabet, RandomPart}; use i18n::{Language, Message, keys}; use serde_json::json; @@ -16,8 +14,7 @@ use crate::theme::icons::Icon; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - CopyValue, ResultRow, card, hint, label, named, number_field, problem, result_rows, - section_title, + CopyValue, ResultRow, card, hint, label, named, number_field, problem, result_rows, section_title, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, IconButton, Kind, Segmented, TextField, address, virtual_list}; @@ -71,18 +68,12 @@ pub(super) fn make() -> Box { } fn name_of(kind: IdKind) -> &'static str { - KINDS - .iter() - .find(|(it, _)| *it == kind) - .map_or("", |(_, name)| name) + KINDS.iter().find(|(it, _)| *it == kind).map_or("", |(_, name)| name) } /// The kinds whose letters carry no meaning in their case: hexadecimal and Crockford's base 32. fn is_caseless(kind: IdKind) -> bool { - matches!( - kind, - IdKind::UuidV4 | IdKind::UuidV7 | IdKind::Ulid | IdKind::ObjectId - ) + matches!(kind, IdKind::UuidV4 | IdKind::UuidV7 | IdKind::Ulid | IdKind::ObjectId) } fn is_uuid(kind: IdKind) -> bool { @@ -149,39 +140,21 @@ fn facts(ui: &mut Ui, inspection: &IdInspection, text: &str, language: Language) let id = json!(inspection); let id = id.get("kind").cloned().unwrap_or_default(); let recognised = named(language, "tools.identifiers.recognised", &id); - let path = format!( - "tools.identifiers.formats.{}", - id.as_str().unwrap_or_default() - ); + let path = format!("tools.identifiers.formats.{}", id.as_str().unwrap_or_default()); let characters = u32::try_from(text.trim().chars().count()).unwrap_or(u32::MAX); - let format = i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key).with("count", characters).text(language) - }); + let format = i18n::Key::find(&path) + .map_or_else(String::new, |key| Message::new(key).with("count", characters).text(language)); let mut rows = vec![(tr(words::FORMAT), format!("{recognised} · {format}"))]; - if let IdInspection::Uuid { - version, - variant, - nil, - .. - } = inspection - { - let shown = if *nil { - tr(words::NIL) - } else { - format!("v{version}") - }; + if let IdInspection::Uuid { version, variant, nil, .. } = inspection { + let shown = if *nil { tr(words::NIL) } else { format!("v{version}") }; rows.push((tr(words::VERSION), shown)); let shown = named(language, "tools.identifiers.variants", &json!(variant)); rows.push((tr(words::VARIANT), shown)); } let (created, random): (Option<&str>, Option<&RandomPart>) = match inspection { - IdInspection::Uuid { - created, random, .. - } => (created.as_deref(), random.as_ref()), + IdInspection::Uuid { created, random, .. } => (created.as_deref(), random.as_ref()), IdInspection::Ulid { created, random } - | IdInspection::ObjectId { - created, random, .. - } + | IdInspection::ObjectId { created, random, .. } | IdInspection::Ksuid { created, random } => (Some(created), Some(random)), IdInspection::CuidV1 { created } => (Some(created), None), _ => (None, None), @@ -203,10 +176,7 @@ fn facts(ui: &mut Ui, inspection: &IdInspection, text: &str, language: Language) rows.push((tr(words::COUNTER), counter.to_string())); } card(ui, "identifiers-facts", |ui| { - let lines: Vec<_> = rows - .iter() - .map(|(name, value)| ResultRow::new(name, value).reading()) - .collect(); + let lines: Vec<_> = rows.iter().map(|(name, value)| ResultRow::new(name, value).reading()).collect(); result_rows(ui, &lines, language); }); } @@ -235,14 +205,9 @@ impl IdentifiersTool { let tr = |key| i18n::translate(language, key, &[]); Segmented::new(&KINDS, "identifiers-kind").show(ui, &mut self.kind); let id = json!(self.kind); - let path = format!( - "tools.identifiers.hints.{}", - id.as_str().unwrap_or_default() - ); + let path = format!("tools.identifiers.hints.{}", id.as_str().unwrap_or_default()); let about = i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key) - .with("name", name_of(self.kind)) - .text(language) + Message::new(key).with("name", name_of(self.kind)).text(language) }); let said = hint(ui, &about); address(ui, &said, "identifiers-hint"); @@ -252,19 +217,13 @@ impl IdentifiersTool { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let fewer = tr(words::FEWER); - if IconButton::new(Icon::Minus, &fewer, "identifiers-fewer") - .show(ui) - .clicked() - { + if IconButton::new(Icon::Minus, &fewer, "identifiers-fewer").show(ui).clicked() { self.step(-1); } let name = tr(words::COUNT); number_field(ui, &mut self.count, &name, "identifiers-count"); let more = tr(words::MORE); - if IconButton::new(Icon::Plus, &more, "identifiers-more") - .show(ui) - .clicked() - { + if IconButton::new(Icon::Plus, &more, "identifiers-more").show(ui).clicked() { self.step(1); } if is_caseless(self.kind) { @@ -296,10 +255,7 @@ impl IdentifiersTool { let tr = |key| i18n::translate(language, key, &[]); let options = [ (NanoAlphabet::UrlSafe, tr(words::alphabets::URL_SAFE)), - ( - NanoAlphabet::Alphanumeric, - tr(words::alphabets::ALPHANUMERIC), - ), + (NanoAlphabet::Alphanumeric, tr(words::alphabets::ALPHANUMERIC)), (NanoAlphabet::HexLower, tr(words::alphabets::HEX_LOWER)), (NanoAlphabet::Digits, tr(words::alphabets::DIGITS)), ]; @@ -319,14 +275,9 @@ impl IdentifiersTool { let Some(ids) = self.generated.value() else { return; }; - let uuid = self - .generated - .answered() - .is_some_and(|(it, _)| is_uuid(it.kind)); + let uuid = self.generated.answered().is_some_and(|(it, _)| is_uuid(it.kind)); let count = u32::try_from(ids.len()).unwrap_or(u32::MAX); - let counted = Message::new(words::COUNTED) - .with("count", count) - .text(language); + let counted = Message::new(words::COUNTED).with("count", count).text(language); let all = ids.join("\n"); crate::tools::ui::section_head(ui, &counted, |ui| { CopyValue::new(&all, &tr(words::ALL), language) @@ -355,16 +306,12 @@ impl IdentifiersTool { match self.inspection.value() { Some(IdInspection::Possible { kinds }) => { let names: Vec<&str> = kinds.iter().map(|it| name_of(*it)).collect(); - let said = Message::new(words::POSSIBLE) - .with("kinds", names.join(" / ")) - .text(language); + let said = Message::new(words::POSSIBLE).with("kinds", names.join(" / ")).text(language); let said = hint(ui, &said); address(ui, &said, "identifiers-possible"); } Some(IdInspection::OutOfRange { id }) => { - let said = Message::new(words::OUT_OF_RANGE) - .with("kind", name_of(*id)) - .text(language); + let said = Message::new(words::OUT_OF_RANGE).with("kind", name_of(*id)).text(language); problem(ui, &said, "identifiers-out-of-range"); } Some(IdInspection::Unrecognised) => { @@ -382,12 +329,10 @@ impl IdentifiersTool { impl Tool for IdentifiersTool { fn update(&mut self, turn: &mut Turn<'_>) { let request = self.request(); - self.generated.update(turn, request, |backend, (asked, _)| { - api::tools::generate_identifiers(backend, asked) - }); + self.generated + .update(turn, request, |backend, (asked, _)| api::tools::generate_identifiers(backend, asked)); let read = (!self.checked.trim().is_empty()).then(|| self.checked.clone()); - self.inspection - .update(turn, read, api::tools::inspect_identifier); + self.inspection.update(turn, read, api::tools::inspect_identifier); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -447,10 +392,7 @@ mod tests { #[test] fn an_instant_reads_in_any_language() { - assert_eq!( - readable("2024-09-25T23:05:01.488Z"), - "2024-09-25 23:05:01.488 UTC" - ); + assert_eq!(readable("2024-09-25T23:05:01.488Z"), "2024-09-25 23:05:01.488 UTC"); } #[test] diff --git a/crates/ui/src/tools/catalogue/identity.rs b/crates/ui/src/tools/catalogue/identity.rs index 43197585e..6854606d8 100644 --- a/crates/ui/src/tools/catalogue/identity.rs +++ b/crates/ui/src/tools/catalogue/identity.rs @@ -10,8 +10,8 @@ use chrono::{Datelike, Local, NaiveDate}; use egui::{CornerRadius, FontId, Sense, Stroke, Ui, Vec2}; use engine::notes::language::Language as NoteLanguage; use engine::tools::identity::{ - AGES, Country, CsvSeparator, Identifier, IdentifierKind, Identity, IdentityAnswer, - IdentityRequest, MAX_PEOPLE, PeopleBatch, PeopleExport, PeopleFormat, Sex, + AGES, Country, CsvSeparator, Identifier, IdentifierKind, Identity, IdentityAnswer, IdentityRequest, + MAX_PEOPLE, PeopleBatch, PeopleExport, PeopleFormat, Sex, }; use i18n::{Language, Message, keys}; use serde_json::json; @@ -22,13 +22,11 @@ use crate::theme::icons::Icon; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - CopyValue, ResultRow, card, columns, copies, copies_width, group_title, hint, label, line, - named, number_field, paragraph, result_rows, section_head, section_title, + CopyValue, ResultRow, card, columns, copies, copies_width, group_title, hint, label, line, named, + number_field, paragraph, result_rows, section_head, section_title, }; use crate::tools::{Action, Drawn, Tool, ToolAction, ToolResult}; -use crate::widgets::{ - self, Button, Chip, ChoiceMenu, IconButton, Segmented, TextField, address, tooltip, -}; +use crate::widgets::{self, Button, Chip, ChoiceMenu, IconButton, Segmented, TextField, address, tooltip}; /// What the options are back to on « Clear », and what a first visit opens on. const AGES_AT_FIRST: (u32, u32) = (18, 80); @@ -74,19 +72,11 @@ struct Row { impl Row { fn new(language: Language, name: i18n::Key, value: &str) -> Self { - Self { - name: i18n::translate(language, name, &[]), - value: value.to_owned(), - raw: None, - mark: None, - } + Self { name: i18n::translate(language, name, &[]), value: value.to_owned(), raw: None, mark: None } } fn number(language: Language, name: i18n::Key, value: &str) -> Self { - Self { - raw: Some(api::tools::raw_number(value)), - ..Self::new(language, name, value) - } + Self { raw: Some(api::tools::raw_number(value)), ..Self::new(language, name, value) } } fn marked(mut self, mark: Option) -> Self { @@ -141,10 +131,7 @@ pub(super) fn make() -> Box { /// The age typed, or the one in force while the field is being written. fn age(typed: &str, otherwise: u32) -> u32 { - typed - .trim() - .parse() - .map_or(otherwise, |age: u32| age.clamp(AGES.0, AGES.1)) + typed.trim().parse().map_or(otherwise, |age: u32| age.clamp(AGES.0, AGES.1)) } /// The whole years between a birth date and today, read as calendar dates. @@ -167,19 +154,11 @@ fn country_name(language: Language, country: Country) -> String { named(language, "tools.identity.countries", &json!(country)) } -fn identifier_rows( - identifiers: &[Identifier], - unkeyed: &[IdentifierKind], - language: Language, -) -> Vec { +fn identifier_rows(identifiers: &[Identifier], unkeyed: &[IdentifierKind], language: Language) -> Vec { identifiers .iter() .map(|identifier| Row { - name: named( - language, - "tools.identity.identifiers", - &json!(identifier.kind), - ), + name: named(language, "tools.identity.identifiers", &json!(identifier.kind)), value: identifier.value.clone(), raw: Some(api::tools::raw_number(&identifier.value)), mark: unkeyed.contains(&identifier.kind).then_some(Mark::Unkeyed), @@ -218,11 +197,7 @@ fn company_rows(answer: &IdentityAnswer, language: Language) -> Vec { let company = &answer.person.company; let name = keys::tools::identity::fields::COMPANY; let mut rows = vec![Row::new(language, name, &company.name)]; - rows.extend(identifier_rows( - &company.identifiers, - &answer.unkeyed, - language, - )); + rows.extend(identifier_rows(&company.identifiers, &answer.unkeyed, language)); rows } @@ -240,9 +215,8 @@ fn block(ui: &mut Ui, id: &str, title: i18n::Key, rows: &[Row], language: Langua let marks: Vec = rows .iter() .map(|row| { - row.mark.map_or_else(String::new, |mark| { - i18n::translate(language, mark.word(), &[]) - }) + row.mark + .map_or_else(String::new, |mark| i18n::translate(language, mark.word(), &[])) }) .collect(); card(ui, &format!("identity-block-{id}"), |ui| { @@ -287,9 +261,7 @@ fn fact( let ink = palette(ui.ctx()).text_0; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; - let copy_room = raw.map_or(0.0, |_| { - copies_width(ui, (value, raw), language) + gap::CONTROLS - }); + let copy_room = raw.map_or(0.0, |_| copies_width(ui, (value, raw), language) + gap::CONTROLS); let room = ui.available_width() - copy_room; ui.allocate_ui(Vec2::new(room, 0.0), |ui| { let said = paragraph(ui, value, style, ink); @@ -324,8 +296,7 @@ fn draw_monogram(ui: &mut Ui, letters: &str) { let (rect, response) = ui.allocate_exact_size(side, Sense::hover()); let corner = CornerRadius::same(radius::CARD); let edge = Stroke::new(1.0, p.line); - ui.painter() - .rect(rect, corner, p.bg_2, edge, egui::StrokeKind::Inside); + ui.painter().rect(rect, corner, p.bg_2, edge, egui::StrokeKind::Inside); let shown = widgets::wrapped(ui, letters, (font::HERO, 700.0), p.text_2, MONOGRAM); let at = rect.center() - shown.size() / 2.0; shown.paint(ui, at, p.text_2); @@ -337,11 +308,7 @@ fn card_head(ui: &mut Ui, person: &Identity, language: Language) { let kind = i18n::translate(language, keys::tools::identity::CARD_KIND, &[]); egui::Frame::new() .fill(p.amber_text.gamma_multiply(0.06)) - .corner_radius(CornerRadius { - nw: 14, - ne: 14, - ..CornerRadius::ZERO - }) + .corner_radius(CornerRadius { nw: 14, ne: 14, ..CornerRadius::ZERO }) .inner_margin(gap::margin(gap::BLOCKS, gap::INSET)) .show(ui, |ui| { ui.horizontal(|ui| { @@ -364,80 +331,32 @@ fn card_facts(ui: &mut Ui, answer: &IdentityAnswer, today: NaiveDate, language: let (given, copied) = (person.given_names.join(", "), person.given_names.join(" ")); let (name, shown) = (tr(words::fields::SURNAME), person.surname.to_uppercase()); let surname = (name.as_str(), shown.as_str()); - fact( - ui, - surname, - (font::DISPLAY, 700.0), - Some(&person.surname), - "identity-surname", - language, - ); + fact(ui, surname, (font::DISPLAY, 700.0), Some(&person.surname), "identity-surname", language); let names = tr(words::fields::GIVEN_NAMES); let names = (names.as_str(), given.as_str()); - fact( - ui, - names, - (font::HEADING, 600.0), - Some(&copied), - "identity-given", - language, - ); + fact(ui, names, (font::HEADING, 600.0), Some(&copied), "identity-given", language); let sex = named(language, "tools.identity.sexes", &json!(person.sex)); - let nationality = named( - language, - "tools.identity.nationalities", - &json!(person.country), - ); + let nationality = named(language, "tools.identity.nationalities", &json!(person.country)); let place = format!("{} ({})", person.birth.city, person.birth.region); let born = person.birth.date.parse().ok().map_or_else( || person.birth.date.clone(), |birth| { - let aged = Message::new(words::AGED) - .with("count", age_on(birth, today)) - .text(language); + let aged = Message::new(words::AGED).with("count", age_on(birth, today)).text(language); format!("{} {aged}", i18n::format::date_long(birth, language)) }, ); let short = (font::READING, 500.0); ui.columns(2, |halves| { let name = tr(words::SEX); - fact( - &mut halves[0], - (&name, &sex), - short, - None, - "identity-card-sex", - language, - ); + fact(&mut halves[0], (&name, &sex), short, None, "identity-card-sex", language); let name = tr(words::fields::NATIONALITY); let shown = (name.as_str(), nationality.as_str()); - fact( - &mut halves[1], - shown, - short, - None, - "identity-nationality", - language, - ); + fact(&mut halves[1], shown, short, None, "identity-nationality", language); let name = tr(words::fields::BORN_ON); let copied = Some(person.birth.date.as_str()); - fact( - &mut halves[0], - (&name, &born), - short, - copied, - "identity-birth", - language, - ); + fact(&mut halves[0], (&name, &born), short, copied, "identity-birth", language); let name = tr(words::fields::BORN_IN); - fact( - &mut halves[1], - (&name, &place), - short, - None, - "identity-birth-place", - language, - ); + fact(&mut halves[1], (&name, &place), short, None, "identity-birth-place", language); }); for row in identifier_rows(&person.identifiers, &answer.unkeyed, language) { number(ui, &row, "identity-personal", language); @@ -475,14 +394,8 @@ impl IdentityTool { IdentityRequest { country: self.country, sex: self.sex, - age_min: age( - &self.age_min, - asked.map_or(AGES_AT_FIRST.0, |it| it.age_min), - ), - age_max: age( - &self.age_max, - asked.map_or(AGES_AT_FIRST.1, |it| it.age_max), - ), + age_min: age(&self.age_min, asked.map_or(AGES_AT_FIRST.0, |it| it.age_min)), + age_max: age(&self.age_max, asked.map_or(AGES_AT_FIRST.1, |it| it.age_max)), seed: (!seed.is_empty()).then(|| seed.to_owned()), } } @@ -513,19 +426,9 @@ impl IdentityTool { Segmented::new(&sexes, "identity-sex").show(ui, &mut self.sex); label(ui, &tr(words::AGE)); line(ui, |ui| { - number_field( - ui, - &mut self.age_min, - &tr(words::AGE_MIN), - "identity-age-min", - ); + number_field(ui, &mut self.age_min, &tr(words::AGE_MIN), "identity-age-min"); hint(ui, "-"); - number_field( - ui, - &mut self.age_max, - &tr(words::AGE_MAX), - "identity-age-max", - ); + number_field(ui, &mut self.age_max, &tr(words::AGE_MAX), "identity-age-max"); hint(ui, &tr(words::YEARS)); }); self.seed_row(ui, language); @@ -550,9 +453,7 @@ impl IdentityTool { .show(ui); }); if !pinned && let Some(used) = &used { - let said = Message::new(words::SEED_USED) - .with("seed", used.as_str()) - .text(language); + let said = Message::new(words::SEED_USED).with("seed", used.as_str()).text(language); let said = hint(ui, &said); address(ui, &said, "identity-seed-used"); } @@ -560,17 +461,9 @@ impl IdentityTool { let pin = IconButton::new(Icon::Pin, &tr(words::PIN_SEED), "identity-pin-seed") .pressed(pinned) .show(ui); - let why = tr(if pinned { - words::FREE_SEED - } else { - words::KEEP_SEED - }); + let why = tr(if pinned { words::FREE_SEED } else { words::KEEP_SEED }); if tooltip(pin, &why).clicked() { - self.seed = if pinned { - String::new() - } else { - used.clone().unwrap_or_default() - }; + self.seed = if pinned { String::new() } else { used.clone().unwrap_or_default() }; } } }); @@ -586,10 +479,8 @@ impl IdentityTool { let tr = |key| i18n::translate(language, key, &[]); ui.add_space(gap::CONTROLS); section_title(ui, &tr(words::BATCH)); - let formats = [ - (PeopleFormat::Json, tr(words::formats::JSON)), - (PeopleFormat::Csv, tr(words::formats::CSV)), - ]; + let formats = + [(PeopleFormat::Json, tr(words::formats::JSON)), (PeopleFormat::Csv, tr(words::formats::CSV))]; let formats = formats.each_ref().map(|(id, name)| (*id, name.as_str())); line(ui, |ui| { let name = tr(words::PEOPLE); @@ -600,10 +491,7 @@ impl IdentityTool { if self.format == PeopleFormat::Csv { self.separator_choice(ui, drawn); } - if Button::new(&tr(words::EXPORT), "identity-export") - .show(ui) - .clicked() - { + if Button::new(&tr(words::EXPORT), "identity-export").show(ui).clicked() { self.wants_export = true; } label(ui, &tr(words::BATCH_COUNTRIES)); @@ -659,20 +547,8 @@ impl IdentityTool { let Some(answer) = self.drawn() else { return }; let today = drawn.now.with_timezone(&Local).date_naive(); person_card(ui, answer, today, language); - block( - ui, - "contact", - words::blocks::CONTACT, - &contact_rows(answer, language), - language, - ); - block( - ui, - "bank", - words::blocks::BANK, - &bank_rows(answer, language), - language, - ); + block(ui, "contact", words::blocks::CONTACT, &contact_rows(answer, language), language); + block(ui, "bank", words::blocks::BANK, &bank_rows(answer, language), language); let rows = company_rows(answer, language); block(ui, "company", words::blocks::COMPANY, &rows, language); if answer.person.company.identifiers.is_empty() { @@ -721,9 +597,9 @@ impl IdentityTool { let Some(answer) = pending.poll() else { return }; self.exporting = None; match answer { - Ok(PeopleExport::Written { people }) => turn.status.report( - Message::new(keys::tools::identity::EXPORTED).with("count", people), - ), + Ok(PeopleExport::Written { people }) => turn + .status + .report(Message::new(keys::tools::identity::EXPORTED).with("count", people)), Ok(PeopleExport::Failed { problem: reason }) => { let path = format!("tools.files.{}", json!(reason).as_str().unwrap_or("")); if let Some(key) = i18n::Key::find(&path) { @@ -743,10 +619,9 @@ impl Tool for IdentityTool { self.separator = turn.csv_separator; self.follow_export(turn); let asked = (self.request(), self.draw); - self.answer - .update(turn, Some(asked), |backend, (request, _)| { - api::tools::generate_identity(backend, request) - }); + self.answer.update(turn, Some(asked), |backend, (request, _)| { + api::tools::generate_identity(backend, request) + }); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -772,11 +647,7 @@ impl Tool for IdentityTool { } fn actions(&self) -> Vec { - vec![ToolAction { - id: "draw", - label: keys::tools::identity::AGAIN, - enabled: true, - }] + vec![ToolAction { id: "draw", label: keys::tools::identity::AGAIN, enabled: true }] } fn run_action(&mut self, id: &str, _: &egui::Context) { diff --git a/crates/ui/src/tools/catalogue/json_generator.rs b/crates/ui/src/tools/catalogue/json_generator.rs index f18244ade..d251e0510 100644 --- a/crates/ui/src/tools/catalogue/json_generator.rs +++ b/crates/ui/src/tools/catalogue/json_generator.rs @@ -11,8 +11,8 @@ use crate::theme::icons::Icon; use crate::tools::live::{Live, Turn}; use crate::tools::ui::note_picker::PickedNote; use crate::tools::ui::{ - CopyValue, code_output, columns, hint, label, line, note_import, number_field, problem, - section_head, text_area, + CopyValue, code_output, columns, hint, label, line, note_import, number_field, problem, section_head, + text_area, }; use crate::tools::{Drawn, Tool, ToolAction, ToolResult}; use crate::widgets::{Button, IconButton, Segmented, TextField, address, tooltip}; @@ -110,13 +110,7 @@ impl JsonGeneratorTool { address(ui, &said, "json-generator-expects"); let name = tr(words::INPUT_LABEL); let placeholder = tr(placeholder); - text_area( - ui, - &mut self.text, - (&name, "json-generator-input"), - &placeholder, - 14, - ); + text_area(ui, &mut self.text, (&name, "json-generator-input"), &placeholder, 14); self.refusal(ui, language); self.seed_row(ui, language); } @@ -169,11 +163,7 @@ impl JsonGeneratorTool { .show(ui); }); if pinned || drawn.is_some() { - let key = if pinned { - words::FREE_SEED - } else { - words::KEEP_SEED - }; + let key = if pinned { words::FREE_SEED } else { words::KEEP_SEED }; let why = tr(key); let pin = IconButton::new(Icon::Pin, &why, "json-generator-keep-seed") .pressed(pinned) @@ -190,9 +180,7 @@ impl JsonGeneratorTool { let said = hint(ui, &tr(words::SEED_PINNED)); address(ui, &said, "json-generator-seed-pinned"); } else if let Some(seed) = drawn { - let words = Message::new(words::SEED_USED) - .with("seed", seed) - .text(language); + let words = Message::new(words::SEED_USED).with("seed", seed).text(language); let said = hint(ui, &words); address(ui, &said, "json-generator-seed-used"); } @@ -203,10 +191,7 @@ impl JsonGeneratorTool { let language = drawn.language; let tr = |key| i18n::translate(language, key, &[]); let name = tr(words::DOCUMENTS); - let Some(GenerateAnswer::Generated { - text, unsupported, .. - }) = self.answer.value() - else { + let Some(GenerateAnswer::Generated { text, unsupported, .. }) = self.answer.value() else { section_head(ui, &name, |_| {}); if !matches!(self.answer.value(), Some(GenerateAnswer::AnExample)) { let said = hint(ui, &tr(words::EMPTY)); @@ -232,9 +217,8 @@ impl JsonGeneratorTool { impl Tool for JsonGeneratorTool { fn update(&mut self, turn: &mut Turn<'_>) { let request = self.request(); - self.answer.update(turn, request, |backend, (asked, _)| { - api::tools::generate_json(backend, asked) - }); + self.answer + .update(turn, request, |backend, (asked, _)| api::tools::generate_json(backend, asked)); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -261,11 +245,7 @@ impl Tool for JsonGeneratorTool { /// Never disabled: with a seed pinned it draws the same documents, and the page says so. fn actions(&self) -> Vec { - vec![ToolAction { - id: "draw", - label: keys::tools::json_generator::AGAIN, - enabled: true, - }] + vec![ToolAction { id: "draw", label: keys::tools::json_generator::AGAIN, enabled: true }] } fn run_action(&mut self, id: &str, _: &egui::Context) { diff --git a/crates/ui/src/tools/catalogue/jwt.rs b/crates/ui/src/tools/catalogue/jwt.rs index 87fae549b..b5b44fdde 100644 --- a/crates/ui/src/tools/catalogue/jwt.rs +++ b/crates/ui/src/tools/catalogue/jwt.rs @@ -14,8 +14,8 @@ use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - CopyValue, ResultRow, card, check, columns, hint, label, named, paragraph, problem, - result_rows, section_head, section_title, text_area, + CopyValue, ResultRow, card, check, columns, hint, label, named, paragraph, problem, result_rows, + section_head, section_title, text_area, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{TextField, address}; @@ -50,35 +50,27 @@ fn span(claim: &DatedClaim, now: DateTime) -> Option { fn malformed_words(answer: &JwtAnswer, language: Language) -> Option { use keys::tools::jwt::problems; - let JwtAnswer::Malformed { - problem: reason, - segment, - segments, - at, - } = answer - else { + let JwtAnswer::Malformed { problem: reason, segment, segments, at } = answer else { return None; }; let tr = |key| i18n::translate(language, key, &[]); let segment = named(language, "tools.jwt.segments", &json!(segment)); Some(match (reason, at) { (JwtProblem::SegmentCount, _) if *segments == 5 => tr(problems::JWE), - (JwtProblem::SegmentCount, _) => Message::new(problems::SEGMENT_COUNT) - .with("count", *segments) - .text(language), + (JwtProblem::SegmentCount, _) => { + Message::new(problems::SEGMENT_COUNT).with("count", *segments).text(language) + } (JwtProblem::NotBase64, Some(at)) => Message::new(problems::NOT_BASE64_AT) .with("segment", segment) .with("at", *at) .text(language), - (JwtProblem::NotBase64, None) => Message::new(problems::NOT_BASE64) - .with("segment", segment) - .text(language), - (JwtProblem::NotJson, _) => Message::new(problems::NOT_JSON) - .with("segment", segment) - .text(language), - (JwtProblem::NotObject, _) => Message::new(problems::NOT_OBJECT) - .with("segment", segment) - .text(language), + (JwtProblem::NotBase64, None) => { + Message::new(problems::NOT_BASE64).with("segment", segment).text(language) + } + (JwtProblem::NotJson, _) => Message::new(problems::NOT_JSON).with("segment", segment).text(language), + (JwtProblem::NotObject, _) => { + Message::new(problems::NOT_OBJECT).with("segment", segment).text(language) + } }) } @@ -119,11 +111,7 @@ impl JwtTool { let words = tr(keys::tools::jwt::SECRET_BASE64); check(ui, &mut self.secret_is_base64, &words, "jwt-secret-base64"); hint(ui, &tr(keys::tools::jwt::FORGOTTEN)); - if let Some(words) = self - .answer - .value() - .and_then(|it| malformed_words(it, language)) - { + if let Some(words) = self.answer.value().and_then(|it| malformed_words(it, language)) { problem(ui, &words, "jwt-problem"); } } @@ -174,9 +162,7 @@ impl JwtTool { json!(verification).as_str().unwrap_or_default() )); let verdict = key.map_or_else(String::new, |key| { - Message::new(key) - .with("family", family_name.as_str()) - .text(language) + Message::new(key).with("family", family_name.as_str()).text(language) }); let said = paragraph(ui, &verdict, (font::BODY, 400.0), ink); address(ui, &said, "jwt-verification"); @@ -234,12 +220,7 @@ impl Tool for JwtTool { } fn result(&self, language: Language) -> Option { - let Some(JwtAnswer::Decoded { - document, - algorithm, - .. - }) = self.answer.value() - else { + let Some(JwtAnswer::Decoded { document, algorithm, .. }) = self.answer.value() else { return None; }; Some(ToolResult { diff --git a/crates/ui/src/tools/catalogue/line_breaks.rs b/crates/ui/src/tools/catalogue/line_breaks.rs index cfb8735ab..3d001699d 100644 --- a/crates/ui/src/tools/catalogue/line_breaks.rs +++ b/crates/ui/src/tools/catalogue/line_breaks.rs @@ -82,28 +82,18 @@ fn visible_lines(text: &str) -> (Vec>, usize) { Some(at) if rest[at..].starts_with("\r\n") => { (&rest[..at], Some(LineEnding::Crlf), &rest[at + 2..]) } - Some(at) if rest[at..].starts_with('\r') => { - (&rest[..at], Some(LineEnding::Cr), &rest[at + 1..]) - } + Some(at) if rest[at..].starts_with('\r') => (&rest[..at], Some(LineEnding::Cr), &rest[at + 1..]), Some(at) => (&rest[..at], Some(LineEnding::Lf), &rest[at + 1..]), }; let content = line.trim_end_matches([' ', '\t']); - lines.push(VisibleLine { - content, - trailing: &line[content.len()..], - ending, - }); + lines.push(VisibleLine { content, trailing: &line[content.len()..], ending }); if ending.is_none() { break; } rest = next; } // A text ending with a newline ends on an empty line with nothing after it: not a line. - if lines.len() > 1 - && lines - .last() - .is_some_and(|it| it.content.is_empty() && it.trailing.is_empty()) - { + if lines.len() > 1 && lines.last().is_some_and(|it| it.content.is_empty() && it.trailing.is_empty()) { lines.pop(); } let hidden = lines.len().saturating_sub(MAX_VISIBLE_LINES); @@ -127,10 +117,7 @@ fn line_view(ui: &mut Ui, text: &str, author_id: &str, language: Language) { let plain = TextFormat::simple(FontId::monospace(font::BODY), p.text_0); for line in &lines { job.append(line.content, 0.0, plain.clone()); - let blank = TextFormat { - background: p.red.gamma_multiply(0.2), - ..plain.clone() - }; + let blank = TextFormat { background: p.red.gamma_multiply(0.2), ..plain.clone() }; job.append(line.trailing, 0.0, blank); if let Some(ending) = line.ending { let ink = match ending { @@ -166,10 +153,7 @@ fn text_box(ui: &mut Ui, id: &str, content: impl FnOnce(&mut Ui)) { .show(ui, |ui| { ui.set_width(ui.available_width()); ui.set_min_height(ZONE_MIN); - egui::ScrollArea::vertical() - .id_salt(id) - .max_height(ZONE_MAX) - .show(ui, content); + egui::ScrollArea::vertical().id_salt(id).max_height(ZONE_MAX).show(ui, content); }); } @@ -328,10 +312,10 @@ impl Tool for LineBreaksTool { if std::mem::take(&mut self.wants_paste) { let clipboard = Arc::clone(turn.clipboard); let typed = self.typed.take(); - self.reading = - Some(turn.backend.compute(move |_| { - Ok(clipboard.text().filter(|text| !text.is_empty()).or(typed)) - })); + self.reading = Some( + turn.backend + .compute(move |_| Ok(clipboard.text().filter(|text| !text.is_empty()).or(typed))), + ); } if let Some(reading) = &mut self.reading && let Some(answer) = reading.poll() @@ -342,8 +326,7 @@ impl Tool for LineBreaksTool { } } let request = self.request(); - self.answer - .update(turn, request, api::tools::fix_line_breaks); + self.answer.update(turn, request, api::tools::fix_line_breaks); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -390,14 +373,7 @@ mod tests { let (lines, hidden) = visible_lines("one \r\ntwo\nthree\r"); assert_eq!(hidden, 0); - assert_eq!( - lines[0], - VisibleLine { - content: "one", - trailing: " ", - ending: Some(LineEnding::Crlf) - } - ); + assert_eq!(lines[0], VisibleLine { content: "one", trailing: " ", ending: Some(LineEnding::Crlf) }); assert_eq!(lines[1].ending, Some(LineEnding::Lf)); assert_eq!(lines[2].ending, Some(LineEnding::Cr)); assert_eq!(lines.len(), 3); diff --git a/crates/ui/src/tools/catalogue/lorem.rs b/crates/ui/src/tools/catalogue/lorem.rs index 3e9a07cf5..fb3259372 100644 --- a/crates/ui/src/tools/catalogue/lorem.rs +++ b/crates/ui/src/tools/catalogue/lorem.rs @@ -62,12 +62,7 @@ fn held_to(unit: LoremUnit) -> Key { impl LoremTool { fn request(&self) -> Option { let count = self.count.trim().parse().ok()?; - let request = LoremRequest { - unit: self.unit, - count, - opening: self.opening, - seed: None, - }; + let request = LoremRequest { unit: self.unit, count, opening: self.opening, seed: None }; Some((request, self.draw)) } @@ -97,9 +92,7 @@ impl LoremTool { return; }; if asked.count > answer.at_most { - let words = Message::new(held_to(asked.unit)) - .with("count", answer.at_most) - .text(language); + let words = Message::new(held_to(asked.unit)).with("count", answer.at_most).text(language); let said = hint(ui, &words); address(ui, &said, "lorem-held"); } @@ -111,9 +104,7 @@ impl LoremTool { }; let p = palette(ui.ctx()); let unit = self.answer.answered().map_or(self.unit, |(it, _)| it.unit); - let words = Message::new(counted(unit)) - .with("count", answer.count) - .text(language); + let words = Message::new(counted(unit)).with("count", answer.count).text(language); let again = i18n::translate(language, keys::tools::lorem::AGAIN, &[]); let mut drawn_again = false; egui::Frame::new() @@ -139,9 +130,7 @@ impl LoremTool { .id_salt("lorem-text") .auto_shrink(false) .show(ui, |ui| { - let text = egui::RichText::new(&answer.text) - .size(font::READING) - .color(p.text_0); + let text = egui::RichText::new(&answer.text).size(font::READING).color(p.text_0); let shown = ui.add(egui::Label::new(text).wrap()); address(ui, &shown, "lorem-output"); }); @@ -155,9 +144,8 @@ impl LoremTool { impl Tool for LoremTool { fn update(&mut self, turn: &mut Turn<'_>) { let request = self.request(); - self.answer.update(turn, request, |backend, (asked, _)| { - api::tools::lorem(backend, asked) - }); + self.answer + .update(turn, request, |backend, (asked, _)| api::tools::lorem(backend, asked)); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { diff --git a/crates/ui/src/tools/catalogue/markdown_sheet.rs b/crates/ui/src/tools/catalogue/markdown_sheet.rs index d0b5505f4..c11be6a20 100644 --- a/crates/ui/src/tools/catalogue/markdown_sheet.rs +++ b/crates/ui/src/tools/catalogue/markdown_sheet.rs @@ -7,9 +7,7 @@ use super::reference::{Reference, Table, columns_of, facts, groups_of, text, wor use crate::tools::Tool; use crate::tools::ui::{Cell, ReferenceRow}; -const GROUPS: [&str; 7] = [ - "headings", "emphasis", "lists", "links", "code", "blocks", "raw", -]; +const GROUPS: [&str; 7] = ["headings", "emphasis", "lists", "links", "code", "blocks", "raw"]; const WIDE_CARD: f32 = 760.0; /// A space that matters is drawn so, and copied as a space. const SPACE: char = '␣'; @@ -18,19 +16,12 @@ const SPACE: char = '␣'; const ENTRIES: &str = include_str!("facts/markdown-sheet.json"); fn works(yes: bool) -> Cell { - if yes { - Cell::checked() - } else { - Cell::text("—") - } + if yes { Cell::checked() } else { Cell::text("—") } } fn row(entry: &Value, language: Language) -> ReferenceRow { let (syntax, group) = (text(entry, "syntax"), text(entry, "group")); - let what = word( - language, - &format!("tools.markdown-sheet.words.entries.{syntax}"), - ); + let what = word(language, &format!("tools.markdown-sheet.words.entries.{syntax}")); let heading = word(language, &format!("tools.markdown-sheet.groups.{group}")); let cells = vec![ Cell::mono(syntax), diff --git a/crates/ui/src/tools/catalogue/mime_types.rs b/crates/ui/src/tools/catalogue/mime_types.rs index fd9b3c1f3..fb9d219d0 100644 --- a/crates/ui/src/tools/catalogue/mime_types.rs +++ b/crates/ui/src/tools/catalogue/mime_types.rs @@ -7,15 +7,7 @@ use crate::tools::Tool; use crate::tools::ui::{Cell, Group, ReferenceRow}; /// Named by themselves: a type's first word is the same in every language. -const GROUPS: [&str; 7] = [ - "text", - "application", - "image", - "audio", - "video", - "font", - "multipart", -]; +const GROUPS: [&str; 7] = ["text", "application", "image", "audio", "video", "font", "multipart"]; const WIDE_CARD: f32 = 760.0; /// A type and its extensions, the most common first; none for a type that never sits in a file. @@ -49,20 +41,11 @@ const TYPES: [(&str, &[&str]); 91] = [ ("application/rtf", &[".rtf"]), ("application/epub+zip", &[".epub"]), ("application/msword", &[".doc"]), - ( - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - &[".docx"], - ), + ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", &[".docx"]), ("application/vnd.ms-excel", &[".xls"]), - ( - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - &[".xlsx"], - ), + ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", &[".xlsx"]), ("application/vnd.ms-powerpoint", &[".ppt"]), - ( - "application/vnd.openxmlformats-officedocument.presentationml.presentation", - &[".pptx"], - ), + ("application/vnd.openxmlformats-officedocument.presentationml.presentation", &[".pptx"]), ("application/vnd.oasis.opendocument.text", &[".odt"]), ("application/vnd.oasis.opendocument.spreadsheet", &[".ods"]), ("application/zip", &[".zip"]), @@ -75,10 +58,7 @@ const TYPES: [(&str, &[&str]); 91] = [ ("application/vnd.rar", &[".rar"]), ("application/java-archive", &[".jar"]), ("application/vnd.android.package-archive", &[".apk"]), - ( - "application/vnd.microsoft.portable-executable", - &[".exe", ".dll"], - ), + ("application/vnd.microsoft.portable-executable", &[".exe", ".dll"]), ("application/vnd.debian.binary-package", &[".deb"]), ("application/x-sh", &[".sh"]), ("application/vnd.ms-fontobject", &[".eot"]), @@ -130,11 +110,7 @@ fn row((mime, extensions): (&str, &[&str]), language: Language) -> ReferenceRow let description = word(language, &format!("tools.mime-types.words.types.{mime}")); let group = mime.split('/').next().unwrap_or_default(); let shown = if extensions.is_empty() { - Cell::mono(i18n::translate( - language, - keys::tools::mime_types::NO_EXTENSION, - &[], - )) + Cell::mono(i18n::translate(language, keys::tools::mime_types::NO_EXTENSION, &[])) } else { Cell::chips(extensions.iter().map(|it| (*it).to_owned()).collect()) }; @@ -154,19 +130,12 @@ pub(crate) fn table(language: Language) -> Table { rows: TYPES.iter().map(|it| row(*it, language)).collect(), groups: GROUPS .iter() - .map(|id| Group { - id: (*id).to_owned(), - label: (*id).to_owned(), - }) + .map(|id| Group { id: (*id).to_owned(), label: (*id).to_owned() }) .collect(), columns: columns_of( language, "tools.mime-types.columns", - &[ - ("type", Some(0.36)), - ("extensions", Some(0.24)), - ("description", None), - ], + &[("type", Some(0.36)), ("extensions", Some(0.24)), ("description", None)], ), caption: keys::tools::mime_types::NAME, placeholder: keys::tools::mime_types::PLACEHOLDER, diff --git a/crates/ui/src/tools/catalogue/mustache_sheet.rs b/crates/ui/src/tools/catalogue/mustache_sheet.rs index c121b0672..ca24abec1 100644 --- a/crates/ui/src/tools/catalogue/mustache_sheet.rs +++ b/crates/ui/src/tools/catalogue/mustache_sheet.rs @@ -15,10 +15,7 @@ const ENTRIES: &str = include_str!("facts/mustache-sheet.json"); fn row(entry: &Value, language: Language) -> ReferenceRow { let (syntax, group) = (text(entry, "syntax"), text(entry, "group")); - let what = word( - language, - &format!("tools.mustache-sheet.words.entries.{syntax}"), - ); + let what = word(language, &format!("tools.mustache-sheet.words.entries.{syntax}")); let heading = word(language, &format!("tools.mustache-sheet.groups.{group}")); let with = i18n::translate(language, keys::tools::mustache_sheet::WITH, &[]); let example = Cell::mono(text(entry, "template")) @@ -37,11 +34,7 @@ pub(crate) fn table(language: Language) -> Table { columns: columns_of( language, "tools.mustache-sheet.columns", - &[ - ("syntax", Some(0.25)), - ("what", Some(0.32)), - ("example", None), - ], + &[("syntax", Some(0.25)), ("what", Some(0.32)), ("example", None)], ), caption: keys::tools::mustache_sheet::NAME, placeholder: keys::tools::mustache_sheet::PLACEHOLDER, diff --git a/crates/ui/src/tools/catalogue/password.rs b/crates/ui/src/tools/catalogue/password.rs index 930793048..9b77649df 100644 --- a/crates/ui/src/tools/catalogue/password.rs +++ b/crates/ui/src/tools/catalogue/password.rs @@ -11,9 +11,7 @@ use serde_json::json; use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; -use crate::tools::ui::{ - OutputRow, check, columns, label, named, number_field, problem, section_title, -}; +use crate::tools::ui::{OutputRow, check, columns, label, named, number_field, problem, section_title}; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, Kind, address}; @@ -27,13 +25,8 @@ const SETS: [(CharacterSet, &str, &str); 4] = [ (CharacterSet::Symbols, "symbols", "!#$"), ]; -const STRENGTHS: [Strength; 5] = [ - Strength::VeryWeak, - Strength::Weak, - Strength::Fair, - Strength::Strong, - Strength::VeryStrong, -]; +const STRENGTHS: [Strength; 5] = + [Strength::VeryWeak, Strength::Weak, Strength::Fair, Strength::Strong, Strength::VeryStrong]; const LENGTH: (u32, u32) = (8, 64); @@ -96,12 +89,9 @@ impl PasswordTool { let p = palette(ui.ctx()); ui.spacing_mut().slider_width = (ui.available_width() - FIELD_ROOM).max(80.0); ui.visuals_mut().selection.bg_fill = p.amber_fill; - let slider = egui::Slider::new(&mut length, range) - .show_value(false) - .trailing_fill(true); + let slider = egui::Slider::new(&mut length, range).show_value(false).trailing_fill(true); let moved = ui.add(slider); - ui.ctx() - .accesskit_node_builder(moved.id, |node| node.set_label(name.clone())); + ui.ctx().accesskit_node_builder(moved.id, |node| node.set_label(name.clone())); if moved.changed() { self.length = length.to_string(); } @@ -111,31 +101,17 @@ impl PasswordTool { for (at, (_, id, sample)) in SETS.iter().enumerate() { let words = named(language, "tools.password.setNames", &json!(id)); let words = format!("{words} {sample}"); - check( - ui, - &mut self.sets[at], - &words, - &format!("password-set-{id}"), - ); + check(ui, &mut self.sets[at], &words, &format!("password-set-{id}")); } let words = format!("{} l 1 I 0 O |", tr(keys::tools::password::LOOK_ALIKES)); - check( - ui, - &mut self.avoid_look_alikes, - &words, - "password-look-alikes", - ); + check(ui, &mut self.avoid_look_alikes, &words, "password-look-alikes"); let name = tr(keys::tools::password::COUNT); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::GROUPS; label(ui, &name); number_field(ui, &mut self.count, &name, "password-count"); let words = tr(keys::tools::password::GENERATE); - if Button::new(&words, "password-generate") - .kind(Kind::Filled) - .show(ui) - .clicked() - { + if Button::new(&words, "password-generate").kind(Kind::Filled).show(ui).clicked() { self.draw += 1; } }); @@ -146,11 +122,7 @@ impl PasswordTool { let tr = |key| i18n::translate(language, key, &[]); section_title(ui, &tr(keys::tools::password::PASSWORDS)); match self.answer.value() { - Some(PasswordAnswer::Generated { - passwords, - entropy_bits, - strength, - }) => { + Some(PasswordAnswer::Generated { passwords, entropy_bits, strength }) => { strength_bar(ui, *entropy_bits, *strength, language); for (at, password) in passwords.iter().enumerate() { OutputRow::new(&format!("#{}", at + 1), password).show(ui, language); @@ -179,11 +151,9 @@ fn strength_bar(ui: &mut Ui, bits: f64, strength: Strength, language: Language) for at in 0..5 { #[expect(clippy::cast_precision_loss, reason = "five steps")] let left = rect.left() + at as f32 * (step + 4.0); - let piece = - Rect::from_min_size(egui::pos2(left, rect.top()), Vec2::new(step, rect.height())); + let piece = Rect::from_min_size(egui::pos2(left, rect.top()), Vec2::new(step, rect.height())); let fill = if at < level { hue } else { p.bg_3 }; - ui.painter() - .rect_filled(piece, CornerRadius::same(radius::MARK), fill); + ui.painter().rect_filled(piece, CornerRadius::same(radius::MARK), fill); } #[expect(clippy::cast_possible_truncation, reason = "a few hundred bits")] let bits = bits.round() as i32; @@ -198,9 +168,8 @@ fn strength_bar(ui: &mut Ui, bits: f64, strength: Strength, language: Language) impl Tool for PasswordTool { fn update(&mut self, turn: &mut Turn<'_>) { let request = self.request(); - self.answer.update(turn, request, |backend, (asked, _)| { - api::tools::generate_passwords(backend, asked) - }); + self.answer + .update(turn, request, |backend, (asked, _)| api::tools::generate_passwords(backend, asked)); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -236,10 +205,7 @@ impl Tool for PasswordTool { /// Nothing typed to empty: Clear puts the options back as they were. fn clear(&mut self) { - *self = Self { - draw: self.draw, - ..Self::default() - }; + *self = Self { draw: self.draw, ..Self::default() }; } fn left(&mut self) { diff --git a/crates/ui/src/tools/catalogue/permissions.rs b/crates/ui/src/tools/catalogue/permissions.rs index 5110ebb64..71640cf6c 100644 --- a/crates/ui/src/tools/catalogue/permissions.rs +++ b/crates/ui/src/tools/catalogue/permissions.rs @@ -13,8 +13,7 @@ use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - ResultRow, card, check, columns, hint, label, named, paragraph, problem, result_rows, - section_title, + ResultRow, card, check, columns, hint, label, named, paragraph, problem, result_rows, section_title, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{TextField, address}; @@ -86,15 +85,11 @@ fn say(language: Language, path: &str) -> String { /// « read, write, execute ». fn rights_words(rights: &ClassRights, language: Language) -> String { - let granted: Vec = [ - (rights.read, "read"), - (rights.write, "write"), - (rights.execute, "execute"), - ] - .into_iter() - .filter(|(on, _)| *on) - .map(|(_, id)| say(language, &format!("tools.permissions.words.{id}"))) - .collect(); + let granted: Vec = [(rights.read, "read"), (rights.write, "write"), (rights.execute, "execute")] + .into_iter() + .filter(|(on, _)| *on) + .map(|(_, id)| say(language, &format!("tools.permissions.words.{id}"))) + .collect(); if granted.is_empty() { i18n::translate(language, keys::tools::permissions::words::NONE, &[]) } else { @@ -134,11 +129,7 @@ impl PermissionsTool { let next = self.bits() ^ mask_of(class, right); self.boxes = Some(next); self.field = Field::Octal; - self.text = if next > 0o777 { - format!("{next:04o}") - } else { - format!("{next:03o}") - }; + self.text = if next > 0o777 { format!("{next:04o}") } else { format!("{next:03o}") }; } fn input(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -176,9 +167,7 @@ impl PermissionsTool { let name = tr(name); label(ui, &name); let mut shown = self.shown(field); - let edited = TextField::new(&mut shown, &name, id) - .hint(&tr(hint_key)) - .show(ui); + let edited = TextField::new(&mut shown, &name, id).hint(&tr(hint_key)).show(ui); if edited.changed() { self.field = field; self.text = shown; @@ -195,17 +184,11 @@ impl PermissionsTool { return; }; match &answer.mode { - ModeReading::Refused { - problem: reason, - at, - } => { + ModeReading::Refused { problem: reason, at } => { let words = refused(*reason, *at, language); problem(ui, &words, "permissions-problem"); } - ModeReading::Read { - file_type: Some(kind), - .. - } => { + ModeReading::Read { file_type: Some(kind), .. } => { let kind = named(language, "tools.permissions.types", &json!(kind)); let words = Message::new(keys::tools::permissions::FILE_TYPE) .with("type", kind) @@ -268,8 +251,7 @@ impl PermissionsTool { fn warnings(&self, ui: &mut Ui, language: Language) { let p = palette(ui.ctx()); - let Some(ModeReading::Read { warnings, .. }) = self.answer.value().map(|it| &it.mode) - else { + let Some(ModeReading::Read { warnings, .. }) = self.answer.value().map(|it| &it.mode) else { return; }; for warning in warnings { @@ -301,10 +283,7 @@ impl PermissionsTool { result_rows(ui, &rows, language); }); } - Some(UmaskReading::Refused { - problem: reason, - at, - }) => { + Some(UmaskReading::Refused { problem: reason, at }) => { let words = refused(*reason, *at, language); problem(ui, &words, "permissions-umask-problem"); } @@ -324,10 +303,7 @@ impl PermissionsTool { let octal = format!("chmod {} {file}", mode.octal); let symbolic = format!("chmod {} {file}", mode.chmod_symbolic); card(ui, "permissions-commands", |ui| { - let rows = [ - ResultRow::new("chmod", &octal), - ResultRow::new("chmod", &symbolic), - ]; + let rows = [ResultRow::new("chmod", &octal), ResultRow::new("chmod", &symbolic)]; result_rows(ui, &rows, language); }); section_title(ui, &tr(keys::tools::permissions::CAN)); @@ -346,10 +322,8 @@ impl PermissionsTool { }) .collect(); card(ui, "permissions-words", |ui| { - let rows: Vec<_> = lines - .iter() - .map(|(name, text)| ResultRow::new(name, text).reading()) - .collect(); + let rows: Vec<_> = + lines.iter().map(|(name, text)| ResultRow::new(name, text).reading()).collect(); result_rows(ui, &rows, language); }); hint(ui, &tr(keys::tools::permissions::DIRECTORY_EXECUTE)); @@ -358,24 +332,16 @@ impl PermissionsTool { fn refused(reason: engine::tools::permissions::ModeProblem, at: u32, language: Language) -> String { let id = json!(reason); - let path = format!( - "tools.permissions.problems.{}", - id.as_str().unwrap_or_default() - ); - i18n::Key::find(&path).map_or_else(String::new, |key| { - Message::new(key).with("at", at).text(language) - }) + let path = format!("tools.permissions.problems.{}", id.as_str().unwrap_or_default()); + i18n::Key::find(&path).map_or_else(String::new, |key| Message::new(key).with("at", at).text(language)) } impl Tool for PermissionsTool { fn update(&mut self, turn: &mut Turn<'_>) { let empty = self.text.trim().is_empty() && self.umask.trim().is_empty(); - let request = (!empty).then(|| PermissionsRequest { - mode: self.text.clone(), - umask: self.umask.clone(), - }); - self.answer - .update(turn, request, api::tools::describe_permissions); + let request = + (!empty).then(|| PermissionsRequest { mode: self.text.clone(), umask: self.umask.clone() }); + self.answer.update(turn, request, api::tools::describe_permissions); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { diff --git a/crates/ui/src/tools/catalogue/ports.rs b/crates/ui/src/tools/catalogue/ports.rs index 22e188db7..c45563001 100644 --- a/crates/ui/src/tools/catalogue/ports.rs +++ b/crates/ui/src/tools/catalogue/ports.rs @@ -98,13 +98,8 @@ fn matches_port(row: &ReferenceRow, query: &str) -> bool { fn row((port, transport, service): (u32, &str, &str), language: Language) -> ReferenceRow { let range = range_of(port); let note = word(language, &format!("tools.ports.words.ports.{port}")); - let carried = word( - language, - &format!( - "tools.ports.transports.{}", - json!(transport).as_str().unwrap_or("") - ), - ); + let carried = + word(language, &format!("tools.ports.transports.{}", json!(transport).as_str().unwrap_or(""))); let heading = word(language, &format!("tools.ports.ranges.{range}")); let cells = vec![ Cell::mono(port.to_string()), @@ -126,12 +121,7 @@ pub(crate) fn table(language: Language) -> Table { columns: columns_of( language, "tools.ports.columns", - &[ - ("port", Some(0.11)), - ("transport", Some(0.16)), - ("service", Some(0.3)), - ("note", None), - ], + &[("port", Some(0.11)), ("transport", Some(0.16)), ("service", Some(0.3)), ("note", None)], ), caption: keys::tools::ports::NAME, placeholder: keys::tools::ports::PLACEHOLDER, diff --git a/crates/ui/src/tools/catalogue/qr.rs b/crates/ui/src/tools/catalogue/qr.rs index aa0f184bd..46d7c64ad 100644 --- a/crates/ui/src/tools/catalogue/qr.rs +++ b/crates/ui/src/tools/catalogue/qr.rs @@ -7,9 +7,7 @@ use std::sync::Arc; use egui::{Color32, ColorImage, CornerRadius, TextureHandle, TextureOptions, Ui, Vec2}; use engine::notes::language::Language as NoteLanguage; -use engine::tools::qr::{ - QrAnswer, QrContent, QrCorrection, QrFormat, QrRequest, SavedCode, WifiSecurity, -}; +use engine::tools::qr::{QrAnswer, QrContent, QrCorrection, QrFormat, QrRequest, SavedCode, WifiSecurity}; use i18n::{Language, Message, keys}; use serde_json::json; use zeroize::Zeroize; @@ -111,12 +109,8 @@ impl QrTool { fn content(&self) -> QrContent { let forms = &self.forms; match self.kind { - ContentKind::Text => QrContent::Text { - text: forms.text.clone(), - }, - ContentKind::Url => QrContent::Url { - url: forms.url.clone(), - }, + ContentKind::Text => QrContent::Text { text: forms.text.clone() }, + ContentKind::Url => QrContent::Url { url: forms.url.clone() }, ContentKind::Wifi => QrContent::Wifi { ssid: forms.ssid.clone(), password: forms.password.clone(), @@ -139,11 +133,7 @@ impl QrTool { fn request(&self) -> Option { let margin = self.margin.trim().parse::().ok()?.min(MAX_MARGIN); - Some(QrRequest { - content: self.content(), - correction: self.correction, - margin, - }) + Some(QrRequest { content: self.content(), correction: self.correction, margin }) } fn answered(&self) -> Option<&QrAnswer> { @@ -188,13 +178,7 @@ impl QrTool { TextField::new(&mut self.forms.url, &name, "qr-url") .hint(&tr(words::placeholders::URL)) .show(ui); - if matches!( - self.answered(), - Some(QrAnswer::Code { - missing_scheme: true, - .. - }) - ) { + if matches!(self.answered(), Some(QrAnswer::Code { missing_scheme: true, .. })) { let said = hint(ui, &tr(words::MISSING_SCHEME)); address(ui, &said, "qr-missing-scheme"); } @@ -203,12 +187,7 @@ impl QrTool { fn wifi_form(&mut self, ui: &mut Ui, language: Language) { use keys::tools::qr as words; let tr = |key| i18n::translate(language, key, &[]); - labelled( - ui, - &tr(words::fields::SSID), - &mut self.forms.ssid, - "qr-ssid", - ); + labelled(ui, &tr(words::fields::SSID), &mut self.forms.ssid, "qr-ssid"); if self.security != WifiSecurity::Open { let name = tr(words::fields::PASSWORD); label(ui, &name); @@ -234,12 +213,7 @@ impl QrTool { use keys::tools::qr::fields; let tr = |key| i18n::translate(language, key, &[]); labelled(ui, &tr(fields::TO), &mut self.forms.to, "qr-to"); - labelled( - ui, - &tr(fields::SUBJECT), - &mut self.forms.subject, - "qr-subject", - ); + labelled(ui, &tr(fields::SUBJECT), &mut self.forms.subject, "qr-subject"); let name = tr(fields::BODY); label(ui, &name); text_area(ui, &mut self.forms.body, (&name, "qr-body"), "", 3); @@ -277,14 +251,7 @@ impl QrTool { use keys::tools::qr as words; let tr = |key| i18n::translate(language, key, &[]); match self.answered() { - Some(QrAnswer::Code { - version, - modules, - bytes, - capacity, - recoverable, - .. - }) => { + Some(QrAnswer::Code { version, modules, bytes, capacity, recoverable, .. }) => { let value = Message::new(words::VERSION_VALUE) .with("version", *version) .with("modules", *modules) @@ -296,11 +263,7 @@ impl QrTool { let spare = Message::new(words::RECOVERABLE_VALUE) .with("percent", *recoverable) .text(language); - let names = ( - tr(words::VERSION), - tr(words::CAPACITY), - tr(words::RECOVERABLE), - ); + let names = (tr(words::VERSION), tr(words::CAPACITY), tr(words::RECOVERABLE)); card(ui, "qr-facts", |ui| { let rows = [ ResultRow::new(&names.0, &value).reading(), @@ -332,11 +295,7 @@ impl QrTool { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let mut button = |key, id, kind| { let words = tr(key); - Button::new(&words, id) - .kind(kind) - .enabled(code) - .show(ui) - .clicked() + Button::new(&words, id).kind(kind).enabled(code).show(ui).clicked() }; if button(words::DOWNLOAD_SVG, "qr-svg", Kind::Filled) { self.wants_file = Some(QrFormat::Svg); @@ -397,8 +356,7 @@ impl QrTool { // The code on screen, not the one being typed: the file is the preview. if let (Ok(Some(path)), Some(request)) = (answer, self.answer.answered()) { let path = path.display().to_string(); - let saved = - api::tools::save_qr_code(turn.backend, request.clone(), format, path); + let saved = api::tools::save_qr_code(turn.backend, request.clone(), format, path); self.saving = Some(Saving::Writing(saved)); } } @@ -406,9 +364,9 @@ impl QrTool { let Some(answer) = pending.poll() else { return }; self.saving = None; match answer { - Ok(SavedCode::Saved { bytes }) => turn - .status - .report(Message::new(keys::tools::qr::SAVED).with("count", bytes)), + Ok(SavedCode::Saved { bytes }) => { + turn.status.report(Message::new(keys::tools::qr::SAVED).with("count", bytes)); + } Ok(SavedCode::Failed { problem: reason }) => { let path = format!("tools.files.{}", json!(reason).as_str().unwrap_or("")); if let Some(key) = i18n::Key::find(&path) { @@ -429,20 +387,12 @@ impl QrTool { self.texture = None; return; }; - if self - .texture - .as_ref() - .is_some_and(|(drawn, _)| drawn == asked) - { + if self.texture.as_ref().is_some_and(|(drawn, _)| drawn == asked) { return; } - let image = pixels - .as_ref() - .and_then(|(side, rgba)| image_of(*side, rgba)); + let image = pixels.as_ref().and_then(|(side, rgba)| image_of(*side, rgba)); self.texture = image.map(|image| { - let texture = turn - .ctx - .load_texture("qr-code", image, TextureOptions::NEAREST); + let texture = turn.ctx.load_texture("qr-code", image, TextureOptions::NEAREST); (asked.clone(), texture) }); } @@ -524,10 +474,7 @@ mod tests { #[test] fn leaving_drops_the_code_that_held_the_password() { let (backend, _profile) = crate::testing::backend(); - let mut tool = QrTool { - kind: ContentKind::Wifi, - ..fresh() - }; + let mut tool = QrTool { kind: ContentKind::Wifi, ..fresh() }; "home".clone_into(&mut tool.forms.ssid); "not a real one".clone_into(&mut tool.forms.password); for time in [0.0, 0.01] { @@ -535,9 +482,9 @@ mod tests { backend.settle(); } let held = |tool: &QrTool| { - tool.answer.answered().is_some_and(|asked| { - matches!(&asked.content, QrContent::Wifi { password, .. } if !password.is_empty()) - }) + tool.answer.answered().is_some_and( + |asked| matches!(&asked.content, QrContent::Wifi { password, .. } if !password.is_empty()), + ) }; assert!(held(&tool)); diff --git a/crates/ui/src/tools/catalogue/reference.rs b/crates/ui/src/tools/catalogue/reference.rs index 65eec20f2..0e03e46c6 100644 --- a/crates/ui/src/tools/catalogue/reference.rs +++ b/crates/ui/src/tools/catalogue/reference.rs @@ -31,12 +31,7 @@ pub(super) struct Reference { impl Reference { pub(super) fn of(build: fn(Language) -> Table) -> Box { - Box::new(Self { - build, - query: String::new(), - lit: None, - built: None, - }) + Box::new(Self { build, query: String::new(), lit: None, built: None }) } } @@ -55,11 +50,7 @@ impl Table { impl Tool for Reference { fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { let language = drawn.language; - if self - .built - .as_ref() - .is_none_or(|(built, _)| *built != language) - { + if self.built.as_ref().is_none_or(|(built, _)| *built != language) { self.built = Some((language, (self.build)(language))); } let Some((_, table)) = &self.built else { @@ -116,25 +107,15 @@ pub(super) fn text<'a>(fact: &'a Value, field: &str) -> &'a str { /// The groups of a reference, their labels under `path`. pub(super) fn groups_of(language: Language, path: &str, ids: &[&str]) -> Vec { ids.iter() - .map(|id| Group { - id: (*id).to_owned(), - label: word(language, &format!("{path}.{id}")), - }) + .map(|id| Group { id: (*id).to_owned(), label: word(language, &format!("{path}.{id}")) }) .collect() } /// The columns of a reference, their labels under `path`. -pub(super) fn columns_of( - language: Language, - path: &str, - columns: &[(&str, Option)], -) -> Vec { +pub(super) fn columns_of(language: Language, path: &str, columns: &[(&str, Option)]) -> Vec { columns .iter() - .map(|(id, share)| Column { - label: word(language, &format!("{path}.{id}")), - share: *share, - }) + .map(|(id, share)| Column { label: word(language, &format!("{path}.{id}")), share: *share }) .collect() } diff --git a/crates/ui/src/tools/catalogue/reference_tests.rs b/crates/ui/src/tools/catalogue/reference_tests.rs index d65a4ab13..5aaa31c80 100644 --- a/crates/ui/src/tools/catalogue/reference_tests.rs +++ b/crates/ui/src/tools/catalogue/reference_tests.rs @@ -41,10 +41,7 @@ fn every_row_has_its_words_and_every_word_its_row() { let (title, line) = &row.found_as; let key = &row.key; assert!(!title.is_empty() && !line.is_empty(), "{id} {key}"); - assert!( - table.groups.iter().any(|group| group.id == row.group), - "{id} {key}: its group" - ); + assert!(table.groups.iter().any(|group| group.id == row.group), "{id} {key}: its group"); assert_eq!(row.cells.len(), table.columns.len(), "{id} {key}"); } for group in &table.groups { @@ -59,16 +56,9 @@ fn every_row_has_its_words_and_every_word_its_row() { #[test] fn a_word_that_holds_a_brace_keeps_it() { - let (_, table) = REFERENCES - .iter() - .find(|it| it.0 == "mustache-sheet") - .unwrap(); + let (_, table) = REFERENCES.iter().find(|it| it.0 == "mustache-sheet").unwrap(); let table = table(Language::En); - let delimiters = table - .rows - .iter() - .find(|row| row.key.contains("<%")) - .unwrap(); + let delimiters = table.rows.iter().find(|row| row.key.contains("<%")).unwrap(); assert!(delimiters.found_as.1.contains("{{ }}")); } @@ -85,10 +75,7 @@ fn each_reference_finds_what_it_is_asked() { #[test] fn a_space_that_matters_is_copied_as_a_space() { - let (_, table) = REFERENCES - .iter() - .find(|it| it.0 == "markdown-sheet") - .unwrap(); + let (_, table) = REFERENCES.iter().find(|it| it.0 == "markdown-sheet").unwrap(); let table = table(Language::En); let spaced = table.rows.iter().find(|row| row.key.contains('␣')).unwrap(); diff --git a/crates/ui/src/tools/catalogue/regex_sheet.rs b/crates/ui/src/tools/catalogue/regex_sheet.rs index 738258381..d08f2eeb2 100644 --- a/crates/ui/src/tools/catalogue/regex_sheet.rs +++ b/crates/ui/src/tools/catalogue/regex_sheet.rs @@ -7,14 +7,7 @@ use super::reference::{Reference, Table, columns_of, facts, groups_of, text, wor use crate::tools::Tool; use crate::tools::ui::{Cell, ReferenceRow}; -const GROUPS: [&str; 6] = [ - "anchors", - "classes", - "quantifiers", - "groups", - "flags", - "escapes", -]; +const GROUPS: [&str; 6] = ["anchors", "classes", "quantifiers", "groups", "flags", "escapes"]; const WIDE_CARD: f32 = 760.0; const METACHARACTERS: &str = r"\^$.*+?()[]{}|"; @@ -36,11 +29,7 @@ fn support_cell(supported: bool, note: &str) -> Cell { if !supported { return Cell::text("—"); } - if note.is_empty() { - Cell::checked() - } else { - Cell::checked().below(note) - } + if note.is_empty() { Cell::checked() } else { Cell::checked().below(note) } } fn example(entry: &Value, language: Language) -> Cell { @@ -49,11 +38,8 @@ fn example(entry: &Value, language: Language) -> Cell { let found: Vec<&str> = entry["matched"] .as_array() .map_or_else(Vec::new, |it| it.iter().filter_map(Value::as_str).collect()); - let matched = if found.is_empty() { - i18n::translate(language, words::NO_MATCH, &[]) - } else { - found.join(" ") - }; + let matched = + if found.is_empty() { i18n::translate(language, words::NO_MATCH, &[]) } else { found.join(" ") }; Cell::mono(text(entry, "pattern")) .below(format!("{on} {} →", text(entry, "text"))) .result(matched) diff --git a/crates/ui/src/tools/catalogue/signals.rs b/crates/ui/src/tools/catalogue/signals.rs index 009aca6f5..d7d783d54 100644 --- a/crates/ui/src/tools/catalogue/signals.rs +++ b/crates/ui/src/tools/catalogue/signals.rs @@ -7,14 +7,7 @@ use super::reference::{Reference, Table, columns_of, facts, groups_of, text, wor use crate::tools::Tool; use crate::tools::ui::{Cell, ReferenceRow}; -const GROUPS: [&str; 6] = [ - "terminal", - "stopping", - "faults", - "timers", - "events", - "application", -]; +const GROUPS: [&str; 6] = ["terminal", "stopping", "faults", "timers", "events", "application"]; const WIDE_CARD: f32 = 760.0; const NONE: &str = "—"; @@ -47,23 +40,13 @@ fn row(signal: &Value, language: Language) -> ReferenceRow { let linux = signal["linux"].as_str(); let usage = word(language, &format!("tools.signals.words.signals.{name}")); let heading = word(language, &format!("tools.signals.groups.{group}")); - let action = word( - language, - &format!("tools.signals.actions.{}", text(signal, "action")), - ); - let catchable = if signal["uncatchable"] == true { - words::NO - } else { - words::YES - }; + let action = word(language, &format!("tools.signals.actions.{}", text(signal, "action"))); + let catchable = if signal["uncatchable"] == true { words::NO } else { words::YES }; let macos = signal["macos"].as_str().unwrap_or(NONE); let on_macos = Cell::mono(macos); // A number macOS gives otherwise is what the column is read for. - let on_macos = if linux.is_none_or(|number| number != macos) { - on_macos.hue(|p| p.amber_text) - } else { - on_macos - }; + let on_macos = + if linux.is_none_or(|number| number != macos) { on_macos.hue(|p| p.amber_text) } else { on_macos }; let cells = vec![ Cell::mono(linux.unwrap_or(NONE)), Cell::mono(name), diff --git a/crates/ui/src/tools/catalogue/sizes.rs b/crates/ui/src/tools/catalogue/sizes.rs index abdd730f0..c7c0f069a 100644 --- a/crates/ui/src/tools/catalogue/sizes.rs +++ b/crates/ui/src/tools/catalogue/sizes.rs @@ -15,8 +15,8 @@ use crate::api; use crate::theme::palette; use crate::tools::live::{Live, Turn}; use crate::tools::ui::{ - ResultRow, card, columns, group_title, hint, label, named, number_field, paragraph, problem, - result_rows, section_title, + ResultRow, card, columns, group_title, hint, label, named, number_field, paragraph, problem, result_rows, + section_title, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{ChoiceMenu, TextField, address}; @@ -35,23 +35,11 @@ const GROUPS: [(&str, &[SizeUnit]); 3] = [ ), ( "decimal", - &[ - SizeUnit::Kilobyte, - SizeUnit::Megabyte, - SizeUnit::Gigabyte, - SizeUnit::Terabyte, - SizeUnit::Petabyte, - ], + &[SizeUnit::Kilobyte, SizeUnit::Megabyte, SizeUnit::Gigabyte, SizeUnit::Terabyte, SizeUnit::Petabyte], ), ( "binary", - &[ - SizeUnit::Kibibyte, - SizeUnit::Mebibyte, - SizeUnit::Gibibyte, - SizeUnit::Tebibyte, - SizeUnit::Pebibyte, - ], + &[SizeUnit::Kibibyte, SizeUnit::Mebibyte, SizeUnit::Gibibyte, SizeUnit::Tebibyte, SizeUnit::Pebibyte], ), ]; @@ -111,10 +99,7 @@ fn digits(value: &str, language: Language) -> String { } fn is_zero(value: &str) -> bool { - value - .trim_start_matches('-') - .bytes() - .all(|it| it == b'0' || it == b'.') + value.trim_start_matches('-').bytes().all(|it| it == b'0' || it == b'.') } /// What rounding would write as a bare 0, as a power of ten: `0.000008` is `8 × 10^-6`. @@ -129,17 +114,8 @@ fn scientific(value: &str, decimals: usize, language: Language) -> Option<(Strin let exponent = i32::try_from(zeros).ok()? + 1; let kept = figures.len().min(decimals + 1); let mantissa = format!("{}.{}", &figures[..1], &figures[1..kept]); - let shown = i18n::format::exact( - mantissa.trim_end_matches('.'), - (0, decimals), - false, - false, - language, - ); - Some(( - format!("{sign}{shown} × 10^-{exponent}"), - figures.len() <= kept, - )) + let shown = i18n::format::exact(mantissa.trim_end_matches('.'), (0, decimals), false, false, language); + Some((format!("{sign}{shown} × 10^-{exponent}"), figures.len() <= kept)) } /// « ≈ » before what rounding changed; a power of ten where it would have left a bare 0. @@ -147,8 +123,7 @@ fn shown_value(row: &SizeRow, decimals: usize, language: Language) -> String { let power = is_zero(&row.rounded) .then(|| scientific(&row.exact, decimals, language)) .flatten(); - let (text, exact) = - power.unwrap_or_else(|| (digits(&row.rounded, language), row.rounded == row.exact)); + let (text, exact) = power.unwrap_or_else(|| (digits(&row.rounded, language), row.rounded == row.exact)); if exact { text } else { format!("≈ {text}") } } @@ -172,11 +147,7 @@ fn time(span: &TransferTime, language: Language) -> String { .filter(|(_, count)| *count > 0) .map(|(key, count)| value(key, count)) .collect(); - if parts.is_empty() { - value(time::SECONDS, 0) - } else { - parts.join(" ") - } + if parts.is_empty() { value(time::SECONDS, 0) } else { parts.join(" ") } } fn unit_options(language: Language) -> Vec<(SizeUnit, String)> { @@ -192,8 +163,7 @@ fn unit_options(language: Language) -> Vec<(SizeUnit, String)> { fn unit_menu(ui: &mut Ui, chosen: &mut SizeUnit, author_id: &str, language: Language) { let options = unit_options(language); - let options: Vec<(SizeUnit, &str)> = - options.iter().map(|(id, it)| (*id, it.as_str())).collect(); + let options: Vec<(SizeUnit, &str)> = options.iter().map(|(id, it)| (*id, it.as_str())).collect(); let name = i18n::translate(language, keys::tools::sizes::UNIT, &[]); ChoiceMenu::new(&name, author_id, &options).show(ui, chosen); } @@ -247,9 +217,7 @@ impl SizesTool { number_field(ui, &mut self.decimals, &name, "sizes-decimals"); }); match self.answer.value() { - Some(SizesAnswer::Converted { - unit_in_text, gap, .. - }) => { + Some(SizesAnswer::Converted { unit_in_text, gap, .. }) => { if *unit_in_text { let said = hint(ui, &tr(keys::tools::sizes::UNIT_IN_TEXT)); address(ui, &said, "sizes-unit-in-text"); @@ -269,29 +237,18 @@ impl SizesTool { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing.y = gap::CONTROLS; let family = egui::FontFamily::Monospace; - let shown = crate::widgets::text( - ui, - &words, - font::HEADING, - 400.0, - family, - p.text_0, - ); + let shown = crate::widgets::text(ui, &words, font::HEADING, 400.0, family, p.text_0); let said = ui.label(shown); address(ui, &said, "sizes-gap"); hint(ui, &tr(keys::tools::sizes::CONVENTIONS)); }); } Some(SizesAnswer::Unreadable { at }) => { - let words = Message::new(keys::tools::sizes::UNREADABLE) - .with("at", *at) - .text(language); + let words = Message::new(keys::tools::sizes::UNREADABLE).with("at", *at).text(language); problem(ui, &words, "sizes-problem"); } Some(SizesAnswer::Negative { at }) => { - let words = Message::new(keys::tools::sizes::NEGATIVE) - .with("at", *at) - .text(language); + let words = Message::new(keys::tools::sizes::NEGATIVE).with("at", *at).text(language); problem(ui, &words, "sizes-problem"); } Some(SizesAnswer::TooLarge) => { @@ -344,29 +301,21 @@ impl SizesTool { let room = ui.available_width() - 170.0; ui.scope(|ui| { ui.set_max_width(room); - TextField::new(&mut self.size, &name, "transfer-size") - .hint("4,7") - .show(ui); + TextField::new(&mut self.size, &name, "transfer-size").hint("4,7").show(ui); }); unit_menu(ui, &mut self.size_unit, "transfer-size-unit", language); }); let name = tr(keys::tools::sizes::RATE); label(ui, &name); - let rates: Vec<(RateUnit, String)> = RATES - .iter() - .map(|it| (*it, rate_name(*it, language))) - .collect(); - let rates: Vec<(RateUnit, &str)> = - rates.iter().map(|(id, it)| (*id, it.as_str())).collect(); + let rates: Vec<(RateUnit, String)> = RATES.iter().map(|it| (*it, rate_name(*it, language))).collect(); + let rates: Vec<(RateUnit, &str)> = rates.iter().map(|(id, it)| (*id, it.as_str())).collect(); let unit_name = tr(keys::tools::sizes::RATE_UNIT); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap::CONTROLS; let room = ui.available_width() - 170.0; ui.scope(|ui| { ui.set_max_width(room); - TextField::new(&mut self.rate, &name, "transfer-rate") - .hint("100") - .show(ui); + TextField::new(&mut self.rate, &name, "transfer-rate").hint("100").show(ui); }); ChoiceMenu::new(&unit_name, "transfer-rate-unit", &rates).show(ui, &mut self.rate_unit); }); @@ -374,8 +323,7 @@ impl SizesTool { label(ui, &name); let range = EFFICIENCY.0..=EFFICIENCY.1; let slider = ui.add(egui::Slider::new(&mut self.efficiency, range).suffix(" %")); - ui.ctx() - .accesskit_node_builder(slider.id, |node| node.set_label(name.clone())); + ui.ctx().accesskit_node_builder(slider.id, |node| node.set_label(name.clone())); address(ui, &slider, "transfer-efficiency"); hint(ui, &tr(keys::tools::sizes::EFFICIENCY_HINT)); hint(ui, &tr(keys::tools::sizes::BITS_AND_BYTES)); @@ -383,11 +331,7 @@ impl SizesTool { fn rate_label(&self, language: Language) -> String { self.transfer.answered().map_or_else(String::new, |asked| { - format!( - "{} {}", - asked.rate.trim(), - rate_name(asked.rate_unit, language) - ) + format!("{} {}", asked.rate.trim(), rate_name(asked.rate_unit, language)) }) } @@ -405,13 +349,7 @@ impl SizesTool { hint(ui, &tr(keys::tools::sizes::TRANSFER_EMPTY)); return; }; - let TransferAnswer::Estimated { - estimate, - theoretical, - efficiency, - connections, - } = answer - else { + let TransferAnswer::Estimated { estimate, theoretical, efficiency, connections } = answer else { if let Some(words) = transfer_problem(answer, language) { problem(ui, &words, "transfer-problem"); } @@ -423,12 +361,7 @@ impl SizesTool { .with("efficiency", *efficiency) .text(language); hint(ui, &at); - let said = paragraph( - ui, - &time(estimate, language), - (font::DISPLAY, 700.0), - p.text_0, - ); + let said = paragraph(ui, &time(estimate, language), (font::DISPLAY, 700.0), p.text_0); address(ui, &said, "transfer-time"); let words = Message::new(keys::tools::sizes::THEORETICAL) .with("time", time(theoretical, language)) @@ -477,12 +410,7 @@ impl SizesTool { } fn transfer_result(&self, language: Language) -> Option { - let Some(TransferAnswer::Estimated { - efficiency, - connections, - .. - }) = self.transfer.value() - else { + let Some(TransferAnswer::Estimated { efficiency, connections, .. }) = self.transfer.value() else { return None; }; let asked = self.transfer.answered()?; @@ -491,10 +419,7 @@ impl SizesTool { .map(|it| (self.connection_name(it, language), time(&it.span, language))) .collect(); let width = rows.iter().map(|(name, _)| name.chars().count()).max()?; - let lines: Vec = rows - .iter() - .map(|(name, value)| format!("{name:width$} {value}")) - .collect(); + let lines: Vec = rows.iter().map(|(name, value)| format!("{name:width$} {value}")).collect(); Some(ToolResult { title: Message::new(keys::tools::sizes::NOTE_TRANSFER) .with("size", asked.size.trim()) @@ -524,8 +449,7 @@ impl Tool for SizesTool { rate_unit: self.rate_unit, efficiency: self.efficiency, }); - self.transfer - .update(turn, request, api::tools::estimate_transfer); + self.transfer.update(turn, request, api::tools::estimate_transfer); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -537,10 +461,7 @@ impl Tool for SizesTool { } fn result(&self, language: Language) -> Option { - ToolResult::together( - self.conversion_result(language), - self.transfer_result(language), - ) + ToolResult::together(self.conversion_result(language), self.transfer_result(language)) } fn has_sample(&self) -> bool { @@ -577,11 +498,8 @@ mod tests { #[test] fn a_rounded_value_is_said_to_be() { - let row = SizeRow { - unit: SizeUnit::Gibibyte, - exact: "4.3772".to_owned(), - rounded: "4.377".to_owned(), - }; + let row = + SizeRow { unit: SizeUnit::Gibibyte, exact: "4.3772".to_owned(), rounded: "4.377".to_owned() }; assert_eq!(shown_value(&row, 3, Language::En), "≈ 4.377"); } diff --git a/crates/ui/src/tools/catalogue/text_stats.rs b/crates/ui/src/tools/catalogue/text_stats.rs index 148d23717..28f22833c 100644 --- a/crates/ui/src/tools/catalogue/text_stats.rs +++ b/crates/ui/src/tools/catalogue/text_stats.rs @@ -33,34 +33,14 @@ pub(super) fn make() -> Box { fn counts(stats: &TextStats) -> [(Key, Option, &'static str, u32); 9] { use keys::tools::text_stats::{hints, rows}; [ - ( - rows::CHARACTERS, - Some(hints::CHARACTERS), - "characters", - stats.characters, - ), - ( - rows::NON_WHITESPACE, - None, - "non-whitespace", - stats.non_whitespace, - ), + (rows::CHARACTERS, Some(hints::CHARACTERS), "characters", stats.characters), + (rows::NON_WHITESPACE, None, "non-whitespace", stats.non_whitespace), (rows::WORDS, None, "words", stats.words), (rows::LINES, None, "lines", stats.lines), - ( - rows::NON_EMPTY_LINES, - None, - "non-empty-lines", - stats.non_empty_lines, - ), + (rows::NON_EMPTY_LINES, None, "non-empty-lines", stats.non_empty_lines), (rows::PARAGRAPHS, None, "paragraphs", stats.paragraphs), (rows::CODE_POINTS, None, "code-points", stats.code_points), - ( - rows::UTF16_UNITS, - Some(hints::UTF16_UNITS), - "utf16-units", - stats.utf16_units, - ), + (rows::UTF16_UNITS, Some(hints::UTF16_UNITS), "utf16-units", stats.utf16_units), (rows::UTF8_BYTES, None, "utf8-bytes", stats.utf8_bytes), ] } @@ -98,14 +78,7 @@ fn count_cell( let words = i18n::translate(language, key, &[]); widgets::wrapped(ui, &words, (font::CAPTION, 400.0), p.text_2, width * 0.6) }); - let number = widgets::text( - ui, - &figure, - font::HEADING, - 400.0, - FontFamily::Monospace, - p.text_0, - ); + let number = widgets::text(ui, &figure, font::HEADING, 400.0, FontFamily::Monospace, p.text_0); let left = label.size().y + under.as_ref().map_or(0.0, |it| it.size().y); let height = left.max(number.size().y) + 18.0; let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), Sense::hover()); @@ -115,17 +88,13 @@ fn count_cell( info }); address(ui, &response, &format!("text-stats-count-{id}")); - ui.painter() - .hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); let label_height = label.size().y; label.paint(ui, rect.min + Vec2::new(0.0, 9.0), p.text_2); if let Some(under) = under { under.paint(ui, rect.min + Vec2::new(0.0, 9.0 + label_height), p.text_2); } - let at = Pos2::new( - rect.right() - number.size().x, - rect.center().y - number.size().y / 2.0, - ); + let at = Pos2::new(rect.right() - number.size().x, rect.center().y - number.size().y / 2.0); ui.painter().galley(at, number, p.text_0); } @@ -139,11 +108,7 @@ fn count_card(ui: &mut Ui, stats: &TextStats, language: Language) { .show(ui, |ui| { let width = ui.available_width(); ui.set_width(width); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a few columns" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a few columns")] let across = (((width + 24.0) / (COUNT_MIN + 24.0)).floor() as usize).max(1); #[expect(clippy::cast_precision_loss, reason = "a few columns")] let each = (width - 24.0 * (across - 1) as f32) / across as f32; @@ -188,18 +153,16 @@ fn frequency_row(ui: &mut Ui, frequency: &Frequency, most: u32, language: Langua let p = palette(ui.ctx()); let width = ui.available_width(); let (rect, response) = ui.allocate_exact_size(Vec2::new(width, ROW), Sense::hover()); - let label = frequency.invisible.map_or_else( - || frequency.character.clone(), - |it| i18n::translate(language, invisible_name(it), &[]), - ); + let label = frequency + .invisible + .map_or_else(|| frequency.character.clone(), |it| i18n::translate(language, invisible_name(it), &[])); response.widget_info(|| { let mut info = WidgetInfo::labeled(Role::Row, true, &label); info.current_text_value = Some(frequency.count.to_string()); info }); address(ui, &response, "text-stats-frequency"); - ui.painter() - .hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); let middle = rect.center().y; let cell = |ink| { let family = FontFamily::Monospace; @@ -216,10 +179,7 @@ fn frequency_row(ui: &mut Ui, frequency: &Frequency, most: u32, language: Langua let at = Pos2::new(rect.left() + width * 0.34, middle - code.size().y / 2.0); ui.painter().galley(at, code, p.text_2); let number = cell(p.text_0)(ui, &frequency.count.to_string(), 12.0); - let at = Pos2::new( - rect.left() + width * 0.68 - number.size().x, - middle - number.size().y / 2.0, - ); + let at = Pos2::new(rect.left() + width * 0.68 - number.size().x, middle - number.size().y / 2.0); ui.painter().galley(at, number, p.text_0); let share = Rect::from_min_max( Pos2::new(rect.left() + width * 0.7, rect.top() + 6.0), @@ -228,17 +188,11 @@ fn frequency_row(ui: &mut Ui, frequency: &Frequency, most: u32, language: Langua #[expect(clippy::cast_precision_loss, reason = "a share on screen")] let filled = frequency.count as f32 / most.max(1) as f32; let bar = Rect::from_min_size(share.min, Vec2::new(share.width() * filled, share.height())); - ui.painter().rect_filled( - bar, - CornerRadius::same(radius::MARK), - p.amber_fill.gamma_multiply(0.25), - ); + ui.painter() + .rect_filled(bar, CornerRadius::same(radius::MARK), p.amber_fill.gamma_multiply(0.25)); let percent = format!("{:.1} %", frequency.share); let percent = cell(p.text_1)(ui, &percent, 11.0); - let at = Pos2::new( - share.right() - percent.size().x, - middle - percent.size().y / 2.0, - ); + let at = Pos2::new(share.right() - percent.size().x, middle - percent.size().y / 2.0); ui.painter().galley(at, percent, p.text_1); } @@ -260,10 +214,7 @@ impl TextStatsTool { text_area( ui, &mut self.text, - ( - &tr(keys::tools::text_stats::INPUT_LABEL), - "text-stats-input", - ), + (&tr(keys::tools::text_stats::INPUT_LABEL), "text-stats-input"), &tr(keys::tools::text_stats::PLACEHOLDER), 14, ); @@ -290,23 +241,13 @@ impl TextStatsTool { let words = tr(keys::tools::text_stats::FOLD_CASE); check(ui, &mut self.fold_case, &words, "text-stats-fold"); let words = tr(keys::tools::text_stats::COUNT_WHITESPACE); - check( - ui, - &mut self.count_whitespace, - &words, - "text-stats-whitespace", - ); + check(ui, &mut self.count_whitespace, &words, "text-stats-whitespace"); }); let Some(stats) = self.answer.value() else { return; }; let p = palette(ui.ctx()); - let most = stats - .frequencies - .iter() - .map(|it| it.count) - .max() - .unwrap_or(1); + let most = stats.frequencies.iter().map(|it| it.count).max().unwrap_or(1); egui::Frame::new() .fill(p.bg_1) .stroke(Stroke::new(1.0, p.line)) @@ -351,10 +292,8 @@ impl Tool for TextStatsTool { .map(|(name, _, _, figure)| (i18n::translate(language, name, &[]), figure)) .collect(); let width = rows.iter().map(|(name, _)| name.chars().count()).max()?; - let content: Vec = rows - .iter() - .map(|(name, figure)| format!("{name:width$} {figure}")) - .collect(); + let content: Vec = + rows.iter().map(|(name, figure)| format!("{name:width$} {figure}")).collect(); Some(ToolResult { title: i18n::translate(language, keys::tools::text_stats::NOTE_TITLE, &[]), language: NoteLanguage::Txt, diff --git a/crates/ui/src/tools/catalogue/text_tests.rs b/crates/ui/src/tools/catalogue/text_tests.rs index 1def16dd5..ba97d9b49 100644 --- a/crates/ui/src/tools/catalogue/text_tests.rs +++ b/crates/ui/src/tools/catalogue/text_tests.rs @@ -35,17 +35,12 @@ pub(super) fn click(harness: &mut Harness<'_, Bench>, id: &str) { pub(super) fn type_in(harness: &mut Harness<'_, Bench>, id: &str, text: &str) { harness.get_by(|node| node.author_id() == Some(id)).focus(); harness.step(); - harness - .get_by(|node| node.author_id() == Some(id)) - .type_text(text); + harness.get_by(|node| node.author_id() == Some(id)).type_text(text); settle(harness); } pub(super) fn has(harness: &Harness<'_, Bench>, id: &str) -> bool { - harness - .query_all_by(|node| node.author_id() == Some(id)) - .next() - .is_some() + harness.query_all_by(|node| node.author_id() == Some(id)).next().is_some() } pub(super) fn value_of(harness: &Harness<'_, Bench>, id: &str) -> String { @@ -75,9 +70,7 @@ fn the_case_converter_writes_a_text_in_every_case_and_its_slug() { let mut harness = opened("case"); type_in(&mut harness, "case-input", "parse URL"); - waits_for(&mut harness, "the cases are shown", |harness| { - !output_values(harness).is_empty() - }); + waits_for(&mut harness, "the cases are shown", |harness| !output_values(harness).is_empty()); let values = output_values(&harness); assert!(values.contains(&"parseUrl".to_owned()), "{values:?}"); @@ -101,9 +94,7 @@ fn line_breaks_count_the_endings_and_rewrite_them() { let mut harness = opened("line-breaks"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the endings are counted", |harness| { - has(harness, "line-breaks-found") - }); + waits_for(&mut harness, "the endings are counted", |harness| has(harness, "line-breaks-found")); assert!(value_of(&harness, "line-breaks-found").contains("CRLF 2")); assert!(value_of(&harness, "line-breaks-changes").contains('2')); @@ -112,16 +103,12 @@ fn line_breaks_count_the_endings_and_rewrite_them() { #[test] fn lorem_opens_on_three_paragraphs_and_draws_another_text() { let mut harness = opened("lorem"); - waits_for(&mut harness, "a text is drawn", |harness| { - has(harness, "lorem-output") - }); + waits_for(&mut harness, "a text is drawn", |harness| has(harness, "lorem-output")); let first = value_of(&harness, "lorem-output"); assert!(first.starts_with("Lorem ipsum")); click(&mut harness, "lorem-again"); - waits_for(&mut harness, "another text is drawn", |harness| { - value_of(harness, "lorem-output") != first - }); + waits_for(&mut harness, "another text is drawn", |harness| value_of(harness, "lorem-output") != first); } #[test] @@ -129,9 +116,7 @@ fn text_statistics_count_the_characters_and_their_frequency() { let mut harness = opened("text-stats"); type_in(&mut harness, "text-stats-input", "été a"); - waits_for(&mut harness, "the text is counted", |harness| { - has(harness, "text-stats-count-words") - }); + waits_for(&mut harness, "the text is counted", |harness| has(harness, "text-stats-count-words")); assert_eq!(value_of(&harness, "text-stats-count-words"), "2"); assert_eq!(value_of(&harness, "text-stats-count-characters"), "5"); @@ -143,9 +128,7 @@ fn the_text_diff_counts_what_changed_and_swaps_its_sides() { let mut harness = opened("diff"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the texts are compared", |harness| { - has(harness, "text-diff-rows") - }); + waits_for(&mut harness, "the texts are compared", |harness| has(harness, "text-diff-rows")); assert_eq!(value_of(&harness, "text-diff-added"), "+ 4 lines"); let added = value_of(&harness, "text-diff-added"); @@ -162,9 +145,7 @@ fn identical_texts_are_said_to_be() { type_in(&mut harness, "text-diff-a", "same"); type_in(&mut harness, "text-diff-b", "same"); - waits_for(&mut harness, "the texts are compared", |harness| { - has(harness, "text-diff-identical") - }); + waits_for(&mut harness, "the texts are compared", |harness| has(harness, "text-diff-identical")); } #[test] @@ -173,9 +154,7 @@ fn the_structured_diff_reads_two_formats_and_lists_the_value_that_changed() { click(&mut harness, "diff-mode-1"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the documents are compared", |harness| { - has(harness, "structured-diff-change") - }); + waits_for(&mut harness, "the documents are compared", |harness| has(harness, "structured-diff-change")); assert_eq!(value_of(&harness, "structured-diff-read-a"), "read as YAML"); assert_eq!(value_of(&harness, "structured-diff-read-b"), "read as JSON"); diff --git a/crates/ui/src/tools/catalogue/time_tests.rs b/crates/ui/src/tools/catalogue/time_tests.rs index 93ce18fbe..d3acc9567 100644 --- a/crates/ui/src/tools/catalogue/time_tests.rs +++ b/crates/ui/src/tools/catalogue/time_tests.rs @@ -7,16 +7,11 @@ fn an_instant_is_read_in_every_form() { let mut harness = opened("dates"); type_in(&mut harness, "dates-input", "1700000000"); - waits_for(&mut harness, "the instant is read", |harness| { - has(harness, "dates-forms") - }); + waits_for(&mut harness, "the instant is read", |harness| has(harness, "dates-forms")); let values = output_values(&harness); assert!(values.contains(&"1700000000000".to_owned()), "{values:?}"); - assert!( - values.contains(&"2023-11-14T22:13:20Z".to_owned()), - "{values:?}" - ); + assert!(values.contains(&"2023-11-14T22:13:20Z".to_owned()), "{values:?}"); assert!(has(&harness, "dates-reading")); } @@ -26,9 +21,7 @@ fn what_is_no_date_says_where_it_stops() { type_in(&mut harness, "dates-input", "not a date"); - waits_for(&mut harness, "the text is refused", |harness| { - has(harness, "dates-problem") - }); + waits_for(&mut harness, "the text is refused", |harness| has(harness, "dates-problem")); } #[test] @@ -37,9 +30,7 @@ fn now_fills_the_field() { click(&mut harness, "dates-now"); - waits_for(&mut harness, "the field is filled", |harness| { - !value_of(harness, "dates-input").is_empty() - }); + waits_for(&mut harness, "the field is filled", |harness| !value_of(harness, "dates-input").is_empty()); } #[test] @@ -47,15 +38,10 @@ fn a_gap_and_a_duration_are_measured_and_read_aloud() { let mut harness = opened("dates"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the gap is measured", |harness| { - has(harness, "dates-gap") - }); + waits_for(&mut harness, "the gap is measured", |harness| has(harness, "dates-gap")); assert!(value_of(&harness, "dates-gap-calendar").contains("6 months")); - assert_eq!( - value_of(&harness, "dates-duration-words"), - "1 hour 30 minutes" - ); + assert_eq!(value_of(&harness, "dates-duration-words"), "1 hour 30 minutes"); } #[test] @@ -64,9 +50,7 @@ fn a_time_is_placed_in_the_zones_of_the_list() { click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the zones are shown", |harness| { - has(harness, "zones-row") - }); + waits_for(&mut harness, "the zones are shown", |harness| has(harness, "zones-row")); assert!(has(&harness, "zones-from")); assert!(has(&harness, "zones-remove-Asia/Tokyo")); } @@ -75,23 +59,15 @@ fn a_time_is_placed_in_the_zones_of_the_list() { fn a_zone_found_joins_the_list_and_leaves_it() { let mut harness = opened("zones"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the zones are shown", |harness| { - has(harness, "zones-row") - }); + waits_for(&mut harness, "the zones are shown", |harness| has(harness, "zones-row")); type_in(&mut harness, "zones-search", "Sydney"); - waits_for(&mut harness, "the zone is found", |harness| { - has(harness, "zones-found-Australia/Sydney") - }); + waits_for(&mut harness, "the zone is found", |harness| has(harness, "zones-found-Australia/Sydney")); click(&mut harness, "zones-found-Australia/Sydney"); - waits_for(&mut harness, "the zone is listed", |harness| { - has(harness, "zones-remove-Australia/Sydney") - }); + waits_for(&mut harness, "the zone is listed", |harness| has(harness, "zones-remove-Australia/Sydney")); click(&mut harness, "zones-remove-Australia/Sydney"); - waits_for(&mut harness, "the zone is gone", |harness| { - !has(harness, "zones-remove-Australia/Sydney") - }); + waits_for(&mut harness, "the zone is gone", |harness| !has(harness, "zones-remove-Australia/Sydney")); } #[test] @@ -99,9 +75,7 @@ fn a_cron_expression_is_read_aloud_with_its_next_runs() { let mut harness = opened("cron"); click(&mut harness, "tool-sample"); - waits_for(&mut harness, "the expression is read", |harness| { - has(harness, "cron-sentence") - }); + waits_for(&mut harness, "the expression is read", |harness| has(harness, "cron-sentence")); assert!(has(&harness, "cron-field")); assert!(has(&harness, "cron-run")); @@ -113,9 +87,7 @@ fn a_cron_field_out_of_range_says_which_and_where() { type_in(&mut harness, "cron-input", "61 * * * *"); - waits_for(&mut harness, "the expression is refused", |harness| { - has(harness, "cron-problem") - }); + waits_for(&mut harness, "the expression is refused", |harness| has(harness, "cron-problem")); assert!(value_of(&harness, "cron-problem").contains("61")); } @@ -126,7 +98,5 @@ fn a_moment_is_checked_against_the_expression() { type_in(&mut harness, "cron-check", "2026-10-14 12:00"); - waits_for(&mut harness, "the moment is checked", |harness| { - has(harness, "cron-verdict") - }); + waits_for(&mut harness, "the moment is checked", |harness| has(harness, "cron-verdict")); } diff --git a/crates/ui/src/tools/catalogue/url_codec.rs b/crates/ui/src/tools/catalogue/url_codec.rs index 5e171a201..a5ad9596b 100644 --- a/crates/ui/src/tools/catalogue/url_codec.rs +++ b/crates/ui/src/tools/catalogue/url_codec.rs @@ -13,14 +13,15 @@ use crate::api; use crate::tools::live::{Live, Turn}; use crate::tools::ui::note_picker::PickedNote; use crate::tools::ui::{ - CopyValue, ResultRow, card, columns, hint, named, note_import, problem, result_rows, - section_head, section_title, text_area, + CopyValue, ResultRow, card, columns, hint, named, note_import, problem, result_rows, section_head, + section_title, text_area, }; use crate::tools::{Drawn, Tool, ToolResult}; use crate::widgets::{Button, Segmented}; /// Its query is encoded: decoded on one tab, its parameters read on the other. -const SAMPLE: &str = "https://ada:secret@api.example.com:8443/v2/search?q=caf%C3%A9%20cr%C3%A8me&tag=a&tag=b#results"; +const SAMPLE: &str = + "https://ada:secret@api.example.com:8443/v2/search?q=caf%C3%A9%20cr%C3%A8me&tag=a&tag=b#results"; #[derive(Clone, Copy, PartialEq, Eq)] enum Side { @@ -84,9 +85,7 @@ impl UrlCodecTool { /// An answer going the other way is not shown: typed on the other side, it is the reverse. fn current(&self) -> Option<&UrlCodecAnswer> { let asked = self.answer.answered()?; - (asked.direction == self.direction()) - .then(|| self.answer.value()) - .flatten() + (asked.direction == self.direction()).then(|| self.answer.value()).flatten() } fn translated(&self) -> &str { @@ -97,11 +96,7 @@ impl UrlCodecTool { } fn of(&self, side: Side) -> &str { - if self.side == side { - &self.text - } else { - self.translated() - } + if self.side == side { &self.text } else { self.translated() } } fn parts(&self) -> Option<&UrlParts> { @@ -120,10 +115,8 @@ impl UrlCodecTool { ui.spacing_mut().item_spacing.x = gap::BLOCKS; Segmented::new(&options, "url-tab").show(ui, &mut self.tab); if self.tab == Tab::Codec { - let options = [ - (UrlScope::Component, tr(scopes::COMPONENT)), - (UrlScope::Whole, tr(scopes::WHOLE)), - ]; + let options = + [(UrlScope::Component, tr(scopes::COMPONENT)), (UrlScope::Whole, tr(scopes::WHOLE))]; let options = options.each_ref().map(|(id, name)| (*id, name.as_str())); crate::tools::ui::label(ui, &tr(keys::tools::url_codec::SCOPE)); Segmented::new(&options, "url-codec-scope").show(ui, &mut self.scope); @@ -168,8 +161,7 @@ impl UrlCodecTool { note_import(ui, drawn, "text"); }); self.codec_field(ui, Side::Decoded, language); - let offers = - self.parts().is_some() && self.parsed.answered().map(String::as_str) == Some(&*value); + let offers = self.parts().is_some() && self.parsed.answered().map(String::as_str) == Some(&*value); if offers { let words = i18n::translate(language, keys::tools::url_codec::ANALYSE_THIS, &[]); if Button::new(&words, "url-analyse-this").show(ui).clicked() { @@ -194,11 +186,9 @@ impl UrlCodecTool { .with("at", *at + 1) .text(language), ), - Some(UrlCodecAnswer::NotUtf8) => Some(i18n::translate( - language, - keys::tools::url_codec::NOT_UTF8, - &[], - )), + Some(UrlCodecAnswer::NotUtf8) => { + Some(i18n::translate(language, keys::tools::url_codec::NOT_UTF8, &[])) + } _ => None, }; if let Some(said) = said { @@ -212,13 +202,7 @@ impl UrlCodecTool { section_title(ui, &tr(keys::tools::INPUT)); let name = tr(keys::tools::url_codec::INPUT_LABEL); let placeholder = tr(keys::tools::url_codec::PLACEHOLDER); - text_area( - ui, - &mut self.text, - (&name, "url-parser-input"), - &placeholder, - 8, - ); + text_area(ui, &mut self.text, (&name, "url-parser-input"), &placeholder, 8); if let Some(UrlAnswer::Invalid { problem: reason }) = self.parsed.value() { let said = named(language, "tools.url-codec.problems", &json!(reason)); problem(ui, &said, "url-parser-problem"); @@ -247,16 +231,8 @@ impl UrlCodecTool { .zip(&names) .map(|((id, value), name)| { let row = ResultRow::new(name, value); - let row = if *id == "password" { - row.reading() - } else { - row - }; - if *id == "port" && parts.port_is_default { - row.meta(&aside) - } else { - row - } + let row = if *id == "password" { row.reading() } else { row }; + if *id == "port" && parts.port_is_default { row.meta(&aside) } else { row } }) .collect(); result_rows(ui, &shown, language); diff --git a/crates/ui/src/tools/catalogue/zones.rs b/crates/ui/src/tools/catalogue/zones.rs index 5c96b2b4f..388afd3b3 100644 --- a/crates/ui/src/tools/catalogue/zones.rs +++ b/crates/ui/src/tools/catalogue/zones.rs @@ -64,10 +64,7 @@ impl ZonesTool { self.later = false; } }); - if Button::new(&tr(keys::tools::zones::NOW), "zones-now") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::tools::zones::NOW), "zones-now").show(ui).clicked() { self.wants_now = true; } }); @@ -84,12 +81,7 @@ impl ZonesTool { fn reading(&mut self, ui: &mut Ui, language: Language) { let tr = |key| i18n::translate(language, key, &[]); match self.answer.value() { - Some(ZonesAnswer::Placed { - from, - ambiguous, - unknown, - .. - }) => { + Some(ZonesAnswer::Placed { from, ambiguous, unknown, .. }) => { let mut words = format!( "{}{from}{}", tr(keys::tools::zones::TYPED_IN_BEFORE), @@ -110,9 +102,7 @@ impl ZonesTool { address(ui, &said, "zones-unknown"); } if let Some(readings) = readings { - let words = Message::new(keys::tools::zones::AMBIGUOUS) - .with("zone", from) - .text(language); + let words = Message::new(keys::tools::zones::AMBIGUOUS).with("zone", from).text(language); hint(ui, &words); for (at, reading) in readings.iter().enumerate() { let mut on = self.later == (at == 1); @@ -123,11 +113,7 @@ impl ZonesTool { } } } - Some(ZonesAnswer::Skipped { - from, - before, - after, - }) => { + Some(ZonesAnswer::Skipped { from, before, after }) => { let words = Message::new(keys::tools::zones::SKIPPED) .with("zone", from.as_str()) .with("before", before.as_str()) @@ -136,9 +122,7 @@ impl ZonesTool { problem(ui, &words, "zones-problem"); } Some(ZonesAnswer::Unreadable { at }) => { - let words = Message::new(keys::tools::zones::UNREADABLE) - .with("at", *at) - .text(language); + let words = Message::new(keys::tools::zones::UNREADABLE).with("at", *at).text(language); problem(ui, &words, "zones-problem"); } Some(ZonesAnswer::UnknownZone { zone }) => { @@ -187,10 +171,7 @@ impl ZonesTool { fn times(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { let language = drawn.language; let Some(ZonesAnswer::Placed { times, .. }) = self.answer.value() else { - hint( - ui, - &i18n::translate(language, keys::tools::zones::EMPTY, &[]), - ); + hint(ui, &i18n::translate(language, keys::tools::zones::EMPTY, &[])); return; }; let mut here = None; @@ -229,33 +210,12 @@ fn found_entry(ui: &mut Ui, entry: &ZoneEntry) -> egui::Response { let rect = response.rect; let fill = towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)); ui.painter().rect_filled(rect, corner, fill); - let name = widgets::text( - ui, - &entry.zone, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_0, - ); + let name = widgets::text(ui, &entry.zone, font::BODY, 400.0, FontFamily::Proportional, p.text_0); let at = Pos2::new(rect.left() + 10.0, rect.center().y - name.size().y / 2.0); ui.painter().galley(at, name, p.text_0); - let offset = format!( - "UTC{} {}", - entry.offset, - entry.abbreviation.as_deref().unwrap_or_default() - ); - let offset = widgets::text( - ui, - &offset, - font::CONTROL, - 400.0, - FontFamily::Monospace, - p.text_2, - ); - let at = Pos2::new( - rect.right() - 10.0 - offset.size().x, - rect.center().y - offset.size().y / 2.0, - ); + let offset = format!("UTC{} {}", entry.offset, entry.abbreviation.as_deref().unwrap_or_default()); + let offset = widgets::text(ui, &offset, font::CONTROL, 400.0, FontFamily::Monospace, p.text_2); + let at = Pos2::new(rect.right() - 10.0 - offset.size().x, rect.center().y - offset.size().y / 2.0); ui.painter().galley(at, offset, p.text_2); response } @@ -293,14 +253,8 @@ fn date_words(time: &ZoneTime, language: Language) -> String { if time.day_shift == 0 { return time.date.clone(); } - let key = if time.day_shift > 0 { - keys::tools::zones::DAY_AHEAD - } else { - keys::tools::zones::DAY_BEHIND - }; - let shift = Message::new(key) - .with("count", time.day_shift.unsigned_abs()) - .text(language); + let key = if time.day_shift > 0 { keys::tools::zones::DAY_AHEAD } else { keys::tools::zones::DAY_BEHIND }; + let shift = Message::new(key).with("count", time.day_shift.unsigned_abs()).text(language); format!("{} {shift}", time.date) } @@ -308,11 +262,7 @@ fn time_row(ui: &mut Ui, time: &ZoneTime, removable: bool, language: Language) - let p = palette(ui.ctx()); let tr = |key| i18n::translate(language, key, &[]); let mut asked = None; - let edge = if time.source { - p.amber_dim - } else { - p.line_soft - }; + let edge = if time.source { p.amber_dim } else { p.line_soft }; let shown = egui::Frame::new() .fill(p.bg_1) .stroke(Stroke::new(1.0, edge)) @@ -331,12 +281,7 @@ fn time_row(ui: &mut Ui, time: &ZoneTime, removable: bool, language: Language) - }); ui.vertical(|ui| { ui.spacing_mut().item_spacing.y = gap::LINE; - let hour = crate::tools::ui::paragraph( - ui, - &time.time, - (font::HEADING, 600.0), - p.text_0, - ); + let hour = crate::tools::ui::paragraph(ui, &time.time, (font::HEADING, 600.0), p.text_0); address(ui, &hour, "zones-time"); hint(ui, &date_words(time, language)); }); @@ -354,18 +299,13 @@ fn time_row(ui: &mut Ui, time: &ZoneTime, removable: bool, language: Language) - asked = Some(RowAsked::Remove); } if !time.source - && Button::new( - &tr(keys::tools::zones::HERE), - &format!("zones-type-in-{}", time.zone), - ) - .show(ui) - .clicked() + && Button::new(&tr(keys::tools::zones::HERE), &format!("zones-type-in-{}", time.zone)) + .show(ui) + .clicked() { asked = Some(RowAsked::Here); } - CopyValue::new(&time.iso, &time.zone, language) - .compact() - .show(ui); + CopyValue::new(&time.iso, &time.zone, language).compact().show(ui); }); }); }); @@ -396,11 +336,9 @@ impl Tool for ZonesTool { zones: self.zones.clone(), later: self.later, }); - self.answer - .update(turn, request, api::tools::place_in_zones); + self.answer.update(turn, request, api::tools::place_in_zones); let query = (!self.query.trim().is_empty()).then(|| self.query.clone()); - self.found - .update(turn, query, api::tools::search_time_zones); + self.found.update(turn, query, api::tools::search_time_zones); } fn ui(&mut self, ui: &mut Ui, drawn: &mut Drawn<'_>) { @@ -423,10 +361,8 @@ impl Tool for ZonesTool { .iter() .map(|time| { let name = time.abbreviation.as_deref().unwrap_or_default(); - let line = format!( - "{:24} {} {} UTC{} {name}", - time.zone, time.date, time.time, time.offset - ); + let line = + format!("{:24} {} {} UTC{} {name}", time.zone, time.date, time.time, time.offset); line.trim_end().to_owned() }) .collect(); diff --git a/crates/ui/src/tools/frame.rs b/crates/ui/src/tools/frame.rs index 2faf9bc24..1cd31c8bd 100644 --- a/crates/ui/src/tools/frame.rs +++ b/crates/ui/src/tools/frame.rs @@ -38,13 +38,8 @@ pub(super) fn show( .layout(egui::Layout::top_down(egui::Align::Min)), ); content.set_clip_rect(body); - let mut drawn = Drawn { - entry, - language: state.language, - now: state.clock.now(), - actions, - importing: None, - }; + let mut drawn = + Drawn { entry, language: state.language, now: state.clock.now(), actions, importing: None }; view.session(entry).ui(&mut content, &mut drawn); if let Some((field, slot)) = drawn.importing && let Some((_, accepts)) = entry.from_note.iter().find(|(name, _)| *name == field) @@ -82,27 +77,16 @@ fn head( if tool.keeps_result() { save_as_note(ui, entry, tool, language, actions); } - if Button::new(&tr(keys::tools::CLEAR), "tool-clear") - .show(ui) - .clicked() - { + if Button::new(&tr(keys::tools::CLEAR), "tool-clear").show(ui).clicked() { tool.clear(); } - if tool.has_sample() - && Button::new(&tr(keys::tools::SAMPLE), "tool-sample") - .show(ui) - .clicked() - { + if tool.has_sample() && Button::new(&tr(keys::tools::SAMPLE), "tool-sample").show(ui).clicked() { tool.sample(language); actions.push(Asked::Tools(Action::SampleLoaded)); } for action in tool.actions().into_iter().rev() { let id = format!("tool-action-{}", action.id); - if Button::new(&tr(action.label), &id) - .enabled(action.enabled) - .show(ui) - .clicked() - { + if Button::new(&tr(action.label), &id).enabled(action.enabled).show(ui).clicked() { tool.run_action(action.id, ui.ctx()); } } @@ -145,14 +129,7 @@ fn save_as_note( fn crumb(ui: &mut Ui, words: &str) -> egui::Response { let p = palette(ui.ctx()); let shown = format!("{words} ›"); - let galley = widgets::text( - ui, - &shown, - font::BODY, - 400.0, - egui::FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &shown, font::BODY, 400.0, egui::FontFamily::Proportional, p.text_2); let response = interact( ui, galley.size(), diff --git a/crates/ui/src/tools/home.rs b/crates/ui/src/tools/home.rs index bc5cb3254..90a8bbc4b 100644 --- a/crates/ui/src/tools/home.rs +++ b/crates/ui/src/tools/home.rs @@ -5,8 +5,8 @@ mod hits; use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Id, Key, Modifiers, Pos2, Rect, Response, Role, Sense, - Stroke, Ui, UiBuilder, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, Id, Key, Modifiers, Pos2, Rect, Response, Role, Sense, Stroke, Ui, + UiBuilder, Vec2, WidgetInfo, }; use i18n::{Language, Message, keys}; @@ -58,22 +58,13 @@ struct Panel { tools: Vec<&'static ToolEntry>, } -pub(super) fn show( - ui: &mut Ui, - rest: Rect, - state: &AppState, - view: &mut HomeView, - actions: &mut Actions, -) { +pub(super) fn show(ui: &mut Ui, rest: Rect, state: &AppState, view: &mut HomeView, actions: &mut Actions) { let (mut row, body) = bar(ui, rest, state, actions); empty_on_escape(ui, view); let field = head(&mut row, state, view, actions); view.typing = widgets::takes_keys(ui, &field); let found = panels(state, view); - let first = view - .searching() - .then(|| found.first()?.tools.first().copied()) - .flatten(); + let first = view.searching().then(|| found.first()?.tools.first().copied()).flatten(); let mut content = ui.new_child(UiBuilder::new().max_rect(body)); view.results.clear(); view.references.search(view.search.trim(), state.language); @@ -102,11 +93,7 @@ pub(super) fn show( /// The panels a search or a filter leaves, in the home's order. fn panels(state: &AppState, view: &HomeView) -> Vec { let query = api::tools::fold(view.search.trim()); - let only = if view.searching() { - None - } else { - state.tools.filter() - }; + let only = if view.searching() { None } else { state.tools.filter() }; let language = state.language; let shown = |tool: &ToolEntry| { (only != Some(Filter::Favourites) || state.tools.is_favourite(tool.id)) @@ -117,10 +104,7 @@ fn panels(state: &AppState, view: &HomeView) -> Vec { .filter(|category| !matches!(only, Some(Filter::Category(wanted)) if wanted != *category)) .map(|category| Panel { category, - tools: TOOLS - .iter() - .filter(|tool| tool.category == category && shown(tool)) - .collect(), + tools: TOOLS.iter().filter(|tool| tool.category == category && shown(tool)).collect(), }) .filter(|panel| !panel.tools.is_empty()) .collect() @@ -143,23 +127,12 @@ fn head(ui: &mut Ui, state: &AppState, view: &mut HomeView, actions: &mut Action let language = state.language; let tr = |key| i18n::translate(language, key, &[]); let title = tr(keys::tools::TITLE); - let galley = widgets::text( - ui, - &title, - font::HEADING, - 700.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, &title, font::HEADING, 700.0, FontFamily::Proportional, p.text_0); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Heading, true, &title)); ui.painter().galley(rect.min, galley, p.text_0); let width = 380.0_f32.min(ui.max_rect().width() * 0.4); - let hidden = if state.settings.rail_shown || view.searching() { - None - } else { - state.tools.filter() - }; + let hidden = if state.settings.rail_shown || view.searching() { None } else { state.tools.filter() }; let room = ui.available_width() - width - 16.0; match hidden { Some(filter) => filtered(ui, filter, language, actions), @@ -168,20 +141,13 @@ fn head(ui: &mut Ui, state: &AppState, view: &mut HomeView, actions: &mut Action ui.add_space((ui.available_width() - width).max(0.0)); let searched = ui .scope(|ui| { - let (hint, keys_said) = ( - tr(keys::tools::SEARCH_PLACEHOLDER), - tr(keys::tools::SEARCH_KEYS), - ); - SearchField::new( - &mut view.search, - &tr(keys::tools::SEARCH_LABEL), - "tools-search", - ) - .hint(&hint) - .key(&keys_said) - .clear(&tr(keys::notes::CLEAR_SEARCH), "tools-search-clear") - .width(width) - .show(ui) + let (hint, keys_said) = (tr(keys::tools::SEARCH_PLACEHOLDER), tr(keys::tools::SEARCH_KEYS)); + SearchField::new(&mut view.search, &tr(keys::tools::SEARCH_LABEL), "tools-search") + .hint(&hint) + .key(&keys_said) + .clear(&tr(keys::notes::CLEAR_SEARCH), "tools-search-clear") + .width(width) + .show(ui) }) .inner; if searched.cleared { @@ -198,18 +164,13 @@ fn head(ui: &mut Ui, state: &AppState, view: &mut HomeView, actions: &mut Action fn subtitle(ui: &mut Ui, language: Language, room: f32) { let p = palette(ui.ctx()); let count = u32::try_from(TOOLS.len()).unwrap_or(u32::MAX); - let words = Message::new(keys::tools::COUNT) - .with("count", count) - .text(language); + let words = Message::new(keys::tools::COUNT).with("count", count).text(language); let galley = widgets::one_line(ui, &words, (font::LABEL, 400.0), p.text_2, room); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); address(ui, &response, "tools-count"); ui.painter().galley(rect.min, galley, p.text_2); - widgets::tooltip( - response, - &i18n::translate(language, keys::tools::OFFLINE, &[]), - ); + widgets::tooltip(response, &i18n::translate(language, keys::tools::OFFLINE, &[])); } /// The rail is what says which category is showing: without it, the filter would be invisible. @@ -220,27 +181,13 @@ fn filtered(ui: &mut Ui, filter: Filter, language: Language, actions: &mut Actio Filter::Favourites => keys::tools::favourites::TITLE, }; let words = format!("› {}", i18n::translate(language, name, &[])); - let galley = widgets::text( - ui, - &words, - font::SUBTITLE, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, &words, font::SUBTITLE, 600.0, FontFamily::Proportional, p.text_0); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, &words)); address(ui, &response, "tools-category-shown"); ui.painter().galley(rect.min, galley, p.text_0); let all = i18n::translate(language, keys::tools::ALL, &[]); - let back = widgets::text( - ui, - &all, - font::BODY, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let back = widgets::text(ui, &all, font::BODY, 400.0, FontFamily::Proportional, p.text_2); let response = interact( ui, back.size() + Vec2::new(12.0, 0.0), @@ -252,8 +199,7 @@ fn filtered(ui: &mut Ui, filter: Filter, language: Language, actions: &mut Actio let ink = towards(p.text_2, p.text_0, hovered(ui, &response)); let at = response.rect.center() - back.size() / 2.0; let line = at.y + back.size().y; - ui.painter() - .hline(at.x..=at.x + back.size().x, line, (1.0, ink)); + ui.painter().hline(at.x..=at.x + back.size().x, line, (1.0, ink)); ui.painter().galley(at, back, ink); if response.clicked() { actions.push(Asked::Tools(Action::Home(None))); @@ -289,10 +235,7 @@ fn favourites(ui: &mut Ui, state: &AppState, actions: &mut Actions) { return; } let language = state.language; - section_title( - ui, - &i18n::translate(language, keys::tools::favourites::TITLE, &[]), - ); + section_title(ui, &i18n::translate(language, keys::tools::favourites::TITLE, &[])); ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = Vec2::splat(gap::CONTROLS); for tool in tools { @@ -333,34 +276,17 @@ fn recents(ui: &mut Ui, state: &AppState, actions: &mut Actions) { ui.add_space(SECTION_GAP); } -fn chip( - ui: &mut Ui, - tool: &ToolEntry, - language: Language, - when: Option<&str>, - author_id: &str, -) -> Response { +fn chip(ui: &mut Ui, tool: &ToolEntry, language: Language, when: Option<&str>, author_id: &str) -> Response { let p = palette(ui.ctx()); let name = tool.name(language); let galley = widgets::wrapped(ui, &name, (font::BODY, 400.0), p.text_0, f32::INFINITY); - let when = when.map(|when| { - widgets::text( - ui, - when, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ) - }); + let when = + when.map(|when| widgets::text(ui, when, font::META, 400.0, FontFamily::Proportional, p.text_2)); let room = when.as_ref().map_or(0.0, |when| when.size().x + 8.0); let corner = CornerRadius::same(radius::MENU); let response = interact( ui, - Vec2::new( - 10.0 + 8.0 + 8.0 + galley.size().x + room + 14.0, - galley.size().y + 16.0, - ), + Vec2::new(10.0 + 8.0 + 8.0 + galley.size().x + room + 14.0, galley.size().y + 16.0), Sense::click(), author_id, || WidgetInfo::labeled(Role::Button, true, &name), @@ -368,13 +294,8 @@ fn chip( ); let rect = response.rect; let edge = towards(p.line_soft, p.amber_dim, hovered(ui, &response)); - ui.painter().rect( - rect, - corner, - p.bg_1, - Stroke::new(1.0, edge), - egui::StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, p.bg_1, Stroke::new(1.0, edge), egui::StrokeKind::Inside); let middle = rect.center().y; let dot = Rect::from_center_size(Pos2::new(rect.left() + 14.0, middle), Vec2::splat(8.0)); ui.painter() @@ -392,11 +313,7 @@ fn chip( /// As many columns of at least `min` as `width` holds, `gap` between each; never none. fn column_count(width: f32, min: f32, gap: f32) -> usize { - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a few columns" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a few columns")] let count = ((width + gap) / (min + gap)).floor() as usize; count.max(1) } @@ -481,10 +398,7 @@ fn panel_of( let last = panel.tools.len() - 1; for (rank, tool) in panel.tools.iter().copied().enumerate() { let is_first = first.is_some_and(|it| std::ptr::eq(it, tool)); - let place = Place { - first: is_first, - last: rank == last, - }; + let place = Place { first: is_first, last: rank == last }; tool_row(ui, state, view, (tool, place), actions); } }); @@ -494,41 +408,20 @@ fn panel_head(ui: &mut Ui, panel: &Panel, language: Language) { let p = palette(ui.ctx()); let width = ui.available_width(); let (rect, _) = ui.allocate_exact_size(Vec2::new(width, 53.0), Sense::hover()); - ui.painter() - .hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); let hue = panel.category.hue(p); let tile = Rect::from_min_size(rect.min + Vec2::new(14.0, 12.0), Vec2::splat(28.0)); - ui.painter().rect_filled( - tile, - CornerRadius::same(radius::CONTROL), - hue.gamma_multiply(0.15), - ); + ui.painter() + .rect_filled(tile, CornerRadius::same(radius::CONTROL), hue.gamma_multiply(0.15)); let glyph = Rect::from_center_size(tile.center(), Vec2::splat(15.0)); icons::paint(ui, glyph, panel.category.icon(), hue); let name = i18n::translate(language, panel.category.name(), &[]); - let galley = widgets::text( - ui, - &name, - font::READING, - 700.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = widgets::text(ui, &name, font::READING, 700.0, FontFamily::Proportional, p.text_0); let at = Pos2::new(tile.right() + 10.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_0); let count = panel.tools.len().to_string(); - let galley = widgets::text( - ui, - &count, - font::META, - 400.0, - FontFamily::Monospace, - p.text_2, - ); - let at = Pos2::new( - rect.right() - 14.0 - galley.size().x, - rect.center().y - galley.size().y / 2.0, - ); + let galley = widgets::text(ui, &count, font::META, 400.0, FontFamily::Monospace, p.text_2); + let at = Pos2::new(rect.right() - 14.0 - galley.size().x, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_2); } @@ -553,23 +446,10 @@ fn tool_row( let name = tool.name(language); let room = width - 14.0 - 44.0; let title = widgets::wrapped(ui, &name, (font::READING, 600.0), p.text_0, room); - let line = widgets::wrapped( - ui, - &tool.line(language), - (font::CONTROL, 400.0), - p.text_2, - room, - ); + let line = widgets::wrapped(ui, &tool.line(language), (font::CONTROL, 400.0), p.text_2, room); let height = 10.0 + title.size().y + 3.0 + line.size().y + 10.0; - let corner = if place.last { - CornerRadius { - sw: 12, - se: 12, - ..CornerRadius::ZERO - } - } else { - CornerRadius::ZERO - }; + let corner = + if place.last { CornerRadius { sw: 12, se: 12, ..CornerRadius::ZERO } } else { CornerRadius::ZERO }; let response = interact( ui, Vec2::new(width, height), @@ -583,8 +463,7 @@ fn tool_row( let fill = towards(Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)); ui.painter().rect_filled(rect, corner, fill); if !place.last { - ui.painter() - .hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.bg_2)); + ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.bg_2)); } let left = rect.left() + 14.0; let title_size = title.size(); @@ -592,11 +471,7 @@ fn tool_row( let below = rect.top() + 10.0 + title_size.y + 3.0; line.paint(ui, Pos2::new(left, below), p.text_2); if place.first { - enter_mark( - ui, - Pos2::new(left + title_size.x + 6.0, rect.top() + 9.0), - language, - ); + enter_mark(ui, Pos2::new(left + title_size.x + 6.0, rect.top() + 9.0), language); } if response.clicked() { actions.push(Asked::Tools(Action::Open(tool.id))); @@ -634,10 +509,7 @@ fn tool_star( actions: &mut Actions, ) { let on = state.tools.is_favourite(tool.id); - let place = Rect::from_min_size( - row.rect.right_top() + Vec2::new(-36.0, 8.0), - Vec2::splat(28.0), - ); + let place = Rect::from_min_size(row.rect.right_top() + Vec2::new(-36.0, 8.0), Vec2::splat(28.0)); let mut layer = ui.new_child(UiBuilder::new().max_rect(place)); let id = layer.next_auto_id(); let lit = on || ui.rect_contains_pointer(row.rect) || ui.memory(|memory| memory.has_focus(id)); @@ -646,23 +518,13 @@ fn tool_star( .with("name", name) .text(state.language); let author = format!("tools-entry-star-{}", tool.id); - if star( - &mut layer, - on, - &label, - &author, - &star_hint(state.language, on), - ) - .clicked() - { + if star(&mut layer, on, &label, &author, &star_hint(state.language, on)).clicked() { actions.push(Asked::Tools(Action::ToggleFavourite(tool.id))); } } fn no_match(ui: &mut Ui, language: Language, query: &str) { - let words = Message::new(keys::tools::NO_MATCH) - .with("query", query) - .text(language); + let words = Message::new(keys::tools::NO_MATCH).with("query", query).text(language); let room = ui.available_rect_before_wrap(); widgets::empty_state(ui, room, (&words, "tools-no-match"), &[]); } diff --git a/crates/ui/src/tools/home/hits.rs b/crates/ui/src/tools/home/hits.rs index e439f2450..92b6d2f55 100644 --- a/crates/ui/src/tools/home/hits.rs +++ b/crates/ui/src/tools/home/hits.rs @@ -74,17 +74,9 @@ fn found_in((tool, table): &(&'static ToolEntry, Table), query: &str) -> Option< let hits: Vec = rows .iter() .take(HITS_PER_REFERENCE) - .map(|row| Hit { - key: row.key.clone(), - title: row.found_as.0.clone(), - line: row.found_as.1.clone(), - }) + .map(|row| Hit { key: row.key.clone(), title: row.found_as.0.clone(), line: row.found_as.1.clone() }) .collect(); - (!hits.is_empty()).then(|| Found { - tool, - hits, - more: rows.len().saturating_sub(HITS_PER_REFERENCE), - }) + (!hits.is_empty()).then(|| Found { tool, hits, more: rows.len().saturating_sub(HITS_PER_REFERENCE) }) } /// On that row: its table whole, the row brought into view and lit. @@ -162,17 +154,13 @@ fn hit_row( view.results.push(response.id); let rect = response.rect; let fill = towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)); - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), fill); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), fill); let left = rect.left() + 14.0; let title_size = title.size(); title.paint(ui, Pos2::new(left, rect.top() + 8.0), p.text_0); let below = rect.top() + 8.0 + title_size.y + 2.0; line.paint(ui, Pos2::new(left, below), p.text_2); - let at = Pos2::new( - rect.right() - 14.0 - where_.size().x, - rect.center().y - where_.size().y / 2.0, - ); + let at = Pos2::new(rect.right() - 14.0 - where_.size().x, rect.center().y - where_.size().y / 2.0); where_.paint(ui, at, p.text_2); if first { let cap = Pos2::new(left + title_size.x + 6.0, rect.top() + 7.0); @@ -206,8 +194,7 @@ fn more_row( view.results.push(response.id); let rect = response.rect; let fill = towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)); - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::MENU), fill); + ui.painter().rect_filled(rect, CornerRadius::same(radius::MENU), fill); shown.paint(ui, rect.min + Vec2::new(14.0, 6.0), p.amber_text); response } diff --git a/crates/ui/src/tools/live.rs b/crates/ui/src/tools/live.rs index 6c17f4cb8..c0513c793 100644 --- a/crates/ui/src/tools/live.rs +++ b/crates/ui/src/tools/live.rs @@ -48,10 +48,7 @@ impl Default for Live { impl Live { /// For what costs more to compute: two whole texts compared. pub fn slower(delay: f64) -> Self { - Self { - delay, - ..Self::default() - } + Self { delay, ..Self::default() } } /// What the inputs ask now, `None` for nothing, and the answer that came. The first request @@ -112,11 +109,7 @@ impl Live { /// Tests only: one frame's `Turn` over `backend`, the platform doing nothing. #[cfg(test)] -pub(crate) fn on_a_turn( - backend: &Backend, - time: f64, - run: impl FnOnce(&mut Turn<'_>) -> R, -) -> R { +pub(crate) fn on_a_turn(backend: &Backend, time: f64, run: impl FnOnce(&mut Turn<'_>) -> R) -> R { let ctx = egui::Context::default(); let mut errors = ErrorNotifier::default(); let mut status = StatusNotifier::default(); diff --git a/crates/ui/src/tools/mod.rs b/crates/ui/src/tools/mod.rs index e7e4b277a..dc5916d36 100644 --- a/crates/ui/src/tools/mod.rs +++ b/crates/ui/src/tools/mod.rs @@ -115,10 +115,7 @@ impl ToolResult { let (Some(first), Some(second)) = (&first, &second) else { return first.or(second); }; - Some(Self { - content: format!("{}\n\n{}", first.content, second.content), - ..first.clone() - }) + Some(Self { content: format!("{}\n\n{}", first.content, second.content), ..first.clone() }) } } @@ -164,10 +161,7 @@ impl View { /// The tool on screen, its session made the first time it is opened. fn session(&mut self, entry: &'static ToolEntry) -> &mut dyn Tool { - self.sessions - .entry(entry.id) - .or_insert_with(entry.make) - .as_mut() + self.sessions.entry(entry.id).or_insert_with(entry.make).as_mut() } pub fn update(&mut self, entry: &'static ToolEntry, turn: &mut Turn<'_>) { @@ -202,17 +196,12 @@ impl View { } pub fn show(ui: &mut Ui, state: &AppState, view: &mut View, actions: &mut Actions) { - let region = widgets::area_room( - ui, - "area-tools", - &i18n::translate(state.language, i18n::keys::areas::TOOLS, &[]), - ); + let region = + widgets::area_room(ui, "area-tools", &i18n::translate(state.language, i18n::keys::areas::TOOLS, &[])); let rail = (state.settings.rail_shown, state.settings.rail_width); - let rest = view - .rail_width - .beside(ui, region, rail, "tools-rail-edge", |ui| { - rail::show(ui, state, actions); - }); + let rest = view.rail_width.beside(ui, region, rail, "tools-rail-edge", |ui| { + rail::show(ui, state, actions); + }); let mut page = ui.new_child(UiBuilder::new().max_rect(rest)); page.set_clip_rect(rest); if let Some(entry) = state.tools.open_tool() { @@ -248,8 +237,7 @@ fn bar(ui: &mut Ui, rest: Rect, state: &AppState, actions: &mut Actions) -> (Ui, use crate::theme::tokens::{BAR_HEIGHT, BAR_INSET}; let p = palette(ui.ctx()); let (bar, body) = rest.split_top_bottom_at_y(rest.top() + BAR_HEIGHT); - ui.painter() - .hline(bar.x_range(), bar.bottom() - 0.5, (1.0, p.line_soft)); + ui.painter().hline(bar.x_range(), bar.bottom() - 0.5, (1.0, p.line_soft)); let inner = bar.shrink2(Vec2::new(BAR_INSET, 0.0)); let mut row = ui.new_child( UiBuilder::new() @@ -259,12 +247,7 @@ fn bar(ui: &mut Ui, rest: Rect, state: &AppState, actions: &mut Actions) -> (Ui, row.spacing_mut().item_spacing.x = gap::GROUPS; let toggle = i18n::translate(state.language, keys::sidebar::TOGGLE, &[]); if widgets::SquareButton::new(Icon::Sidebar, &toggle, "tools-rail-toggle") - .keys( - state - .settings - .bindings - .of(crate::services::shortcuts::RAIL_ACTION), - ) + .keys(state.settings.bindings.of(crate::services::shortcuts::RAIL_ACTION)) .pressed(state.settings.rail_shown) .show(&mut row) .clicked() @@ -286,11 +269,7 @@ fn star(ui: &mut Ui, on: bool, label: &str, author_id: &str, hint: &str) -> Resp corner, ); let p = palette(ui.ctx()); - let ink = if on { - p.amber_text - } else { - towards(p.text_2, p.text_0, hovered(ui, &response)) - }; + let ink = if on { p.amber_text } else { towards(p.text_2, p.text_0, hovered(ui, &response)) }; let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(15.0)); let icon = if on { Icon::StarFilled } else { Icon::Star }; icons::paint(ui, glyph, icon, ink); @@ -298,11 +277,7 @@ fn star(ui: &mut Ui, on: bool, label: &str, author_id: &str, hint: &str) -> Resp } fn star_hint(language: Language, on: bool) -> String { - let key = if on { - keys::tools::favourites::REMOVE - } else { - keys::tools::favourites::ADD - }; + let key = if on { keys::tools::favourites::REMOVE } else { keys::tools::favourites::ADD }; i18n::translate(language, key, &[]) } diff --git a/crates/ui/src/tools/rail.rs b/crates/ui/src/tools/rail.rs index 737a61623..cec5b4ba2 100644 --- a/crates/ui/src/tools/rail.rs +++ b/crates/ui/src/tools/rail.rs @@ -2,9 +2,7 @@ //! In the frame the three areas share, so going from one to the other moves nothing. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - Color32, CornerRadius, FontFamily, Margin, Pos2, Rect, Role, Sense, Ui, Vec2, WidgetInfo, -}; +use egui::{Color32, CornerRadius, FontFamily, Margin, Pos2, Rect, Role, Sense, Ui, Vec2, WidgetInfo}; use i18n::keys; use super::catalogue::{self, Category, TOOLS, ToolEntry}; @@ -19,12 +17,7 @@ use crate::widgets::{self, hovered, interact, towards}; pub(super) fn show(ui: &mut Ui, state: &AppState, actions: &mut Actions) { let s = spacing(ui.ctx()); #[expect(clippy::cast_possible_truncation, reason = "a few points")] - let margin = Margin { - left: 10, - right: 10, - top: s.card as i8, - bottom: s.canvas as i8, - }; + let margin = Margin { left: 10, right: 10, top: s.card as i8, bottom: s.canvas as i8 }; egui::ScrollArea::vertical() .id_salt("tools-rail") .auto_shrink(false) @@ -73,9 +66,7 @@ fn categories(ui: &mut Ui, state: &AppState, filter: Option, actions: &m let words = i18n::translate(state.language, category.name(), &[]); let on = filter == Some(Filter::Category(category)); let id = format!("tools-rail-category-{}", category.id()); - let link = Link::new(&words, &id, on) - .lead(Lead::Hue(category.hue(p))) - .count(count); + let link = Link::new(&words, &id, on).lead(Lead::Hue(category.hue(p))).count(count); if link.show(ui).clicked() { actions.push(Asked::Tools(Action::Home(Some(Filter::Category(category))))); } @@ -100,10 +91,7 @@ fn around_a_tool(ui: &mut Ui, state: &AppState, tool: &ToolEntry, actions: &mut for sibling in catalogue::in_category(tool.category) { let words = sibling.name(language); let id = format!("tools-rail-tool-{}", sibling.id); - if Link::new(&words, &id, sibling.id == tool.id) - .show(ui) - .clicked() - { + if Link::new(&words, &id, sibling.id == tool.id).show(ui).clicked() { actions.push(Asked::Tools(Action::Open(sibling.id))); } } @@ -114,11 +102,8 @@ fn around_a_tool(ui: &mut Ui, state: &AppState, tool: &ToolEntry, actions: &mut ui.add_space(gap::GROUPS); let p = palette(ui.ctx()); let (line, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 1.0), Sense::hover()); - ui.painter().hline( - line.shrink2(Vec2::new(10.0, 0.0)).x_range(), - line.top(), - (1.0, p.line_soft), - ); + ui.painter() + .hline(line.shrink2(Vec2::new(10.0, 0.0)).x_range(), line.top(), (1.0, p.line_soft)); heading(ui, &i18n::translate(language, keys::tools::RECENTS, &[])); for recent in recents { let words = recent.name(language); @@ -133,20 +118,11 @@ fn around_a_tool(ui: &mut Ui, state: &AppState, tool: &ToolEntry, actions: &mut fn heading(ui: &mut Ui, words: &str) { let p = palette(ui.ctx()); ui.add_space(gap::BLOCKS); - let galley = widgets::text( - ui, - words, - font::CONTROL, - 500.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, words, font::CONTROL, 500.0, FontFamily::Proportional, p.text_2); let height = galley.size().y + 4.0; - let (rect, response) = - ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); - ui.painter() - .galley(rect.min + Vec2::new(10.0, 0.0), galley, p.text_2); + ui.painter().galley(rect.min + Vec2::new(10.0, 0.0), galley, p.text_2); } enum Lead { @@ -166,13 +142,7 @@ struct Link<'a> { impl<'a> Link<'a> { fn new(words: &'a str, author_id: &'a str, on: bool) -> Self { - Self { - words, - author_id, - on, - lead: Lead::None, - count: None, - } + Self { words, author_id, on, lead: Lead::None, count: None } } fn lead(mut self, lead: Lead) -> Self { @@ -192,14 +162,7 @@ impl<'a> Link<'a> { let width = ui.available_width(); let count = self.count.map(|count| { let ink = if self.on { p.amber_text } else { p.text_2 }; - widgets::text( - ui, - &count.to_string(), - font::META, - 400.0, - FontFamily::Monospace, - ink, - ) + widgets::text(ui, &count.to_string(), font::META, 400.0, FontFamily::Monospace, ink) }); let lead = match self.lead { Lead::None => 0.0, @@ -219,34 +182,26 @@ impl<'a> Link<'a> { corner, ); let rect = response.rect; - let fill = if self.on { - p.bg_3 - } else { - towards(Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)) - }; + let fill = + if self.on { p.bg_3 } else { towards(Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)) }; ui.painter().rect_filled(rect, corner, fill); let middle = rect.center().y; let left = rect.left() + 10.0; match self.lead { Lead::None => {} Lead::Star => { - let glyph = - Rect::from_center_size(Pos2::new(left + 6.5, middle), Vec2::splat(13.0)); + let glyph = Rect::from_center_size(Pos2::new(left + 6.5, middle), Vec2::splat(13.0)); icons::paint(ui, glyph, Icon::StarFilled, p.amber_text); } Lead::Hue(hue) => { let dot = Rect::from_center_size(Pos2::new(left + 4.0, middle), Vec2::splat(8.0)); - ui.painter() - .rect_filled(dot, CornerRadius::same(radius::MARK), hue); + ui.painter().rect_filled(dot, CornerRadius::same(radius::MARK), hue); } } let top = middle - label.size().y / 2.0; label.paint(ui, Pos2::new(left + lead, top), ink); if let Some(count) = count { - let at = Pos2::new( - rect.right() - 10.0 - count.size().x, - middle - count.size().y / 2.0, - ); + let at = Pos2::new(rect.right() - 10.0 - count.size().x, middle - count.size().y / 2.0); ui.painter().galley(at, count, p.text_2); } response diff --git a/crates/ui/src/tools/tests.rs b/crates/ui/src/tools/tests.rs index 9304a5c4e..d8e7daa1d 100644 --- a/crates/ui/src/tools/tests.rs +++ b/crates/ui/src/tools/tests.rs @@ -26,19 +26,13 @@ fn click(harness: &mut Harness<'_, Bench>, id: &str) { } fn present(harness: &Harness<'_, Bench>, id: &str) -> bool { - harness - .query_by(|node| node.author_id() == Some(id)) - .is_some() + harness.query_by(|node| node.author_id() == Some(id)).is_some() } fn type_search(harness: &mut Harness<'_, Bench>, text: &str) { - harness - .get_by(|node| node.author_id() == Some("tools-search")) - .focus(); + harness.get_by(|node| node.author_id() == Some("tools-search")).focus(); harness.step(); - harness - .get_by(|node| node.author_id() == Some("tools-search")) - .type_text(text); + harness.get_by(|node| node.author_id() == Some("tools-search")).type_text(text); settle(harness); } @@ -61,10 +55,7 @@ fn the_home_lists_the_catalogue_and_says_how_many() { assert_eq!(entries(&harness).len(), 32); let count = harness.get_by(|node| node.author_id() == Some("tools-count")); - assert_eq!( - count.accesskit_node().value().as_deref(), - Some("32 utilities, all offline") - ); + assert_eq!(count.accesskit_node().value().as_deref(), Some("32 utilities, all offline")); } #[test] diff --git a/crates/ui/src/tools/ui/copy_value.rs b/crates/ui/src/tools/ui/copy_value.rs index e8ecc602b..09c637b0e 100644 --- a/crates/ui/src/tools/ui/copy_value.rs +++ b/crates/ui/src/tools/ui/copy_value.rs @@ -1,9 +1,7 @@ //! « Copy », beside a result, and what it says for a moment once done. use crate::theme::tokens::{font, gap, radius}; -use egui::{ - CornerRadius, FontFamily, Id, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, -}; +use egui::{CornerRadius, FontFamily, Id, Rect, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo}; use i18n::{Key, Language, Message, keys}; use crate::theme::icons::{self, Icon}; @@ -23,14 +21,7 @@ pub struct CopyValue<'a> { impl<'a> CopyValue<'a> { pub fn new(value: &'a str, what: &'a str, language: Language) -> Self { - Self { - value, - what, - language, - compact: false, - raw: false, - label: keys::tools::COPY, - } + Self { value, what, language, compact: false, raw: false, label: keys::tools::COPY } } /// The icon alone, at the end of a row: its word is the tooltip's. @@ -58,11 +49,7 @@ impl<'a> CopyValue<'a> { let time = ui.input(|input| input.time); let copied = copied_until(ui, id).is_some_and(|until| until > time); let enabled = !self.value.is_empty(); - let key = if copied { - keys::tools::COPIED - } else { - self.label - }; + let key = if copied { keys::tools::COPIED } else { self.label }; let word = i18n::translate(self.language, key, &[]); let response = if self.raw { self.word(ui, copied) @@ -81,14 +68,8 @@ impl<'a> CopyValue<'a> { } fn accessible_name(&self) -> String { - let key = if self.raw { - keys::tools::COPY_RAW_WHAT - } else { - keys::tools::COPY_WHAT - }; - Message::new(key) - .with("what", self.what) - .text(self.language) + let key = if self.raw { keys::tools::COPY_RAW_WHAT } else { keys::tools::COPY_WHAT }; + Message::new(key).with("what", self.what).text(self.language) } fn word(&self, ui: &mut Ui, copied: bool) -> Response { @@ -119,8 +100,7 @@ impl<'a> CopyValue<'a> { } else { let ink = towards(p.text_2, p.text_0, hover); let at = pill.center() - galley.size() / 2.0; - ui.painter() - .galley_with_override_text_color(at, galley, ink); + ui.painter().galley_with_override_text_color(at, galley, ink); } let hint = i18n::translate(self.language, keys::tools::COPY_RAW_HINT, &[]); widgets::tooltip(response, &hint) @@ -148,11 +128,7 @@ impl<'a> CopyValue<'a> { egui::StrokeKind::Inside, ); } - let ink = if copied { - p.green - } else { - towards(p.text_2, p.text_0, hover) - }; + let ink = if copied { p.green } else { towards(p.text_2, p.text_0, hover) }; let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(12.0)); icons::paint(ui, glyph, mark(copied), ink); widgets::tooltip(response, word) @@ -161,14 +137,7 @@ impl<'a> CopyValue<'a> { fn framed(&self, ui: &mut Ui, copied: bool, enabled: bool, word: &str) -> Response { let p = palette(ui.ctx()); let name = self.accessible_name(); - let galley = widgets::text( - ui, - word, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, word, font::CONTROL, 400.0, FontFamily::Proportional, p.text_1); let corner = CornerRadius::same(radius::CONTROL); let response = interact( ui, @@ -187,15 +156,9 @@ impl<'a> CopyValue<'a> { Stroke::new(1.0, towards(p.line, p.amber_dim, hover)), egui::StrokeKind::Inside, ); - let ink = if copied { - p.amber_text - } else { - towards(p.text_1, p.text_0, hover) - }; - let glyph = Rect::from_center_size( - egui::pos2(rect.left() + 16.0, rect.center().y), - Vec2::splat(12.0), - ); + let ink = if copied { p.amber_text } else { towards(p.text_1, p.text_0, hover) }; + let glyph = + Rect::from_center_size(egui::pos2(rect.left() + 16.0, rect.center().y), Vec2::splat(12.0)); icons::paint(ui, glyph, mark(copied), ink); let at = egui::pos2(rect.left() + 28.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, ink); @@ -208,11 +171,7 @@ fn copied_until(ui: &Ui, id: Id) -> Option { } fn sense(enabled: bool) -> Sense { - if enabled { - Sense::click() - } else { - Sense::hover() - } + if enabled { Sense::click() } else { Sense::hover() } } fn mark(copied: bool) -> Icon { @@ -232,9 +191,7 @@ fn raw_word(ui: &Ui, language: Language) -> std::sync::Arc { /// What the copies of a result take at the end of its row. pub fn copies_width(ui: &Ui, (shown, raw): (&str, Option<&str>), language: Language) -> f32 { let second = raw.filter(|raw| *raw != shown); - 28.0 + second.map_or(0.0, |_| { - gap::LINE + raw_word(ui, language).size().x + RAW_ROOM - }) + 28.0 + second.map_or(0.0, |_| gap::LINE + raw_word(ui, language).size().x + RAW_ROOM) } /// The result as it is shown and, where it is written otherwise, as it is stored: two buttons diff --git a/crates/ui/src/tools/ui/mod.rs b/crates/ui/src/tools/ui/mod.rs index 91b5db0b3..9f2068925 100644 --- a/crates/ui/src/tools/ui/mod.rs +++ b/crates/ui/src/tools/ui/mod.rs @@ -17,8 +17,8 @@ pub use text_table::{TextColumn, text_table}; use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Id, Key, Margin, Modifiers, Response, Role, Sense, - Stroke, TextEdit, Ui, UiBuilder, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, FontId, Id, Key, Margin, Modifiers, Response, Role, Sense, Stroke, + TextEdit, Ui, UiBuilder, Vec2, WidgetInfo, }; use super::Drawn; @@ -37,12 +37,7 @@ const RESULTS_SHARE: f32 = 1.15; pub type Part = fn(&mut T, &mut Ui, &mut Drawn<'_>); /// What goes in on the left, what comes out on the right, each scrolling on its own. -pub fn columns( - ui: &mut Ui, - tool: &mut T, - drawn: &mut Drawn<'_>, - (left, right): (Part, Part), -) { +pub fn columns(ui: &mut Ui, tool: &mut T, drawn: &mut Drawn<'_>, (left, right): (Part, Part)) { if ui.ctx().content_rect().width() < NARROW { egui::ScrollArea::vertical() .id_salt("tool-column") @@ -61,12 +56,10 @@ pub fn columns( let second = rest.with_min_x(first.right() + COLUMN_GAP); for (rect, salt, part) in [(first, "tool-input", left), (second, "tool-output", right)] { let mut column = ui.new_child(UiBuilder::new().id_salt(salt).max_rect(rect)); - egui::ScrollArea::vertical() - .auto_shrink(false) - .show(&mut column, |ui| { - ui.spacing_mut().item_spacing.y = gap::INSET; - part(tool, ui, drawn); - }); + egui::ScrollArea::vertical().auto_shrink(false).show(&mut column, |ui| { + ui.spacing_mut().item_spacing.y = gap::INSET; + part(tool, ui, drawn); + }); } } @@ -74,14 +67,7 @@ pub fn columns( pub fn section_title(ui: &mut Ui, words: &str) { let p = palette(ui.ctx()); let shown = words.to_uppercase(); - let galley = widgets::text( - ui, - &shown, - font::META, - 700.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = widgets::text(ui, &shown, font::META, 700.0, FontFamily::Proportional, p.text_2); let (rect, response) = ui.allocate_exact_size(galley.size(), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Heading, true, words)); ui.painter().galley(rect.min, galley, p.text_2); @@ -185,14 +171,7 @@ pub fn named(language: i18n::Language, prefix: &str, value: &serde_json::Value) /// A checkbox and its label, in the accent. pub fn check(ui: &mut Ui, value: &mut bool, words: &str, author_id: &str) -> Response { let p = palette(ui.ctx()); - let label = widgets::text( - ui, - words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let label = widgets::text(ui, words, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); let on = *value; let response = widgets::interact( ui, @@ -206,23 +185,14 @@ pub fn check(ui: &mut Ui, value: &mut bool, words: &str, author_id: &str) -> Res *value = !*value; } let rect = response.rect; - let tick = egui::Rect::from_min_size( - egui::pos2(rect.left(), rect.center().y - 7.0), - Vec2::splat(14.0), - ); + let tick = egui::Rect::from_min_size(egui::pos2(rect.left(), rect.center().y - 7.0), Vec2::splat(14.0)); let corner = CornerRadius::same(radius::TAG); if *value { ui.painter().rect_filled(tick, corner, p.amber_fill); - crate::theme::icons::paint( - ui, - tick.shrink(1.5), - crate::theme::icons::Icon::Check, - p.amber_ink, - ); + crate::theme::icons::paint(ui, tick.shrink(1.5), crate::theme::icons::Icon::Check, p.amber_ink); } else { let edge = Stroke::new(1.0, p.line); - ui.painter() - .rect(tick, corner, p.bg_1, edge, egui::StrokeKind::Inside); + ui.painter().rect(tick, corner, p.bg_1, edge, egui::StrokeKind::Inside); } let at = egui::pos2(tick.right() + 7.0, rect.center().y - label.size().y / 2.0); ui.painter().galley(at, label, p.text_1); @@ -233,38 +203,19 @@ pub fn check(ui: &mut Ui, value: &mut bool, words: &str, author_id: &str) -> Res pub fn switch(ui: &mut Ui, value: &mut bool, words: &str, author_id: &str) -> Response { let p = palette(ui.ctx()); let response = widgets::switch(ui, words, author_id, value, true); - ui.label(widgets::text( - ui, - words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - )); + ui.label(widgets::text(ui, words, font::LABEL, 400.0, FontFamily::Proportional, p.text_1)); response } /// A state, at a glance: its words on a tint of its hue. pub fn pill(ui: &mut Ui, words: &str, hue: Color32) -> Response { let p = palette(ui.ctx()); - let shown = widgets::text( - ui, - words, - font::CONTROL, - 600.0, - FontFamily::Proportional, - p.text_1, - ); - let (rect, response) = - ui.allocate_exact_size(shown.size() + Vec2::new(16.0, 6.0), Sense::hover()); + let shown = widgets::text(ui, words, font::CONTROL, 600.0, FontFamily::Proportional, p.text_1); + let (rect, response) = ui.allocate_exact_size(shown.size() + Vec2::new(16.0, 6.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); - ui.painter().rect_filled( - rect, - CornerRadius::same(radius::MENU), - hue.gamma_multiply(0.18), - ); ui.painter() - .galley(rect.center() - shown.size() / 2.0, shown, p.text_1); + .rect_filled(rect, CornerRadius::same(radius::MENU), hue.gamma_multiply(0.18)); + ui.painter().galley(rect.center() - shown.size() / 2.0, shown, p.text_1); response } @@ -272,9 +223,7 @@ pub fn pill(ui: &mut Ui, words: &str, hue: Color32) -> Response { pub fn number_field(ui: &mut Ui, value: &mut String, name: &str, author_id: &str) -> Response { ui.scope(|ui| { ui.set_max_width(72.0); - widgets::TextField::new(value, name, author_id) - .compact() - .show(ui) + widgets::TextField::new(value, name, author_id).compact().show(ui) }) .inner } @@ -322,10 +271,7 @@ pub fn card(ui: &mut Ui, author_id: &str, rows: impl FnOnce(&mut Ui) -> R) -> .fill(p.bg_1) .stroke(Stroke::new(1.0, p.line_soft)) .corner_radius(CornerRadius::same(radius::CARD)) - .inner_margin(Margin { - bottom: 4, - ..Margin::ZERO - }) + .inner_margin(Margin { bottom: 4, ..Margin::ZERO }) .show(ui, |ui| { ui.set_width(ui.available_width()); ui.spacing_mut().item_spacing = Vec2::ZERO; @@ -362,10 +308,7 @@ pub(super) fn walk(ui: &Ui, results: &[Id], field: &Response) { let Some(at) = focused.and_then(|id| results.iter().position(|it| *it == id)) else { return; }; - let filter = egui::EventFilter { - vertical_arrows: true, - ..egui::EventFilter::default() - }; + let filter = egui::EventFilter { vertical_arrows: true, ..egui::EventFilter::default() }; ui.memory_mut(|memory| memory.set_focus_lock_filter(results[at], filter)); if pressed(Key::ArrowDown) && let Some(id) = results.get(at + 1) diff --git a/crates/ui/src/tools/ui/note_import.rs b/crates/ui/src/tools/ui/note_import.rs index f2165c989..27aa84d5d 100644 --- a/crates/ui/src/tools/ui/note_import.rs +++ b/crates/ui/src/tools/ui/note_import.rs @@ -28,14 +28,7 @@ pub fn note_import_into( } let p = palette(ui.ctx()); let words = i18n::translate(drawn.language, keys::tools::from_note::OPEN, &[]); - let galley = widgets::text( - ui, - &words, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let galley = widgets::text(ui, &words, font::CONTROL, 400.0, FontFamily::Proportional, p.text_1); let corner = CornerRadius::same(radius::CONTROL); let response = interact( ui, @@ -54,10 +47,7 @@ pub fn note_import_into( egui::StrokeKind::Inside, ); let ink = towards(p.text_1, p.text_0, hover); - let glyph = Rect::from_center_size( - Pos2::new(rect.left() + 16.5, rect.center().y), - Vec2::splat(13.0), - ); + let glyph = Rect::from_center_size(Pos2::new(rect.left() + 16.5, rect.center().y), Vec2::splat(13.0)); icons::paint(ui, glyph, Icon::FileText, ink); let at = Pos2::new(rect.left() + 29.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, ink); diff --git a/crates/ui/src/tools/ui/note_picker.rs b/crates/ui/src/tools/ui/note_picker.rs index 44d6682dc..cda5563e6 100644 --- a/crates/ui/src/tools/ui/note_picker.rs +++ b/crates/ui/src/tools/ui/note_picker.rs @@ -89,11 +89,7 @@ impl Picker { } } -pub(super) fn query( - search: String, - accepts: NoteInput, - now: chrono::DateTime, -) -> NotesQuery { +pub(super) fn query(search: String, accepts: NoteInput, now: chrono::DateTime) -> NotesQuery { NotesQuery { space_id: None, folder_id: None, @@ -115,10 +111,7 @@ pub(super) fn query( fn picked(note: &DisplayNote) -> PickedNote { PickedNote { title: note.title.clone(), - content: note - .copy_text - .clone() - .unwrap_or_else(|| note.content.clone()), + content: note.copy_text.clone().unwrap_or_else(|| note.content.clone()), language: (note.kind == NoteKind::Snippet).then_some(note.language), } } @@ -128,10 +121,7 @@ pub fn show(ui: &Ui, state: &AppState, picker: &mut Picker) { ui, ( "note-picker", - ( - &i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), - "note-picker-cross", - ), + (&i18n::translate(state.language, i18n::keys::dialog::CLOSE, &[]), "note-picker-cross"), ), |ui| body(ui, state, picker), ); @@ -152,12 +142,7 @@ fn body(ui: &mut Ui, state: &AppState, picker: &mut Picker) { let title = tr(keys::tools::from_note::TITLE); let heading = super::paragraph(ui, &title, (font::TITLE, 600.0), p.text_0); address(ui, &heading, "note-picker"); - let accepted = super::paragraph( - ui, - &accepted(picker.accepts, language), - (font::LABEL, 400.0), - p.text_2, - ); + let accepted = super::paragraph(ui, &accepted(picker.accepts, language), (font::LABEL, 400.0), p.text_2); address(ui, &accepted, "note-picker-accepted"); let label = tr(keys::tools::from_note::SEARCH); let field = TextField::new(&mut picker.search, &label, "note-picker-search") @@ -232,11 +217,7 @@ fn accepted(accepts: NoteInput, locale: i18n::Language) -> String { if accepts.languages.is_empty() { return i18n::translate(locale, keys::tools::from_note::ANY_NOTE, &[]); } - let names: Vec<&str> = accepts - .languages - .iter() - .map(|it| language::name(*it)) - .collect(); + let names: Vec<&str> = accepts.languages.iter().map(|it| language::name(*it)).collect(); Message::new(keys::tools::from_note::SNIPPETS) .with("languages", i18n::format::or_list(&names, locale)) .text(locale) @@ -273,21 +254,12 @@ fn option(ui: &mut Ui, state: &AppState, card: &engine::notes::view::Card) -> eg row.spacing_mut().item_spacing.x = gap::CONTROLS; let badge = kind_mark(&mut row, note.kind, note.language, locale); let place = where_of(state, card); - let tail = widgets::one_line( - &row, - &place, - (font::CONTROL, 400.0), - p.text_2, - inner.width() * 0.35, - ); + let tail = widgets::one_line(&row, &place, (font::CONTROL, 400.0), p.text_2, inner.width() * 0.35); let room = inner.right() - badge.rect.right() - tail.size().x - 24.0; let name = widgets::one_line(&row, &title, (font::READING, 400.0), p.text_0, room); let (at, _) = row.allocate_exact_size(name.size(), Sense::hover()); row.painter().galley(at.min, name, p.text_0); - let right = egui::pos2( - inner.right() - tail.size().x, - rect.center().y - tail.size().y / 2.0, - ); + let right = egui::pos2(inner.right() - tail.size().x, rect.center().y - tail.size().y / 2.0); row.painter().galley(right, tail, p.text_2); response } diff --git a/crates/ui/src/tools/ui/output_row.rs b/crates/ui/src/tools/ui/output_row.rs index abc40712d..149c7a7c7 100644 --- a/crates/ui/src/tools/ui/output_row.rs +++ b/crates/ui/src/tools/ui/output_row.rs @@ -1,4 +1,4 @@ -//! One result of a tool: its name, what it measures, the value itself and its copy button. +//! One result of a tool: its name, the value itself and its copy button. use crate::theme::tokens::{font, gap, radius}; use egui::{CornerRadius, Response, Role, Stroke, Ui, Vec2, WidgetInfo}; @@ -7,7 +7,7 @@ use i18n::Language; use super::CopyValue; use super::result_row::{value_galley, value_label}; use crate::theme::palette; -use crate::widgets::{self, address}; +use crate::widgets::address; /// Held to a height: a long value scrolls in its own block, not the page past the others. const MAX_HEIGHT: f32 = 10.0 * 12.0 * 1.55; @@ -16,78 +16,24 @@ const MAX_HEIGHT: f32 = 10.0 * 12.0 * 1.55; pub struct OutputRow<'a> { name: &'a str, value: &'a str, - copied: Option<&'a str>, - meta: &'a str, - matched: bool, } impl<'a> OutputRow<'a> { pub fn new(name: &'a str, value: &'a str) -> Self { - Self { - name, - value, - copied: None, - meta: "", - matched: false, - } - } - - /// What Copy gives when it is not what is shown: the exact value behind a rounded one. - #[must_use] - pub fn copied(mut self, copied: &'a str) -> Self { - self.copied = Some(copied); - self - } - - /// « 256 bits »: what the value is, beside its name. - #[must_use] - pub fn meta(mut self, meta: &'a str) -> Self { - self.meta = meta; - self - } - - /// Outlined, when this is the one that answers what was asked: a signature it matches. - #[must_use] - pub fn matched(mut self, matched: bool) -> Self { - self.matched = matched; - self + Self { name, value } } pub fn show(self, ui: &mut Ui, language: Language) -> Response { let p = palette(ui.ctx()); - let edge = if self.matched { - p.green.gamma_multiply(0.5) - } else { - p.line_soft - }; - let ink = if self.matched { p.green } else { p.text_0 }; let shown = egui::Frame::new() .fill(p.bg_1) - .stroke(Stroke::new(1.0, edge)) + .stroke(Stroke::new(1.0, p.line_soft)) .corner_radius(CornerRadius::same(radius::CARD)) .inner_margin(gap::margin(gap::BLOCKS, gap::GROUPS)) .show(ui, |ui| { ui.spacing_mut().item_spacing.y = gap::SNUG; ui.set_width(ui.available_width()); - ui.horizontal(|ui| { - super::paragraph(ui, self.name, (font::BODY, 600.0), ink); - if !self.meta.is_empty() { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let family = egui::FontFamily::Monospace; - let meta = widgets::text( - ui, - self.meta, - font::CAPTION, - 400.0, - family, - p.text_2, - ); - let (rect, _) = - ui.allocate_exact_size(meta.size(), egui::Sense::hover()); - ui.painter().galley(rect.min, meta, p.text_2); - }); - } - }); + super::paragraph(ui, self.name, (font::BODY, 600.0), p.text_0); self.line(ui, language); }); let response = shown.response; @@ -98,7 +44,7 @@ impl<'a> OutputRow<'a> { fn line(self, ui: &mut Ui, language: Language) { let width = ui.available_width(); - let copy = CopyValue::new(self.copied.unwrap_or(self.value), self.name, language); + let copy = CopyValue::new(self.value, self.name, language); ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = gap::INSET; let room = width - 96.0; diff --git a/crates/ui/src/tools/ui/reference_table.rs b/crates/ui/src/tools/ui/reference_table.rs index 2b96f9417..a80ee8ff9 100644 --- a/crates/ui/src/tools/ui/reference_table.rs +++ b/crates/ui/src/tools/ui/reference_table.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Response, RichText, Role, Sense, Stroke, - Ui, UiBuilder, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, FontId, Pos2, Rect, Response, RichText, Role, Sense, Stroke, Ui, + UiBuilder, Vec2, WidgetInfo, }; use i18n::{Language, Message, keys}; @@ -38,7 +38,6 @@ pub struct Column { pub struct Cell { pub text: String, pub mono: bool, - pub ink: Option, pub below: Option, /// « Supported », as a mark in the place of the text. pub checked: bool, @@ -54,37 +53,19 @@ pub struct Cell { impl Cell { pub fn text(text: impl Into) -> Self { - Self { - text: text.into(), - ..Self::default() - } + Self { text: text.into(), ..Self::default() } } pub fn mono(text: impl Into) -> Self { - Self { - mono: true, - ..Self::text(text) - } + Self { mono: true, ..Self::text(text) } } pub fn chips(chips: Vec) -> Self { - Self { - chips, - ..Self::default() - } + Self { chips, ..Self::default() } } pub fn checked() -> Self { - Self { - checked: true, - ..Self::default() - } - } - - #[must_use] - pub fn ink(mut self, ink: Color32) -> Self { - self.ink = Some(ink); - self + Self { checked: true, ..Self::default() } } #[must_use] @@ -237,11 +218,7 @@ impl ReferenceTable<'_> { fn cards(&self, ui: &mut Ui, cards: &[(&Group, Vec<&ReferenceRow>)], language: Language) { let width = ui.available_width(); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a few columns" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a few columns")] let across = (((width + CARD_GAP) / (self.card_width + CARD_GAP)).floor() as usize).max(1); #[expect(clippy::cast_precision_loss, reason = "a few columns")] let each = (width - CARD_GAP * (across - 1) as f32) / across as f32; @@ -288,9 +265,7 @@ impl ReferenceTable<'_> { } }); let label = group.label.as_str(); - shown - .response - .widget_info(|| WidgetInfo::labeled(Role::Table, true, label)); + shown.response.widget_info(|| WidgetInfo::labeled(Role::Table, true, label)); address(ui, &shown.response, "reference-group"); } @@ -301,23 +276,18 @@ impl ReferenceTable<'_> { let free = self.columns.iter().filter(|it| it.share.is_none()).count(); #[expect(clippy::cast_precision_loss, reason = "a few columns")] let rest = (1.0 - taken).max(0.0) / free.max(1) as f32; - self.columns - .iter() - .map(|column| column.share.unwrap_or(rest) * room) - .collect() + self.columns.iter().map(|column| column.share.unwrap_or(rest) * room).collect() } fn column_heads(&self, ui: &mut Ui, widths: &[f32]) { let p = palette(ui.ctx()); let total = ui.available_width(); let (rect, _) = ui.allocate_exact_size(Vec2::new(total, 26.0), Sense::hover()); - ui.painter() - .hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.bottom() - 0.5, (1.0, p.line_soft)); let mut left = rect.left(); for (column, width) in self.columns.iter().zip(widths) { let words = column.label.to_uppercase(); - let galley = - widgets::one_line(ui, &words, (font::CAPTION, 600.0), p.text_2, width - 24.0); + let galley = widgets::one_line(ui, &words, (font::CAPTION, 600.0), p.text_2, width - 24.0); let at = Pos2::new(left + 12.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, p.text_2); left += width; @@ -340,8 +310,7 @@ impl ReferenceTable<'_> { address(ui, &response, "reference-row"); let lit = self.lit == Some(row.key.as_str()); if lit { - ui.painter() - .rect_filled(rect, 0.0, p.amber_fill.gamma_multiply(0.12)); + ui.painter().rect_filled(rect, 0.0, p.amber_fill.gamma_multiply(0.12)); let edge = Rect::from_min_size(rect.min, Vec2::new(3.0, rect.height())); ui.painter().rect_filled(edge, 0.0, p.amber_edge); if ui.data_mut(|data| !data.get_temp::(response.id).unwrap_or(false)) { @@ -351,8 +320,7 @@ impl ReferenceTable<'_> { } else if response.hovered() { ui.painter().rect_filled(rect, 0.0, p.bg_2); } - ui.painter() - .hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); let mut left = rect.left(); for (cell, width) in laid.into_iter().zip(widths) { cell.paint(ui, Pos2::new(left + 12.0, rect.top() + 7.0)); @@ -366,24 +334,14 @@ impl ReferenceTable<'_> { let (value, what) = row .copy .as_ref() - .map_or((row.key.as_str(), row.key.as_str()), |(value, what)| { - (value.as_str(), what.as_str()) - }); - CopyValue::new(value, what, language) - .compact() - .show(&mut end); + .map_or((row.key.as_str(), row.key.as_str()), |(value, what)| (value.as_str(), what.as_str())); + CopyValue::new(value, what, language).compact().show(&mut end); } } fn card_head(ui: &mut Ui, group: &Group, count: usize) { let p = palette(ui.ctx()); - let title = widgets::wrapped( - ui, - &group.label, - (font::BODY, 600.0), - p.text_0, - f32::INFINITY, - ); + let title = widgets::wrapped(ui, &group.label, (font::BODY, 600.0), p.text_0, f32::INFINITY); let number = count.to_string(); let family = FontFamily::Proportional; let number = widgets::text(ui, &number, font::BODY, 400.0, family, p.text_2); @@ -412,21 +370,15 @@ fn chip(ui: &Ui, at: Pos2, words: &str, family: FontFamily) -> f32 { let shown = widgets::text(ui, words, font::META, 400.0, family, p.text_1); let size = shown.size() + Vec2::new(CHIP_PADDING, 2.0); let rect = Rect::from_min_size(at, size); - ui.painter() - .rect_filled(rect, CornerRadius::same(radius::TAG), p.bg_3); - ui.painter() - .galley(rect.center() - shown.size() / 2.0, shown, p.text_1); + ui.painter().rect_filled(rect, CornerRadius::same(radius::TAG), p.bg_3); + ui.painter().galley(rect.center() - shown.size() / 2.0, shown, p.text_1); rect.right() } impl LaidCell { fn text_height(&self) -> f32 { let mark = self.check.map_or(0.0, |_| CHECK); - let chips = if self.chips.is_empty() { - 0.0 - } else { - CHIP_HEIGHT - }; + let chips = if self.chips.is_empty() { 0.0 } else { CHIP_HEIGHT }; self.text.size().y.max(mark).max(chips) } @@ -447,12 +399,7 @@ impl LaidCell { let after_text = at.x + self.text.size().x + 8.0; ui.painter().galley(at, self.text, self.ink); if let Some(tag) = &self.tag { - chip( - ui, - Pos2::new(after_text, at.y), - tag, - FontFamily::Proportional, - ); + chip(ui, Pos2::new(after_text, at.y), tag, FontFamily::Proportional); } if let Some(below) = self.below { let top = at + Vec2::new(0.0, height + 2.0); @@ -468,15 +415,9 @@ impl LaidCell { fn laid_cell(ui: &Ui, cell: &Cell, width: f32) -> LaidCell { let p = palette(ui.ctx()); - let ink = cell.hue.map_or(cell.ink.unwrap_or(p.text_0), |hue| hue(p)); - let family = if cell.mono { - FontFamily::Monospace - } else { - FontFamily::Proportional - }; - let text = RichText::new(&cell.text) - .font(FontId::new(font::BODY, family)) - .color(ink); + let ink = cell.hue.map_or(p.text_0, |hue| hue(p)); + let family = if cell.mono { FontFamily::Monospace } else { FontFamily::Proportional }; + let text = RichText::new(&cell.text).font(FontId::new(font::BODY, family)).color(ink); let text = egui::WidgetText::from(text).into_galley( ui, Some(egui::TextWrapMode::Wrap), diff --git a/crates/ui/src/tools/ui/result_row.rs b/crates/ui/src/tools/ui/result_row.rs index 77e327aee..2666153b7 100644 --- a/crates/ui/src/tools/ui/result_row.rs +++ b/crates/ui/src/tools/ui/result_row.rs @@ -5,8 +5,7 @@ use crate::theme::tokens::{font, radius}; use std::sync::Arc; use egui::{ - FontFamily, FontId, Galley, Pos2, Rect, Response, RichText, Role, Sense, Ui, UiBuilder, Vec2, - WidgetInfo, + FontFamily, FontId, Galley, Pos2, Rect, Response, RichText, Role, Sense, Ui, UiBuilder, Vec2, WidgetInfo, }; use i18n::Language; @@ -35,16 +34,7 @@ pub struct ResultRow<'a> { impl<'a> ResultRow<'a> { pub fn new(name: &'a str, value: &'a str) -> Self { - Self { - name, - value, - copied: None, - raw: None, - copyable: true, - meta: "", - matched: false, - tag: None, - } + Self { name, value, copied: None, raw: None, copyable: true, meta: "", matched: false, tag: None } } /// What the icon copies when it is not what is shown: the exact value behind a rounded one. @@ -101,27 +91,15 @@ impl<'a> ResultRow<'a> { let copies = copies_width(ui, given, language); let copy = if self.copyable { copies + 12.0 } else { 0.0 }; let long = self.is_long(); - let name_room = if long { - inner - copy - } else { - (inner * 0.32).max(96.0) - }; + let name_room = if long { inner - copy } else { (inner * 0.32).max(96.0) }; let ink = if self.matched { p.green } else { p.text_0 }; let name = widgets::wrapped(ui, self.name, (font::BODY, 500.0), ink, name_room); let meta = (!self.meta.is_empty()) .then(|| widgets::wrapped(ui, self.meta, (font::META, 400.0), p.text_2, name_room)); let label_height = name.size().y + meta.as_ref().map_or(0.0, |it| it.size().y + 2.0); - let value_room = if long { - inner - } else { - inner - name_room - 12.0 - copy - }; + let value_room = if long { inner } else { inner - name_room - 12.0 - copy }; let galley = value_galley(ui, self.value, value_room); - let value_height = if long { - galley.size().y.min(8.0 * LINE) - } else { - galley.size().y - }; + let value_height = if long { galley.size().y.min(8.0 * LINE) } else { galley.size().y }; let height = if long { 8.0 + label_height.max(28.0) + 6.0 + value_height + 10.0 } else { @@ -131,35 +109,20 @@ impl<'a> ResultRow<'a> { response.widget_info(|| WidgetInfo::labeled(Role::Row, true, self.name)); address(ui, &response, "output-row"); if self.matched { - ui.painter() - .rect_filled(rect, 0.0, p.green.gamma_multiply(0.08)); + ui.painter().rect_filled(rect, 0.0, p.green.gamma_multiply(0.08)); } - ui.painter() - .hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); let left = rect.left() + 16.0; - let head = if long { - rect.top() + 8.0 - } else { - rect.center().y - label_height / 2.0 - }; + let head = if long { rect.top() + 8.0 } else { rect.center().y - label_height / 2.0 }; let name_height = name.size().y; let name_right = left + name.size().x; name.paint(ui, Pos2::new(left, head), ink); if let Some(tag) = self.tag { - let words = widgets::text( - ui, - tag, - font::CAPTION, - 500.0, - FontFamily::Proportional, - p.text_2, - ); + let words = widgets::text(ui, tag, font::CAPTION, 500.0, FontFamily::Proportional, p.text_2); let size = words.size() + Vec2::new(10.0, 2.0); let chip = Rect::from_min_size(Pos2::new(name_right + 8.0, head + 1.0), size); - ui.painter() - .rect_filled(chip, egui::CornerRadius::same(radius::TAG), p.bg_3); - ui.painter() - .galley(chip.center() - words.size() / 2.0, words, p.text_2); + ui.painter().rect_filled(chip, egui::CornerRadius::same(radius::TAG), p.bg_3); + ui.painter().galley(chip.center() - words.size() / 2.0, words, p.text_2); } if let Some(meta) = meta { meta.paint(ui, Pos2::new(left, head + name_height + 2.0), p.text_2); @@ -171,24 +134,15 @@ impl<'a> ResultRow<'a> { ) } else { Rect::from_min_size( - Pos2::new( - left + name_room + 12.0, - rect.center().y - value_height / 2.0, - ), + Pos2::new(left + name_room + 12.0, rect.center().y - value_height / 2.0), Vec2::new(value_room, value_height), ) }; self.value_of(ui, place, galley, long); if self.copyable { - let top = if long { - rect.top() + 8.0 - } else { - rect.center().y - 14.0 - }; - let at = Rect::from_min_size( - Pos2::new(rect.right() - 10.0 - copies, top), - Vec2::new(copies, 28.0), - ); + let top = if long { rect.top() + 8.0 } else { rect.center().y - 14.0 }; + let at = + Rect::from_min_size(Pos2::new(rect.right() - 10.0 - copies, top), Vec2::new(copies, 28.0)); let reading = egui::Layout::left_to_right(egui::Align::Center); let mut end = ui.new_child(UiBuilder::new().max_rect(at).layout(reading)); super::copies(&mut end, given, self.name, language); @@ -231,11 +185,7 @@ pub(super) fn value_label(ui: &mut Ui, galley: Arc) { /// Rows in a card, two abreast once it is wide enough. pub fn result_rows(ui: &mut Ui, rows: &[ResultRow<'_>], language: Language) { let width = ui.available_width(); - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a few rows" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a few rows")] let across = ((width / ROW_MIN).floor() as usize).max(1); #[expect(clippy::cast_precision_loss, reason = "a few rows")] let each = width / across as f32; diff --git a/crates/ui/src/tools/ui/tests.rs b/crates/ui/src/tools/ui/tests.rs index 19c74c8ee..13ce0f4c9 100644 --- a/crates/ui/src/tools/ui/tests.rs +++ b/crates/ui/src/tools/ui/tests.rs @@ -30,9 +30,7 @@ fn values(harness: &Harness<'_>) -> Vec { #[test] fn a_result_row_says_its_name_and_value_and_copies_the_exact_one() { let mut harness = drawn_alone(|ui| { - ResultRow::new("Size", "1.5 GiB") - .copied("1610612736") - .show(ui, Language::En); + ResultRow::new("Size", "1.5 GiB").copied("1610612736").show(ui, Language::En); }); harness.run(); assert_eq!(values(&harness), ["1.5 GiB"]); @@ -40,29 +38,25 @@ fn a_result_row_says_its_name_and_value_and_copies_the_exact_one() { harness.get_by_label("Copy Size").click(); harness.step(); - let copied = harness.output().platform_output.commands.iter().any( - |command| matches!(command, egui::OutputCommand::CopyText(text) if text == "1610612736"), - ); + let copied = harness + .output() + .platform_output + .commands + .iter() + .any(|command| matches!(command, egui::OutputCommand::CopyText(text) if text == "1610612736")); assert!(copied); } #[test] fn a_reading_offers_no_copy_and_an_empty_value_cannot_be_copied() { let mut harness = drawn_alone(|ui| { - ResultRow::new("Reading", "ok") - .reading() - .show(ui, Language::En); + ResultRow::new("Reading", "ok").reading().show(ui, Language::En); CopyValue::new("", "nothing", Language::En).show(ui); }); harness.run(); assert!(harness.query_by_label("Copy Reading").is_none()); - assert!( - harness - .get_by_label("Copy nothing") - .accesskit_node() - .is_disabled() - ); + assert!(harness.get_by_label("Copy nothing").accesskit_node().is_disabled()); } #[test] @@ -79,11 +73,9 @@ fn a_long_value_goes_under_its_name_held_to_a_height() { } #[test] -fn an_output_row_shows_its_value_and_what_it_measures() { +fn an_output_row_shows_its_value_and_copies_it_by_its_name() { let mut harness = drawn_alone(|ui| { - OutputRow::new("SHA-256", "abc") - .meta("256 bits") - .show(ui, Language::En); + OutputRow::new("SHA-256", "abc").show(ui, Language::En); }); harness.run(); @@ -92,46 +84,34 @@ fn an_output_row_shows_its_value_and_what_it_measures() { } fn table_rows() -> Vec { - [ - ("404", "4xx", "Not Found"), - ("500", "5xx", "Internal Server Error"), - ] - .into_iter() - .map(|(key, group, name)| { - ReferenceRow::new(key, group, vec![Cell::mono(key), Cell::text(name)]) - .searched_by([key, name]) - }) - .collect() + [("404", "4xx", "Not Found"), ("500", "5xx", "Internal Server Error")] + .into_iter() + .map(|(key, group, name)| { + ReferenceRow::new(key, group, vec![Cell::mono(key), Cell::text(name)]).searched_by([key, name]) + }) + .collect() } fn table(query: &'static str) -> Harness<'static, String> { let rows = table_rows(); - let groups = ["4xx", "5xx"].map(|id| Group { - id: id.to_owned(), - label: id.to_owned(), - }); - let columns = ["Code", "Name"].map(|label| Column { - label: label.to_owned(), - share: None, - }); - testing::harness() - .with_size(Vec2::new(900.0, 500.0)) - .build_ui_state( - move |ui, query: &mut String| { - let table = ReferenceTable { - rows: &rows, - groups: &groups, - columns: &columns, - caption: "Statuses", - placeholder: "A code", - card_width: 560.0, - lit: None, - matches: None, - }; - table.show(ui, query, Language::En); - }, - query.to_owned(), - ) + let groups = ["4xx", "5xx"].map(|id| Group { id: id.to_owned(), label: id.to_owned() }); + let columns = ["Code", "Name"].map(|label| Column { label: label.to_owned(), share: None }); + testing::harness().with_size(Vec2::new(900.0, 500.0)).build_ui_state( + move |ui, query: &mut String| { + let table = ReferenceTable { + rows: &rows, + groups: &groups, + columns: &columns, + caption: "Statuses", + placeholder: "A code", + card_width: 560.0, + lit: None, + matches: None, + }; + table.show(ui, query, Language::En); + }, + query.to_owned(), + ) } fn row_keys(harness: &Harness<'_, String>) -> Vec { @@ -161,11 +141,7 @@ fn a_search_narrows_the_rows_folding_case_and_says_when_nothing_is_left() { harness.state_mut().push_str("zzz"); harness.run(); assert!(row_keys(&harness).is_empty()); - assert!( - harness - .query_by(|node| node.author_id() == Some("reference-empty")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("reference-empty")).is_some()); } /// A tool that keeps what it is given: the frame's side of the contract. @@ -190,9 +166,7 @@ impl Tool for Echo { title: "Echoed".to_owned(), language: NoteLanguage::Txt, content: self.text.to_uppercase(), - warning: self - .warned - .then_some(i18n::keys::tools::password::SAVE_WARNING), + warning: self.warned.then_some(i18n::keys::tools::password::SAVE_WARNING), }) } @@ -213,19 +187,10 @@ fn echo(text: &str, warned: bool) -> Harness<'static, Bench> { .set_missing_glyph_policy(egui::epaint::text::MissingGlyphPolicy::Tofu); let bench = harness.state_mut(); bench.state.spaces.create_space(&bench.backend, "Travail"); - until(&mut harness, "the space is listed", |harness| { - !harness.state().state.spaces.spaces().is_empty() - }); + until(&mut harness, "the space is listed", |harness| !harness.state().state.spaces.spaces().is_empty()); click(&mut harness, "tools-entry-case"); - let tool = Echo { - text: text.to_owned(), - warned, - }; - harness - .state_mut() - .state - .tools_view - .put("case", Box::new(tool)); + let tool = Echo { text: text.to_owned(), warned }; + harness.state_mut().state.tools_view.put("case", Box::new(tool)); settle(&mut harness); harness } @@ -240,10 +205,8 @@ fn a_note(harness: &mut Harness<'_, Bench>, title: &str, content: &str) { let space = bench.state.spaces.spaces()[0].id.clone(); let mut draft = testing::snippet(space, title.to_owned()); draft.content = content.to_owned(); - engine::db::run_here(bench.backend.engine(), move |engine| { - engine::notes::create_note(engine, draft) - }) - .unwrap(); + engine::db::run_here(bench.backend.engine(), move |engine| engine::notes::create_note(engine, draft)) + .unwrap(); } #[test] @@ -255,18 +218,14 @@ fn a_note_is_imported_whole_into_the_input_it_was_asked_for() { assert_eq!(names(&harness, "note-picker-option"), ["Journal"]); harness .get_by(|node| { - node.author_id() == Some("note-picker-option") - && node.label().as_deref() == Some("Journal") + node.author_id() == Some("note-picker-option") && node.label().as_deref() == Some("Journal") }) .click(); settle(&mut harness); assert!(names(&harness, "note-picker").is_empty()); let input = harness.get_by(|node| node.author_id() == Some("echo-input")); - assert_eq!( - input.accesskit_node().value().as_deref(), - Some("the whole body") - ); + assert_eq!(input.accesskit_node().value().as_deref(), Some("the whole body")); } #[test] @@ -289,10 +248,7 @@ fn enter_takes_the_first_note_found_and_escape_leaves_the_tool_as_it_was() { harness.key_press(Key::Enter); settle(&mut harness); let input = harness.get_by(|node| node.author_id() == Some("echo-input")); - assert_eq!( - input.accesskit_node().value().as_deref(), - Some("the whole body") - ); + assert_eq!(input.accesskit_node().value().as_deref(), Some("the whole body")); } #[test] @@ -334,8 +290,5 @@ fn a_secret_kept_says_so_and_the_button_says_it_goes_all_the_same() { .is_some() ); let submit = harness.get_by(|node| node.author_id() == Some("save-as-note-submit")); - assert_eq!( - submit.accesskit_node().label().as_deref(), - Some("Save anyway") - ); + assert_eq!(submit.accesskit_node().label().as_deref(), Some("Save anyway")); } diff --git a/crates/ui/src/tools/ui/text_table.rs b/crates/ui/src/tools/ui/text_table.rs index 536ca8362..e9bf38fdc 100644 --- a/crates/ui/src/tools/ui/text_table.rs +++ b/crates/ui/src/tools/ui/text_table.rs @@ -88,16 +88,13 @@ fn row( towards(egui::Color32::TRANSPARENT, p.bg_2, hovered(ui, &response)) }; ui.painter().rect_filled(rect, 0.0, fill); - ui.painter() - .hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top() + 0.5, (1.0, p.line_soft)); let mut left = rect.left() + 12.0; for (column, cell) in columns.iter().zip(cells) { let family = FontFamily::Monospace; let galley = widgets::text(ui, cell, font::LABEL, 400.0, family, p.text_0); let at = Pos2::new(left, rect.center().y - galley.size().y / 2.0); - ui.painter() - .with_clip_rect(rect) - .galley(at, galley, p.text_0); + ui.painter().with_clip_rect(rect).galley(at, galley, p.text_0); left += width * column.share; } response diff --git a/crates/ui/src/widgets/badge.rs b/crates/ui/src/widgets/badge.rs index c978a89a8..f60a27292 100644 --- a/crates/ui/src/widgets/badge.rs +++ b/crates/ui/src/widgets/badge.rs @@ -3,8 +3,7 @@ use crate::theme::tokens::{font, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, - WidgetInfo, + Color32, CornerRadius, FontFamily, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, }; use engine::notes::priority::Priority; @@ -21,12 +20,7 @@ pub struct Chip<'a> { impl<'a> Chip<'a> { pub fn new(label: &'a str, author_id: &'a str, selected: bool) -> Self { - Self { - label, - author_id, - selected, - widest: f32::INFINITY, - } + Self { label, author_id, selected, widest: f32::INFINITY } } /// No wider than this: its label is cut, said whole on hover. @@ -45,14 +39,7 @@ impl<'a> Chip<'a> { pub fn show(self, ui: &mut Ui) -> Response { let p = palette(ui.ctx()); - let probe = text( - ui, - self.label, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let probe = text(ui, self.label, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); let corner = CornerRadius::same(u8::MAX); let (label, selected) = (self.label, self.selected); let width = (probe.size().x + 20.0).min(self.widest); @@ -64,17 +51,9 @@ impl<'a> Chip<'a> { || WidgetInfo::selected(Role::CheckBox, true, selected, label), corner, ); - let lit = if self.selected { - 1.0 - } else { - hovered(ui, &response) - }; + let lit = if self.selected { 1.0 } else { hovered(ui, &response) }; let edge = towards(p.line_soft, p.amber_dim, lit); - let ink = if self.selected { - p.amber_text - } else { - p.text_1 - }; + let ink = if self.selected { p.amber_text } else { p.text_1 }; ui.painter().rect( response.rect, corner, @@ -115,17 +94,11 @@ pub fn hue_badge(ui: &mut Ui, label: &str, hue: Color32) -> Response { let p = palette(ui.ctx()); let words = label.to_uppercase(); let galley = text(ui, &words, font::BADGE, 700.0, FontFamily::Monospace, hue); - let (rect, response) = - ui.allocate_exact_size(galley.size() + Vec2::new(12.0, 4.0), Sense::hover()); + let (rect, response) = ui.allocate_exact_size(galley.size() + Vec2::new(12.0, 4.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, label)); let corner = CornerRadius::same(radius::TAG); - ui.painter().rect( - rect, - corner, - p.bg_3, - Stroke::new(1.0, hue.gamma_multiply(0.4)), - StrokeKind::Inside, - ); + ui.painter() + .rect(rect, corner, p.bg_3, Stroke::new(1.0, hue.gamma_multiply(0.4)), StrokeKind::Inside); let at = egui::pos2(rect.left() + 6.0, rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, hue); response @@ -137,16 +110,8 @@ pub struct Kbd<'a>(pub &'a str); impl Kbd<'_> { pub fn show(self, ui: &mut Ui) -> Response { let p = palette(ui.ctx()); - let galley = text( - ui, - self.0, - font::CAPTION, - 400.0, - FontFamily::Monospace, - p.text_1, - ); - let (rect, response) = - ui.allocate_exact_size(galley.size() + Vec2::new(12.0, 2.0), Sense::hover()); + let galley = text(ui, self.0, font::CAPTION, 400.0, FontFamily::Monospace, p.text_1); + let (rect, response) = ui.allocate_exact_size(galley.size() + Vec2::new(12.0, 2.0), Sense::hover()); response.widget_info(|| WidgetInfo::labeled(Role::Label, true, self.0)); ui.painter().rect( rect, @@ -155,8 +120,7 @@ impl Kbd<'_> { Stroke::new(1.0, p.line), StrokeKind::Inside, ); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, p.text_1); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text_1); response } } diff --git a/crates/ui/src/widgets/button.rs b/crates/ui/src/widgets/button.rs index 4b38c4cea..cbafc8db3 100644 --- a/crates/ui/src/widgets/button.rs +++ b/crates/ui/src/widgets/button.rs @@ -4,8 +4,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, - Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, Pos2, Rect, Response, Role, Sense, Stroke, StrokeKind, Ui, Vec2, + WidgetInfo, }; use super::{dimmed, hovered, interact, text, towards}; @@ -110,9 +110,8 @@ impl<'a> Button<'a> { pub fn tall_width(ui: &Ui, label: &str, keys: Option<&str>) -> f32 { let family = FontFamily::Proportional; let probe = text(ui, label, TALL_SIZE, TALL_WEIGHT, family, Color32::WHITE); - let keys = keys.map_or(0.0, |keys| { - KEYS_GAP + super::arrowed(ui, None, keys, font::CAPTION, Color32::WHITE) - }); + let keys = + keys.map_or(0.0, |keys| KEYS_GAP + super::arrowed(ui, None, keys, font::CAPTION, Color32::WHITE)); probe.size().x + keys + 2.0 * TALL_PADDING } @@ -149,34 +148,18 @@ impl<'a> Button<'a> { /// What a button of the default size with `label` takes in a row. pub fn width(ui: &Ui, label: &str) -> f32 { - let probe = text( - ui, - label, - font::LABEL, - 400.0, - FontFamily::Proportional, - Color32::WHITE, - ); + let probe = text(ui, label, font::LABEL, 400.0, FontFamily::Proportional, Color32::WHITE); (probe.size().x + 24.0).max(super::MIN_TARGET) } pub fn show(self, ui: &mut Ui) -> Response { let (size, weight, padding, corner) = match (self.size, self.kind) { - (Size::Tall | Size::TallIcon, _) => { - (TALL_SIZE, TALL_WEIGHT, Vec2::new(TALL_PADDING, 0.0), 8) - } + (Size::Tall | Size::TallIcon, _) => (TALL_SIZE, TALL_WEIGHT, Vec2::new(TALL_PADDING, 0.0), 8), (Size::Large, _) => (14.0, 600.0, Vec2::splat(10.0), 8), (Size::Regular, Kind::Quiet) => (12.0, 400.0, Vec2::new(6.0, 0.0), 6), (Size::Regular, _) => (12.0, 400.0, Vec2::new(12.0, 6.0), 6), }; - let probe = text( - ui, - self.label, - size, - weight, - FontFamily::Proportional, - Color32::WHITE, - ); + let probe = text(ui, self.label, size, weight, FontFamily::Proportional, Color32::WHITE); let icon_room = if self.icon.is_some() { 16.0 + 6.0 } else { 0.0 }; let cap_room = if self.capped { 12.0 } else { 0.0 }; let keys_room = self.keys.map_or(0.0, |keys| { @@ -189,11 +172,7 @@ impl<'a> Button<'a> { Size::TallIcon => wanted = Vec2::splat(TALL_HEIGHT), Size::Regular => {} } - let sense = if self.enabled { - Sense::click() - } else { - Sense::hover() - }; + let sense = if self.enabled { Sense::click() } else { Sense::hover() }; let corner = CornerRadius::same(corner); let (label, enabled) = (self.label, self.enabled); let response = interact( @@ -204,21 +183,11 @@ impl<'a> Button<'a> { || WidgetInfo::labeled(Role::Button, enabled, label), corner, ); - let hover = if self.enabled { - hovered(ui, &response) - } else { - 0.0 - }; + let hover = if self.enabled { hovered(ui, &response) } else { 0.0 }; let (fill, edge, ink) = self.colours(ui, hover); let rect = response.rect; let painter = ui.painter(); - painter.rect( - rect, - corner, - fill, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); + painter.rect(rect, corner, fill, Stroke::new(1.0, edge), StrokeKind::Inside); if let (Size::TallIcon, Some(icon)) = (self.size, self.icon) { let place = Rect::from_center_size(rect.center(), Vec2::splat(16.0)); icons::paint(ui, place, icon, ink); @@ -228,17 +197,12 @@ impl<'a> Button<'a> { let width = galley.size().x + icon_room + keys_room; let mut left = rect.center().x - width / 2.0; if let Some(icon) = self.icon { - let place = - Rect::from_center_size(Pos2::new(left + 8.0, rect.center().y), Vec2::splat(16.0)); + let place = Rect::from_center_size(Pos2::new(left + 8.0, rect.center().y), Vec2::splat(16.0)); icons::paint(ui, place, icon, ink); left += icon_room; } let after = left + galley.size().x + KEYS_GAP; - painter.galley( - Pos2::new(left, rect.center().y - galley.size().y / 2.0), - galley, - ink, - ); + painter.galley(Pos2::new(left, rect.center().y - galley.size().y / 2.0), galley, ink); if let Some(keys) = self.keys { let at = Pos2::new(after + cap_room / 2.0, rect.center().y); if self.capped { @@ -265,40 +229,22 @@ impl<'a> Button<'a> { fn colours(&self, ui: &Ui, hover: f32) -> (Color32, Color32, Color32) { let p = palette(ui.ctx()); let (fill, edge, ink) = match self.kind { - Kind::Outline if self.armed => { - (p.amber_fill.gamma_multiply(0.1), p.amber_dim, p.amber_text) + Kind::Outline if self.armed => (p.amber_fill.gamma_multiply(0.1), p.amber_dim, p.amber_text), + Kind::Outline => { + (p.bg_2, towards(p.line_soft, p.amber_dim, hover), towards(p.text_1, p.amber_text, hover)) } - Kind::Outline => ( - p.bg_2, - towards(p.line_soft, p.amber_dim, hover), - towards(p.text_1, p.amber_text, hover), - ), Kind::Filled => (p.amber_fill, p.amber_edge, p.amber_ink), - Kind::Accent => ( - p.amber_fill.gamma_multiply(0.08), - towards(p.amber_dim, p.amber_edge, hover), - p.amber_text, - ), + Kind::Accent => { + (p.amber_fill.gamma_multiply(0.08), towards(p.amber_dim, p.amber_edge, hover), p.amber_text) + } Kind::Quiet if self.armed => (p.bg_3, Color32::TRANSPARENT, p.amber_text), - Kind::Quiet => ( - Color32::TRANSPARENT, - Color32::TRANSPARENT, - towards(p.text_2, p.text_1, hover), - ), + Kind::Quiet => (Color32::TRANSPARENT, Color32::TRANSPARENT, towards(p.text_2, p.text_1, hover)), Kind::Destructive => { let lit = if self.armed { 1.0 } else { hover }; - ( - towards(p.bg_2, p.bg_3, lit), - towards(p.red.gamma_multiply(0.3), p.red, lit), - p.red, - ) + (towards(p.bg_2, p.bg_3, lit), towards(p.red.gamma_multiply(0.3), p.red, lit), p.red) } }; - ( - dimmed(fill, self.enabled), - dimmed(edge, self.enabled), - dimmed(ink, self.enabled), - ) + (dimmed(fill, self.enabled), dimmed(edge, self.enabled), dimmed(ink, self.enabled)) } } @@ -313,13 +259,7 @@ pub struct IconButton<'a> { impl<'a> IconButton<'a> { pub fn new(icon: Icon, label: &'a str, author_id: &'a str) -> Self { - Self { - icon, - label, - author_id, - pressed: false, - keys: None, - } + Self { icon, label, author_id, pressed: false, keys: None } } /// The keys that do the same, said after its name in the tooltip. @@ -348,17 +288,9 @@ impl<'a> IconButton<'a> { ); let p = palette(ui.ctx()); let hover = hovered(ui, &response); - let ink = if self.pressed { - p.amber_text - } else { - towards(p.text_2, p.text_0, hover) - }; + let ink = if self.pressed { p.amber_text } else { towards(p.text_2, p.text_0, hover) }; if self.pressed || hover > 0.0 { - let fill = if self.pressed { - p.bg_3 - } else { - p.bg_3.gamma_multiply(hover) - }; + let fill = if self.pressed { p.bg_3 } else { p.bg_3.gamma_multiply(hover) }; ui.painter().rect_filled(response.rect, corner, fill); } let glyph = Rect::from_center_size(response.rect.center(), Vec2::splat(16.0)); @@ -387,13 +319,7 @@ pub struct SquareButton<'a> { impl<'a> SquareButton<'a> { pub fn new(icon: Icon, label: &'a str, author_id: &'a str) -> Self { - Self { - icon, - label, - author_id, - open: false, - keys: None, - } + Self { icon, label, author_id, open: false, keys: None } } /// The keys that do the same, said after its name in the tooltip. diff --git a/crates/ui/src/widgets/date.rs b/crates/ui/src/widgets/date.rs index e3b08be71..0aa70a375 100644 --- a/crates/ui/src/widgets/date.rs +++ b/crates/ui/src/widgets/date.rs @@ -5,8 +5,8 @@ use crate::theme::tokens::{font, gap, radius}; use chrono::{Datelike, Days, Months, NaiveDate}; use egui::{ - Color32, CornerRadius, FontFamily, Key, Modifiers, Popup, PopupCloseBehavior, Response, Role, - Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, Key, Modifiers, Popup, PopupCloseBehavior, Response, Role, Sense, + Stroke, StrokeKind, Ui, Vec2, WidgetInfo, }; use i18n::{Language, keys}; @@ -31,19 +31,8 @@ pub struct DateField<'a> { } impl<'a> DateField<'a> { - pub fn new( - value: Option, - today: NaiveDate, - name: &'a str, - author_id: &'a str, - ) -> Self { - Self { - value, - today, - name, - author_id, - language: Language::En, - } + pub fn new(value: Option, today: NaiveDate, name: &'a str, author_id: &'a str) -> Self { + Self { value, today, name, author_id, language: Language::En } } #[must_use] @@ -58,11 +47,7 @@ impl<'a> DateField<'a> { || i18n::translate(self.language, keys::editor::date::EMPTY, &[]), |day| i18n::format::date_numeric(day, self.language), ); - let ink = if self.value.is_some() { - p.text_1 - } else { - p.text_2 - }; + let ink = if self.value.is_some() { p.text_1 } else { p.text_2 }; let probe = text(ui, &shown, font::CONTROL, 400.0, FontFamily::Monospace, ink); let corner = CornerRadius::same(radius::CONTROL); let name = self.name; @@ -80,17 +65,9 @@ impl<'a> DateField<'a> { corner, ); let edge = towards(p.line, p.amber_dim, hovered(ui, &response)); - ui.painter().rect( - response.rect, - corner, - p.bg_1, - Stroke::new(1.0, edge), - StrokeKind::Inside, - ); - let at = egui::pos2( - response.rect.left() + 8.0, - response.rect.center().y - probe.size().y / 2.0, - ); + ui.painter() + .rect(response.rect, corner, p.bg_1, Stroke::new(1.0, edge), StrokeKind::Inside); + let at = egui::pos2(response.rect.left() + 8.0, response.rect.center().y - probe.size().y / 2.0); ui.painter().galley(at, probe, ink); let glyph = egui::Rect::from_center_size( egui::pos2(response.rect.right() - 13.0, response.rect.center().y), @@ -98,12 +75,7 @@ impl<'a> DateField<'a> { ); icons::paint(ui, glyph, Icon::Calendar, p.text_2); if open { - let arrows = egui::EventFilter { - horizontal_arrows: true, - vertical_arrows: true, - ..Default::default() - }; - ui.memory_mut(|memory| memory.set_focus_lock_filter(response.id, arrows)); + super::keep_arrows(ui, &response); } if takes_delete(ui, &response) { return Some(Picked::Cleared); @@ -140,12 +112,7 @@ struct Keys { fn take_keys(ui: &Ui) -> Keys { ui.input_mut(|input| { - let moves = [ - (Key::ArrowLeft, -1), - (Key::ArrowRight, 1), - (Key::ArrowUp, -7), - (Key::ArrowDown, 7), - ]; + let moves = [(Key::ArrowLeft, -1), (Key::ArrowRight, 1), (Key::ArrowUp, -7), (Key::ArrowDown, 7)]; let mut keys = Keys::default(); for (key, by) in moves { while input.consume_key(Modifiers::NONE, key) { @@ -167,12 +134,7 @@ fn takes_delete(ui: &Ui, response: &Response) -> bool { } /// The month around `cursor`, from Monday; the day the arrows moved to, and the one picked. -fn month( - ui: &mut Ui, - cursor: NaiveDate, - field: &DateField<'_>, - keys: Keys, -) -> (NaiveDate, Option) { +fn month(ui: &mut Ui, cursor: NaiveDate, field: &DateField<'_>, keys: Keys) -> (NaiveDate, Option) { let p = palette(ui.ctx()); let language = field.language; let tr = |key| i18n::translate(language, key, &[]); @@ -195,56 +157,35 @@ fn month( ("year", cursor.year().to_string().into()), ], ); - let galley = text( - ui, - &title, - font::BODY, - 600.0, - FontFamily::Proportional, - p.text_0, - ); + let galley = text(ui, &title, font::BODY, 600.0, FontFamily::Proportional, p.text_0); let (rect, _) = ui.allocate_exact_size(Vec2::new(150.0, 24.0), Sense::hover()); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, p.text_0); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text_0); let next = tr(keys::editor::date::NEXT); - if super::IconButton::new(Icon::ArrowRight, &next, "date-next") - .show(ui) - .clicked() - { + if super::IconButton::new(Icon::ArrowRight, &next, "date-next").show(ui).clicked() { cursor = cursor + Months::new(1); } }); let first = cursor.with_day(1).unwrap_or(cursor); let lead = u64::from(first.weekday().num_days_from_monday()); let start = first - Days::new(lead); - egui::Grid::new("date-grid") - .spacing(Vec2::splat(2.0)) - .show(ui, |ui| { - for weekday in 1..=7 { - let initial = weekday_initial(weekday, language); - let galley = text( - ui, - &initial, - font::CAPTION, - 500.0, - FontFamily::Proportional, - p.text_2, - ); - let (rect, _) = ui.allocate_exact_size(Vec2::splat(28.0), Sense::hover()); - ui.painter() - .galley(rect.center() - galley.size() / 2.0, galley, p.text_2); - } - ui.end_row(); - for week in 0..6 { - for weekday in 0..7 { - let day = start + Days::new(week * 7 + weekday); - if day_cell(ui, day, cursor, field).clicked() { - picked = Some(Picked::Day(day)); - } + egui::Grid::new("date-grid").spacing(Vec2::splat(2.0)).show(ui, |ui| { + for weekday in 1..=7 { + let initial = weekday_initial(weekday, language); + let galley = text(ui, &initial, font::CAPTION, 500.0, FontFamily::Proportional, p.text_2); + let (rect, _) = ui.allocate_exact_size(Vec2::splat(28.0), Sense::hover()); + ui.painter().galley(rect.center() - galley.size() / 2.0, galley, p.text_2); + } + ui.end_row(); + for week in 0..6 { + for weekday in 0..7 { + let day = start + Days::new(week * 7 + weekday); + if day_cell(ui, day, cursor, field).clicked() { + picked = Some(Picked::Day(day)); } - ui.end_row(); } - }); + ui.end_row(); + } + }); let clear = tr(keys::editor::date::CLEAR); if super::Button::new(&clear, "date-clear").show(ui).clicked() { picked = Some(Picked::Cleared); @@ -275,12 +216,8 @@ fn day_cell(ui: &mut Ui, day: NaiveDate, cursor: NaiveDate, field: &DateField<'_ }; ui.painter().rect_filled(response.rect, corner, fill); if day == field.today { - ui.painter().rect_stroke( - response.rect, - corner, - Stroke::new(1.0, p.amber_dim), - StrokeKind::Inside, - ); + ui.painter() + .rect_stroke(response.rect, corner, Stroke::new(1.0, p.amber_dim), StrokeKind::Inside); } let ink = if selected { p.amber_text @@ -289,19 +226,9 @@ fn day_cell(ui: &mut Ui, day: NaiveDate, cursor: NaiveDate, field: &DateField<'_ } else { p.text_1 }; - let galley = text( - ui, - &day.day().to_string(), - font::CONTROL, - 400.0, - FontFamily::Proportional, - ink, - ); - ui.painter().galley( - response.rect.center() - galley.size() / 2.0, - galley, - Color32::TRANSPARENT, - ); + let galley = text(ui, &day.day().to_string(), font::CONTROL, 400.0, FontFamily::Proportional, ink); + ui.painter() + .galley(response.rect.center() - galley.size() / 2.0, galley, Color32::TRANSPARENT); response } @@ -344,13 +271,157 @@ mod tests { #[test] fn the_arrows_move_by_a_day_and_by_a_week() { let day = NaiveDate::from_ymd_opt(2026, 3, 1).unwrap(); - assert_eq!( - shifted(day, -1), - NaiveDate::from_ymd_opt(2026, 2, 28).unwrap() + assert_eq!(shifted(day, -1), NaiveDate::from_ymd_opt(2026, 2, 28).unwrap()); + assert_eq!(shifted(day, 7), NaiveDate::from_ymd_opt(2026, 3, 8).unwrap()); + } + + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + struct Screen { + value: Option, + picked: Option, + } + + fn day(month: u32, day: u32) -> NaiveDate { + NaiveDate::from_ymd_opt(2026, month, day).unwrap() + } + + fn field(value: Option) -> Harness<'static, Screen> { + let screen = Screen { value, picked: None }; + let mut harness = crate::testing::harness().with_size(egui::vec2(700.0, 600.0)).build_ui_state( + |ui, screen: &mut Screen| { + let field = DateField::new(screen.value, day(3, 10), "Échéance", "date"); + if let Some(picked) = field.show(ui) { + screen.picked = Some(picked); + } + }, + screen, ); - assert_eq!( - shifted(day, 7), - NaiveDate::from_ymd_opt(2026, 3, 8).unwrap() + harness.run(); + harness + } + + fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness.get_by(|node| node.author_id() == Some(author_id)).click(); + harness.run(); + harness.run(); + } + + fn press(harness: &mut Harness<'_, Screen>, key: Key) { + harness.key_press(key); + harness.run(); + } + + fn opened(value: Option) -> Harness<'static, Screen> { + let mut harness = field(value); + click(&mut harness, "date"); + harness + } + + fn days(harness: &Harness<'_, Screen>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("date-day")) + .map(|node| node.accesskit_node().label().unwrap_or_default()) + .collect() + } + + #[test] + fn it_shows_its_day_or_that_there_is_none() { + assert!( + crate::testing::painted(&field(Some(day(3, 4)))).contains(&"2026-03-04".to_owned()) + || crate::testing::painted(&field(Some(day(3, 4)))) + .iter() + .any(|words| words.contains("2026")) ); + assert!(!crate::testing::painted(&field(None)).iter().any(|words| words.contains("2026"))); + } + + /// Six weeks from Monday, the days around the month drawn too. + #[test] + fn a_month_is_six_weeks_from_the_monday_that_holds_its_first() { + let harness = opened(Some(day(3, 4))); + let days = days(&harness); + + assert_eq!(days.len(), 42); + assert!(days[0].contains("23") && days[0].contains("February"), "{}", days[0]); + } + + #[test] + fn it_opens_on_its_day_or_on_today() { + for (value, start) in [(Some(day(7, 14)), day(7, 14)), (None, day(3, 10))] { + let mut harness = opened(value); + press(&mut harness, Key::Enter); + assert_eq!(harness.state().picked, Some(Picked::Day(start))); + } + } + + #[test] + fn the_arrows_move_the_day_enter_takes() { + for (keys, taken) in [ + (vec![Key::ArrowRight], day(3, 11)), + (vec![Key::ArrowLeft, Key::ArrowLeft], day(3, 8)), + (vec![Key::ArrowDown, Key::ArrowDown], day(3, 24)), + (vec![Key::ArrowUp, Key::ArrowUp], day(2, 24)), + ] { + let mut harness = opened(None); + for key in &keys { + press(&mut harness, *key); + } + press(&mut harness, Key::Enter); + assert_eq!(harness.state().picked, Some(Picked::Day(taken)), "{keys:?}"); + } + } + + #[test] + fn a_day_clicked_is_taken_and_closes_the_month() { + let mut harness = opened(Some(day(3, 4))); + let wanted = days(&harness)[10].clone(); + harness + .get_by(|node| { + node.author_id() == Some("date-day") && node.label().as_deref() == Some(wanted.as_str()) + }) + .click(); + harness.run(); + harness.run(); + + assert_eq!(harness.state().picked, Some(Picked::Day(day(3, 5)))); + assert!(days(&harness).is_empty()); + } + + #[test] + fn the_months_before_and_after_are_one_click_away() { + for (button, taken) in [("date-previous", day(2, 28)), ("date-next", day(4, 30))] { + let mut harness = opened(Some(day(3, 31))); + click(&mut harness, button); + press(&mut harness, Key::Enter); + let picked = harness.state().picked; + assert_eq!(picked, Some(Picked::Day(taken)), "{button}"); + } + } + + #[test] + fn the_day_is_taken_off_by_its_button_and_by_either_key() { + let mut harness = opened(Some(day(3, 4))); + click(&mut harness, "date-clear"); + assert_eq!(harness.state().picked, Some(Picked::Cleared)); + + for key in [Key::Delete, Key::Backspace] { + let mut harness = field(Some(day(3, 4))); + harness.get_by(|node| node.author_id() == Some("date")).focus(); + harness.run(); + press(&mut harness, key); + assert_eq!(harness.state().picked, Some(Picked::Cleared), "{key:?}"); + } + } + + #[test] + fn escape_closes_the_month_and_takes_nothing() { + let mut harness = opened(Some(day(3, 4))); + press(&mut harness, Key::ArrowRight); + press(&mut harness, Key::Escape); + + assert!(days(&harness).is_empty()); + assert_eq!(harness.state().picked, None); } } diff --git a/crates/ui/src/widgets/dialog.rs b/crates/ui/src/widgets/dialog.rs index 86c836308..c5b5546e0 100644 --- a/crates/ui/src/widgets/dialog.rs +++ b/crates/ui/src/widgets/dialog.rs @@ -10,8 +10,6 @@ use crate::theme::{palette, spacing}; /// The rungs, lowest first. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Layer { - Editor, - Titlebar, App, Settings, Update, @@ -87,11 +85,6 @@ impl DialogStack { pub fn top(&self) -> Option { self.open.last().map(|opened| opened.id) } - - /// The open ones, lowest first: the order to draw them in. - pub fn in_order(&self) -> impl Iterator + '_ { - self.open.iter().map(|opened| opened.id) - } } /// What a modal drew, and whether it asks to close: Escape, a click outside, or its cross. @@ -128,23 +121,12 @@ pub(crate) fn cross(ui: &mut egui::Ui, (label, author_id): Cross<'_>, margin: f3 } pub(crate) fn shown(response: ModalResponse<(R, bool)>) -> Shown { - let ModalResponse { - response, - backdrop_response, - inner: (inner, crossed), - is_top_modal, - any_popup_open, - } = response; + let ModalResponse { response, backdrop_response, inner: (inner, crossed), is_top_modal, any_popup_open } = + response; Shown { inner, crossed, - modal: ModalResponse { - response, - backdrop_response, - inner: (), - is_top_modal, - any_popup_open, - }, + modal: ModalResponse { response, backdrop_response, inner: (), is_top_modal, any_popup_open }, } } @@ -216,11 +198,7 @@ pub fn framed_dialog( /// A Notes panel's modal (a folder's name, a snippet's fields, the tags, the trash): the /// dialog's frame, padded evenly, over the dimmed backdrop. Its keys and its closing stay the /// caller's. -pub fn modal_panel( - ctx: &Context, - id: Id, - content: impl FnOnce(&mut egui::Ui) -> R, -) -> ModalResponse { +pub fn modal_panel(ctx: &Context, id: Id, content: impl FnOnce(&mut egui::Ui) -> R) -> ModalResponse { let p = palette(ctx); #[expect(clippy::cast_possible_truncation, reason = "a few points")] let padding = spacing(ctx).canvas.round() as i8; @@ -239,14 +217,7 @@ pub fn modal_panel( /// A dialog's title: its words at the title's size, read as its heading, found by `author_id`. pub fn dialog_title(ui: &mut egui::Ui, words: &str, author_id: &str) -> egui::Response { let ink = palette(ui.ctx()).text_0; - let galley = super::text( - ui, - words, - font::TITLE, - 600.0, - egui::FontFamily::Proportional, - ink, - ); + let galley = super::text(ui, words, font::TITLE, 600.0, egui::FontFamily::Proportional, ink); let (rect, heading) = ui.allocate_exact_size(galley.size(), egui::Sense::hover()); ui.painter().galley(rect.min, galley, ink); heading.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Heading, true, words)); @@ -276,7 +247,7 @@ mod tests { assert_eq!(stack.top(), Some(passphrase)); stack.close(&ctx, passphrase); assert_eq!(stack.top(), Some(settings)); - assert_eq!(stack.in_order().collect::>(), [settings]); + assert_eq!(stack.top(), Some(settings)); } #[derive(Default)] @@ -286,44 +257,39 @@ mod tests { } fn screen() -> egui_kittest::Harness<'static, Screen> { - crate::testing::harness() - .with_size(egui::vec2(800.0, 600.0)) - .build_ui_state( - |ui, screen: &mut Screen| { - screen.stack.begin_frame(ui.ctx()); - let opener = Button::new("Préférences", "open-settings").show(ui); - if opener.clicked() { - screen - .stack - .open(Layer::Settings, Id::unique("settings"), Some(opener.id)); - } - if Button::new("Dessous", "under").show(ui).clicked() { - screen.under_clicked = true; - } - dialog( - ui.ctx(), - &screen.stack, - (Id::unique("settings"), ("Fermer", "settings-cross")), - 480.0, - |ui| { - Button::new("Un", "first").show(ui); - Button::new("Deux", "second").show(ui); - }, - ); - let close = [Binding { - key: Key::Escape, - modifiers: Modifiers::NONE, - read: Read::Character, - while_typing: true, - action: crate::action::Action::Global(crate::action::GlobalAction::Quit), - }]; - if screen.stack.top().is_some() && keys::dispatch(ui.ctx(), &[&close]).is_some() - { - screen.stack.close(ui.ctx(), Id::unique("settings")); - } - }, - Screen::default(), - ) + crate::testing::harness().with_size(egui::vec2(800.0, 600.0)).build_ui_state( + |ui, screen: &mut Screen| { + screen.stack.begin_frame(ui.ctx()); + let opener = Button::new("Préférences", "open-settings").show(ui); + if opener.clicked() { + screen.stack.open(Layer::Settings, Id::unique("settings"), Some(opener.id)); + } + if Button::new("Dessous", "under").show(ui).clicked() { + screen.under_clicked = true; + } + dialog( + ui.ctx(), + &screen.stack, + (Id::unique("settings"), ("Fermer", "settings-cross")), + 480.0, + |ui| { + Button::new("Un", "first").show(ui); + Button::new("Deux", "second").show(ui); + }, + ); + let close = [Binding { + key: Key::Escape, + modifiers: Modifiers::NONE, + read: Read::Character, + while_typing: true, + action: crate::action::Action::Global(crate::action::GlobalAction::Quit), + }]; + if screen.stack.top().is_some() && keys::dispatch(ui.ctx(), &[&close]).is_some() { + screen.stack.close(ui.ctx(), Id::unique("settings")); + } + }, + Screen::default(), + ) } fn focused(harness: &egui_kittest::Harness<'_, Screen>) -> Option { @@ -336,23 +302,16 @@ mod tests { fn a_modal_keeps_tab_inside_blocks_what_is_under_and_gives_the_focus_back() { let mut harness = screen(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("open-settings")) - .click(); + harness.get_by(|node| node.author_id() == Some("open-settings")).click(); harness.run(); for _ in 0..4 { harness.key_press(Key::Tab); harness.run(); let now = focused(&harness); - assert!( - matches!(now.as_deref(), Some("first" | "second" | "settings-cross")), - "{now:?}" - ); + assert!(matches!(now.as_deref(), Some("first" | "second" | "settings-cross")), "{now:?}"); } - harness - .get_by(|node| node.author_id() == Some("under")) - .click(); + harness.get_by(|node| node.author_id() == Some("under")).click(); harness.run(); assert!(!harness.state().under_clicked); diff --git a/crates/ui/src/widgets/editor/bubbles.rs b/crates/ui/src/widgets/editor/bubbles.rs index 0d75c9313..82b40f922 100644 --- a/crates/ui/src/widgets/editor/bubbles.rs +++ b/crates/ui/src/widgets/editor/bubbles.rs @@ -68,8 +68,7 @@ pub(crate) fn keys(ui: &Ui, editor: &mut Editor, completion: &Completion<'_>) -> ( input.consume_key(Modifiers::NONE, Key::ArrowUp), input.consume_key(Modifiers::NONE, Key::ArrowDown), - input.consume_key(Modifiers::NONE, Key::Tab) - || input.consume_key(Modifiers::NONE, Key::Enter), + input.consume_key(Modifiers::NONE, Key::Tab) || input.consume_key(Modifiers::NONE, Key::Enter), input.consume_key(Modifiers::NONE, Key::Escape), ) }); @@ -90,10 +89,7 @@ pub(crate) fn keys(ui: &Ui, editor: &mut Editor, completion: &Completion<'_>) -> /// The word at the caret replaced by entry `at`. fn accept_entry(editor: &mut Editor, completion: &Completion<'_>, at: usize) -> usize { let head = editor.buffer.selection().head; - editor.buffer.select(Selection { - anchor: completion.from, - head, - }); + editor.buffer.select(Selection { anchor: completion.from, head }); let edited = editor.buffer.insert(&completion.items[at]); editor.choosing = Choosing::default(); edited.first_line @@ -153,8 +149,7 @@ pub(crate) fn list( /// An entry: amber while it is the one Enter takes. fn option(ui: &mut Ui, item: &str, selected: bool) -> Response { - let entry = - crate::widgets::menu_entry(ui, item, "editor-completion-option", false, selected, false); + let entry = crate::widgets::menu_entry(ui, item, "editor-completion-option", false, selected, false); entry.widget_info(|| WidgetInfo::selected(Role::ListBoxOption, true, selected, item)); entry } diff --git a/crates/ui/src/widgets/editor/bubbles/tests.rs b/crates/ui/src/widgets/editor/bubbles/tests.rs index e3646bbc4..d7c067574 100644 --- a/crates/ui/src/widgets/editor/bubbles/tests.rs +++ b/crates/ui/src/widgets/editor/bubbles/tests.rs @@ -10,43 +10,34 @@ const WORDS: [&str; 3] = ["somme", "sommet", "moyenne"]; /// The editor, completing from `WORDS` from three characters, and saying the length of the /// word under the pointer. fn screen(text: &str) -> Harness<'static, Editor> { - crate::testing::harness() - .with_size(egui::vec2(600.0, 300.0)) - .build_ui_state( - |ui, editor: &mut Editor| { - let (from, word) = editor.word_at_caret(); - let items: Vec = if word.chars().count() >= 3 { - WORDS - .iter() - .filter(|candidate| candidate.starts_with(&word) && **candidate != word) - .map(|candidate| (*candidate).to_owned()) - .collect() - } else { - Vec::new() - }; - let hover = |at: usize| Some(format!("position {at}")); - EditorView::new(editor, "Feuille", "sheet") - .completion(Some(Completion { - from, - items: &items, - })) - .hover(&hover) - .show(ui); - }, - Editor::new(text), - ) + crate::testing::harness().with_size(egui::vec2(600.0, 300.0)).build_ui_state( + |ui, editor: &mut Editor| { + let (from, word) = editor.word_at_caret(); + let items: Vec = if word.chars().count() >= 3 { + WORDS + .iter() + .filter(|candidate| candidate.starts_with(&word) && **candidate != word) + .map(|candidate| (*candidate).to_owned()) + .collect() + } else { + Vec::new() + }; + let hover = |at: usize| Some(format!("position {at}")); + EditorView::new(editor, "Feuille", "sheet") + .completion(Some(Completion { from, items: &items })) + .hover(&hover) + .show(ui); + }, + Editor::new(text), + ) } fn type_in(harness: &mut Harness<'_, Editor>, words: &str) { - harness - .get_by(|node| node.author_id() == Some("sheet")) - .click(); + harness.get_by(|node| node.author_id() == Some("sheet")).click(); harness.run(); let end = harness.state().buffer.len(); harness.state_mut().buffer.move_to(end, false); - harness - .get_by(|node| node.author_id() == Some("sheet")) - .type_text(words); + harness.get_by(|node| node.author_id() == Some("sheet")).type_text(words); harness.run(); harness.run(); } @@ -86,18 +77,10 @@ fn escape_closes_the_list_and_the_text_keeps_the_focus() { harness.run(); assert!(listed(&harness).is_empty()); - assert!( - harness - .get_by(|node| node.author_id() == Some("sheet")) - .is_focused() - ); + assert!(harness.get_by(|node| node.author_id() == Some("sheet")).is_focused()); harness.key_press(Key::Enter); harness.run(); - assert_eq!( - harness.state().text(), - "x = moy\n", - "Enter is the text's again" - ); + assert_eq!(harness.state().text(), "x = moy\n", "Enter is the text's again"); } #[test] @@ -106,8 +89,7 @@ fn an_entry_clicked_replaces_the_word() { type_in(&mut harness, "som"); harness .get_by(|node| { - node.author_id() == Some("editor-completion-option") - && node.label().as_deref() == Some("somme") + node.author_id() == Some("editor-completion-option") && node.label().as_deref() == Some("somme") }) .click(); harness.run(); @@ -126,9 +108,7 @@ fn the_word_at_the_caret_stops_at_what_is_not_a_letter() { #[test] fn the_tooltip_says_the_callers_words_for_the_position_hovered() { let mut harness = screen("abcdef"); - harness - .ctx - .all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + harness.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); harness.run(); let node = harness.get_by(|node| node.author_id() == Some("sheet")); let bounds = node.accesskit_node().bounding_box().unwrap(); @@ -139,10 +119,7 @@ fn the_tooltip_says_the_callers_words_for_the_position_hovered() { harness.step(); } let tip = harness.query_by(|node| node.author_id() == Some("editor-hover")); - assert!(tip.is_some_and(|tip| { - tip.accesskit_node() - .value() - .unwrap_or_default() - .starts_with("position") - })); + assert!( + tip.is_some_and(|tip| { tip.accesskit_node().value().unwrap_or_default().starts_with("position") }) + ); } diff --git a/crates/ui/src/widgets/editor/geometry.rs b/crates/ui/src/widgets/editor/geometry.rs index 6959a733f..ce3458471 100644 --- a/crates/ui/src/widgets/editor/geometry.rs +++ b/crates/ui/src/widgets/editor/geometry.rs @@ -138,24 +138,15 @@ pub(crate) fn galley( hang.min(width / 2.0) }); let mut job = LayoutJob::default(); - job.wrap.max_width = frame - .wrap - .map_or(f32::INFINITY, |width| width - hang.unwrap_or(0.0)); + job.wrap.max_width = frame.wrap.map_or(f32::INFINITY, |width| width - hang.unwrap_or(0.0)); let start = buffer.line_start(line); let runs = paint.map_or_else(Vec::new, |paint| runs(&text, line, start, paint, p)); let mut at = 0; let mut byte = 0; let mut push = |job: &mut LayoutJob, to: usize, colour: Color32, background: Color32| { - let end = text - .char_indices() - .nth(to) - .map_or(text.len(), |(index, _)| index); - let format = TextFormat { - font_id: frame.font.clone(), - color: colour, - background, - ..TextFormat::default() - }; + let end = text.char_indices().nth(to).map_or(text.len(), |(index, _)| index); + let format = + TextFormat { font_id: frame.font.clone(), color: colour, background, ..TextFormat::default() }; job.append(&text[byte..end], 0.0, format); byte = end; }; @@ -165,12 +156,7 @@ pub(crate) fn galley( at = to; } } - push( - &mut job, - text.chars().count(), - p.text_0, - Color32::TRANSPARENT, - ); + push(&mut job, text.chars().count(), p.text_0, Color32::TRANSPARENT); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); match hang { Some(hang) if galley.rows.len() > 1 => { @@ -194,15 +180,11 @@ fn runs( p: &crate::theme::tokens::Palette, ) -> Vec<(usize, Color32, Color32)> { let length = text.chars().count(); - let colours = paint - .colours - .map_or_else(Vec::new, |colours| colours(line, text)); + let colours = paint.colours.map_or_else(Vec::new, |colours| colours(line, text)); let decorations: Vec<(std::ops::Range, Mark)> = paint .decorations .iter() - .filter(|decoration| { - decoration.range.start < start + length && decoration.range.end > start - }) + .filter(|decoration| decoration.range.start < start + length && decoration.range.end > start) .map(|decoration| { let from = decoration.range.start.saturating_sub(start); let to = (decoration.range.end - start).min(length); @@ -212,11 +194,7 @@ fn runs( let mut cuts: Vec = colours .iter() .flat_map(|(range, _)| [range.start, range.end]) - .chain( - decorations - .iter() - .flat_map(|(range, _)| [range.start, range.end]), - ) + .chain(decorations.iter().flat_map(|(range, _)| [range.start, range.end])) .filter(|cut| *cut <= length) .collect(); cuts.push(length); @@ -257,13 +235,7 @@ pub(crate) fn origin(lines: &Lines, line: usize, frame: &Frame) -> Pos2 { } /// The caret's rectangle at `at`, on screen. -pub(crate) fn caret_rect( - ui: &Ui, - buffer: &Buffer, - lines: &Lines, - at: usize, - frame: &Frame, -) -> Rect { +pub(crate) fn caret_rect(ui: &Ui, buffer: &Buffer, lines: &Lines, at: usize, frame: &Frame) -> Rect { let line = buffer.line_of(at); let column = at - buffer.line_start(line); let galley = galley(ui, buffer, line, frame, None); @@ -271,6 +243,16 @@ pub(crate) fn caret_rect( local.translate(origin(lines, line, frame).to_vec2()) } +/// The character under `pos`: the caret goes to the nearer side of it. +pub(crate) fn char_at(ui: &Ui, buffer: &Buffer, lines: &Lines, pos: Pos2, frame: &Frame) -> usize { + let line = lines.line_at(pos.y - frame.top); + let galley = galley(ui, buffer, line, frame, None); + let local = pos - origin(lines, line, frame); + let cursor = galley.cursor_from_pos(local); + let before = local.x < galley.pos_from_cursor(cursor).center().x; + buffer.line_start(line) + cursor.index.0.saturating_sub(usize::from(before)) +} + /// The position under `pos`, on screen. pub(crate) fn hit(ui: &Ui, buffer: &Buffer, lines: &Lines, pos: Pos2, frame: &Frame) -> usize { if pos.y < frame.top { diff --git a/crates/ui/src/widgets/editor/input.rs b/crates/ui/src/widgets/editor/input.rs index 5bab65430..15598ce2b 100644 --- a/crates/ui/src/widgets/editor/input.rs +++ b/crates/ui/src/widgets/editor/input.rs @@ -11,7 +11,6 @@ use super::geometry::{self, Frame}; pub(crate) struct Keys<'a> { pub unit: &'a str, pub comment: Option<&'a str>, - pub read_only: bool, /// The viewport's height: how far Page Up and Page Down go. pub page: f32, } @@ -31,20 +30,18 @@ pub(crate) fn pointer(ui: &Ui, response: &Response, editor: &mut Editor, frame: } else { editor.buffer.len() }; - editor.buffer.select(Selection { - anchor: editor.buffer.line_start(line), - head: end, - }); + editor + .buffer + .select(Selection { anchor: editor.buffer.line_start(line), head: end }); } else if response.double_clicked() { - let start = editor.buffer.step(at, Direction::Backward, Unit::Word); - let end = editor.buffer.step(start, Direction::Forward, Unit::Word); - editor.buffer.select(Selection { - anchor: start, - head: end.max(at), - }); - } else if ui.input(|input| input.pointer.primary_pressed()) - && response.is_pointer_button_down_on() - { + let under = geometry::char_at(ui, &editor.buffer, &editor.lines, pos, frame); + let line = editor.buffer.line_of(under); + let start = editor.buffer.line_start(line); + let word = text::word_around(&editor.buffer.line(line), under - start); + editor + .buffer + .select(Selection { anchor: start + word.start, head: start + word.end }); + } else if ui.input(|input| input.pointer.primary_pressed()) && response.is_pointer_button_down_on() { editor.buffer.move_to(at, shift); response.request_focus(); } else if response.dragged() { @@ -57,41 +54,32 @@ pub(crate) fn pointer(ui: &Ui, response: &Response, editor: &mut Editor, frame: } /// The frame's events for the focused editor; the first line an edit touched. -pub(crate) fn keyboard( - ui: &Ui, - editor: &mut Editor, - keys: &Keys<'_>, - frame: &Frame, -) -> Option { +pub(crate) fn keyboard(ui: &Ui, editor: &mut Editor, keys: &Keys<'_>, frame: &Frame) -> Option { let events = ui.input(|input| input.events.clone()); let mut first: Option = None; let mut handled = Vec::with_capacity(events.len()); for event in &events { let edited = match event { - Event::Text(text) if !keys.read_only => Some(editor.buffer.insert(text).first_line), - Event::Paste(text) if !keys.read_only => Some(editor.buffer.insert(text).first_line), + Event::Text(text) | Event::Paste(text) => Some(editor.buffer.insert(text).first_line), Event::Copy => { copy(ui, editor); None } Event::Cut => { copy(ui, editor); - cut(editor, keys) + cut(editor) } - Event::Ime(ime) => ime_event(editor, ime, keys), - Event::Key { - key, - pressed: true, - modifiers, - .. - } => match key_event(ui, editor, (*key, *modifiers), keys, frame) { - Handled::No => { - handled.push(false); - continue; + Event::Ime(ime) => ime_event(editor, ime), + Event::Key { key, pressed: true, modifiers, .. } => { + match key_event(ui, editor, (*key, *modifiers), keys, frame) { + Handled::No => { + handled.push(false); + continue; + } + Handled::Moved => None, + Handled::Edited(line) => line, } - Handled::Moved => None, - Handled::Edited(line) => line, - }, + } _ => { handled.push(false); continue; @@ -142,15 +130,10 @@ fn key_event( } }; let edit = |line: Option| Handled::Edited(line.map(|edited| edited.first_line)); - let writable = !keys.read_only; match key { Key::ArrowLeft | Key::ArrowRight if modifiers.alt => Handled::No, Key::ArrowLeft | Key::ArrowRight => { - let direction = if key == Key::ArrowLeft { - Direction::Backward - } else { - Direction::Forward - }; + let direction = if key == Key::ArrowLeft { Direction::Backward } else { Direction::Forward }; let to = if !extend && !word && !buffer.selection().is_empty() { collapse(buffer, direction) } else { @@ -160,12 +143,8 @@ fn key_event( editor.goal_x = None; Handled::Moved } - Key::ArrowUp | Key::ArrowDown if modifiers.alt && writable => { - let direction = if key == Key::ArrowUp { - Direction::Backward - } else { - Direction::Forward - }; + Key::ArrowUp | Key::ArrowDown if modifiers.alt => { + let direction = if key == Key::ArrowUp { Direction::Backward } else { Direction::Forward }; edit(buffer.move_lines(direction)) } Key::ArrowUp | Key::ArrowDown if !modifiers.command => { @@ -175,21 +154,11 @@ fn key_event( } Key::PageUp | Key::PageDown => { let sign = if key == Key::PageUp { -1.0 } else { 1.0 }; - vertical( - ui, - editor, - sign * keys.page.max(frame.row_height), - extend, - frame, - ); + vertical(ui, editor, sign * keys.page.max(frame.row_height), extend, frame); Handled::Moved } Key::Home | Key::End => { - let direction = if key == Key::Home { - Direction::Backward - } else { - Direction::Forward - }; + let direction = if key == Key::Home { Direction::Backward } else { Direction::Forward }; let to = match (word, direction) { (true, Direction::Backward) => 0, (true, Direction::Forward) => buffer.len(), @@ -203,12 +172,10 @@ fn key_event( buffer.select_all(); Handled::Moved } - Key::Backspace if writable => edit(buffer.delete(Direction::Backward, unit)), - Key::Delete if writable => edit(buffer.delete(Direction::Forward, unit)), - Key::K if modifiers.command && modifiers.shift && writable => { - edit(buffer.delete(Direction::Forward, Unit::Line)) - } - Key::Enter if writable && !modifiers.command => { + Key::Backspace => edit(buffer.delete(Direction::Backward, unit)), + Key::Delete => edit(buffer.delete(Direction::Forward, unit)), + Key::K if modifiers.command && modifiers.shift => edit(buffer.delete(Direction::Forward, Unit::Line)), + Key::Enter if !modifiers.command => { let line = buffer.line_of(head); let before: String = buffer .line(line) @@ -218,12 +185,12 @@ fn key_event( .collect(); edit(Some(buffer.insert(&format!("\n{before}")))) } - Key::Tab if writable && modifiers.shift => edit(buffer.outdent(keys.unit)), - Key::Tab if writable && modifiers.is_none() => edit(Some(buffer.indent(keys.unit))), - Key::Z if modifiers.command && modifiers.shift && writable => edit(buffer.redo()), - Key::Z if modifiers.command && writable => edit(buffer.undo()), - Key::Y if modifiers.command && writable => edit(buffer.redo()), - Key::Slash if modifiers.command && writable => match keys.comment { + Key::Tab if modifiers.shift => edit(buffer.outdent(keys.unit)), + Key::Tab if modifiers.is_none() => edit(Some(buffer.indent(keys.unit))), + Key::Z if modifiers.command && modifiers.shift => edit(buffer.redo()), + Key::Z if modifiers.command => edit(buffer.undo()), + Key::Y if modifiers.command => edit(buffer.redo()), + Key::Slash if modifiers.command => match keys.comment { Some(token) => edit(Some(buffer.toggle_comment(token))), None => Handled::No, }, @@ -238,16 +205,8 @@ fn home_or_end(buffer: &text::Buffer, head: usize, direction: Direction) -> usiz match direction { Direction::Forward => buffer.line_end(line), Direction::Backward => { - let indent = buffer - .line(line) - .chars() - .take_while(|c| c.is_whitespace()) - .count(); - if head == start + indent { - start - } else { - start + indent - } + let indent = buffer.line(line).chars().take_while(|c| c.is_whitespace()).count(); + if head == start + indent { start } else { start + indent } } } } @@ -276,8 +235,8 @@ fn copy(ui: &Ui, editor: &Editor) { } } -fn cut(editor: &mut Editor, keys: &Keys<'_>) -> Option { - if keys.read_only || editor.buffer.selection().is_empty() { +fn cut(editor: &mut Editor) -> Option { + if editor.buffer.selection().is_empty() { return None; } editor @@ -287,7 +246,7 @@ fn cut(editor: &mut Editor, keys: &Keys<'_>) -> Option { } /// A composition is drawn at the caret while it is built; only what it commits is typed. -fn ime_event(editor: &mut Editor, ime: &ImeEvent, keys: &Keys<'_>) -> Option { +fn ime_event(editor: &mut Editor, ime: &ImeEvent) -> Option { match ime { ImeEvent::Preedit { text, .. } => { editor.preedit.clone_from(text); @@ -295,19 +254,13 @@ fn ime_event(editor: &mut Editor, ime: &ImeEvent, keys: &Keys<'_>) -> Option { editor.preedit.clear(); - (!keys.read_only && !text.is_empty()).then(|| editor.buffer.insert(text).first_line) + (!text.is_empty()).then(|| editor.buffer.insert(text).first_line) } - ImeEvent::DeleteSurrounding { - before_chars, - after_chars, - } if !keys.read_only => { + ImeEvent::DeleteSurrounding { before_chars, after_chars } => { let head = editor.buffer.selection().head; let from = head.saturating_sub(*before_chars); let to = (head + after_chars).min(editor.buffer.len()); - editor.buffer.select(Selection { - anchor: from, - head: to, - }); + editor.buffer.select(Selection { anchor: from, head: to }); editor .buffer .delete(Direction::Backward, Unit::Grapheme) diff --git a/crates/ui/src/widgets/editor/mod.rs b/crates/ui/src/widgets/editor/mod.rs index 3af2398c6..a9d78fdad 100644 --- a/crates/ui/src/widgets/editor/mod.rs +++ b/crates/ui/src/widgets/editor/mod.rs @@ -12,8 +12,7 @@ use std::ops::Range; use egui::text::CCursor; use egui::{ - Color32, FontFamily, FontId, Galley, Id, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, - WidgetInfo, + Color32, FontFamily, FontId, Galley, Id, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, WidgetInfo, }; use text::{Buffer, Selection}; @@ -68,10 +67,7 @@ pub struct Editor { impl Editor { pub fn new(text: &str) -> Self { - Self { - buffer: Buffer::new(text), - ..Self::default() - } + Self { buffer: Buffer::new(text), ..Self::default() } } pub fn text(&self) -> String { @@ -95,11 +91,7 @@ impl Editor { /// The lines the last frame drew; a first screenful before any. pub fn visible_lines(&self) -> Range { - if self.visible.is_empty() { - 0..self.buffer.line_count().min(80) - } else { - self.visible.clone() - } + if self.visible.is_empty() { 0..self.buffer.line_count().min(80) } else { self.visible.clone() } } /// The selection brought into view at the next frame. @@ -114,10 +106,7 @@ impl Editor { /// `range` selected and shown. pub fn select(&mut self, range: Range) { - self.buffer.select(Selection { - anchor: range.start, - head: range.end, - }); + self.buffer.select(Selection { anchor: range.start, head: range.end }); self.reveal = true; } } @@ -125,10 +114,7 @@ impl Editor { /// ⚠️ An id of its own, not the next automatic one: a bar opening above would change it, and the /// text would lose the focus as the bar closes. fn text_surface(ui: &Ui, visible: Rect, id: Id) -> Response { - #[expect( - clippy::disallowed_methods, - reason = "named and addressed by the view, as the text" - )] + #[expect(clippy::disallowed_methods, reason = "named and addressed by the view, as the text")] let surface = ui.interact(visible, id.with("text"), Sense::click_and_drag()); if surface.hovered() || surface.dragged() { ui.ctx().set_cursor_icon(egui::CursorIcon::Text); @@ -162,7 +148,6 @@ pub struct EditorView<'a> { comment: Option<&'a str>, wrap: bool, gutter: bool, - read_only: bool, font: FontId, decorations: &'a [Decoration], marked_lines: &'a [usize], @@ -185,7 +170,6 @@ impl<'a> EditorView<'a> { comment: None, wrap: false, gutter: true, - read_only: false, font: FontId::new(font::READING, FontFamily::Monospace), decorations: &[], marked_lines: &[], @@ -250,12 +234,6 @@ impl<'a> EditorView<'a> { self } - #[must_use] - pub fn read_only(mut self, read_only: bool) -> Self { - self.read_only = read_only; - self - } - #[must_use] pub fn font(mut self, font: FontId) -> Self { self.font = font; @@ -301,34 +279,17 @@ impl<'a> EditorView<'a> { let char_width = ui.fonts_mut(|fonts| fonts.glyph_width(&self.font, '0')); let digits = self.editor.buffer.line_count().to_string().len().max(2); #[expect(clippy::cast_precision_loss, reason = "a handful of digits")] - let gutter = if self.gutter { - digits as f32 * char_width + 2.0 * PADDING - } else { - 0.0 - }; - let scroll = if self.wrap { - egui::ScrollArea::vertical() - } else { - egui::ScrollArea::both() - }; + let gutter = if self.gutter { digits as f32 * char_width + 2.0 * PADDING } else { 0.0 }; + let scroll = if self.wrap { egui::ScrollArea::vertical() } else { egui::ScrollArea::both() }; let mut changed = None; let mut rows = Vec::new(); let shown = scroll .id_salt(id.with("scroll")) .auto_shrink(false) .show_viewport(ui, |ui, viewport| { - self.body( - ui, - id, - (viewport, gutter, row_height, char_width), - (&mut changed, &mut rows), - ) + self.body(ui, id, (viewport, gutter, row_height, char_width), (&mut changed, &mut rows)) }); - Output { - response: shown.inner, - changed, - rows, - } + Output { response: shown.inner, changed, rows } } fn body( @@ -370,15 +331,10 @@ impl<'a> EditorView<'a> { lock_focus(ui, id, bubbles::open(editor, self.completion.as_ref())); } input::pointer(ui, &response, editor, &frame); - let keys = input::Keys { - unit: self.unit, - comment: self.comment, - read_only: self.read_only, - page: viewport.height(), - }; + let keys = input::Keys { unit: self.unit, comment: self.comment, page: viewport.height() }; // While the pointer is on the list, a click on it moves the focus there: it stays shown. - let listing = bubbles::open(editor, self.completion.as_ref()) - && (focused || bubbles::pointer_on_list(ui, id)); + let listing = + bubbles::open(editor, self.completion.as_ref()) && (focused || bubbles::pointer_on_list(ui, id)); if listing && focused && let Some(completion) = &self.completion @@ -389,7 +345,7 @@ impl<'a> EditorView<'a> { if focused && let Some(first) = input::keyboard(ui, editor, &keys, &frame) { *changed = Some(changed.map_or(first, |earlier| earlier.min(first))); } - if let Some(first) = menu(&response, editor, &keys, self.language) { + if let Some(first) = menu(&response, editor, self.language) { *changed = Some(changed.map_or(first, |earlier| earlier.min(first))); } if let Some(first) = *changed { @@ -398,10 +354,7 @@ impl<'a> EditorView<'a> { response.mark_changed(); } let style = Style { - paint: geometry::Paint { - colours: self.colours, - decorations: self.decorations, - }, + paint: geometry::Paint { colours: self.colours, decorations: self.decorations }, marked: self.marked_lines, lit: self.lit_lines.clone(), hint: self.hint, @@ -460,21 +413,13 @@ fn rows_on_screen<'a>( /// The keys the text keeps: Tab and the arrows; Escape too while a list is open, which it /// closes rather than leaving the text. fn lock_focus(ui: &Ui, id: egui::Id, escape: bool) { - let filter = egui::EventFilter { - tab: true, - horizontal_arrows: true, - vertical_arrows: true, - escape, - }; + let filter = egui::EventFilter { tab: true, horizontal_arrows: true, vertical_arrows: true, escape }; ui.memory_mut(|memory| memory.set_focus_lock_filter(id, filter)); } /// Where the window puts the input method's window: at the caret. fn ask_input_method(ui: &Ui, visible: Rect, caret: Rect) { - let to_global = ui - .ctx() - .layer_transform_to_global(ui.layer_id()) - .unwrap_or_default(); + let to_global = ui.ctx().layer_transform_to_global(ui.layer_id()).unwrap_or_default(); ui.ctx().output_mut(|output| { output.ime = Some(egui::output::IMEOutput { purpose: egui::IMEPurpose::Normal, @@ -497,13 +442,7 @@ struct Style<'a> { /// The visible lines: gutter, current line, selection, text, composition and caret. Answers /// the caret's rectangle. -fn paint( - ui: &Ui, - editor: &mut Editor, - frame: &geometry::Frame, - visible: Rect, - style: &Style<'_>, -) -> Rect { +fn paint(ui: &Ui, editor: &mut Editor, frame: &geometry::Frame, visible: Rect, style: &Style<'_>) -> Rect { let p = palette(ui.ctx()); let painter = ui.painter_at(visible); let selection = editor.buffer.selection(); @@ -520,30 +459,19 @@ fn paint( editor.lines.set_height(line, height); let at = geometry::origin(&editor.lines, line, frame); if style.focused && selected.is_empty() && line == head_line { - let row = Rect::from_min_size( - Pos2::new(visible.left(), at.y), - Vec2::new(visible.width(), height), - ); + let row = + Rect::from_min_size(Pos2::new(visible.left(), at.y), Vec2::new(visible.width(), height)); painter.rect_filled(row, 0.0, p.bg_2); } if style.lit.contains(&line) { - let row = Rect::from_min_size( - Pos2::new(visible.left(), at.y), - Vec2::new(visible.width(), height), - ); + let row = + Rect::from_min_size(Pos2::new(visible.left(), at.y), Vec2::new(visible.width(), height)); painter.rect_filled(row, 0.0, p.blue.gamma_multiply(0.1)); let bar = Rect::from_min_size(row.min, Vec2::new(3.0, height)); painter.rect_filled(bar, 0.0, p.blue); } if style.gutter > 0.0 { - gutter_cell( - &painter, - (line, line == head_line), - at.y, - gutter_left, - style, - frame, - ); + gutter_cell(&painter, (line, line == head_line), at.y, gutter_left, style, frame); } let start = editor.buffer.line_start(line); let length = editor.buffer.line(line).chars().count(); @@ -566,23 +494,12 @@ fn paint( let mut caret_x = caret.left(); if !editor.preedit.is_empty() { let family = frame.font.family.clone(); - let composed = crate::widgets::text( - ui, - &editor.preedit, - frame.font.size, - 400.0, - family, - p.text_0, - ); + let composed = crate::widgets::text(ui, &editor.preedit, frame.font.size, 400.0, family, p.text_0); let width = composed.size().x; let under = Rect::from_min_size(caret.min, Vec2::new(width, caret.height())); painter.rect_filled(under, 0.0, p.bg_1); painter.galley(caret.min, composed, p.text_0); - painter.hline( - caret.left()..=caret.left() + width, - caret.bottom() - 1.0, - Stroke::new(1.0, p.text_1), - ); + painter.hline(caret.left()..=caret.left() + width, caret.bottom() - 1.0, Stroke::new(1.0, p.text_1)); caret_x += width; } if style.focused { @@ -606,10 +523,8 @@ fn gutter_cell( let right = left + style.gutter - PADDING; painter.galley(Pos2::new(right - number.size().x, top), number, ink); if style.marked.binary_search(&line).is_ok() { - let bar = Rect::from_min_size( - Pos2::new(left + style.gutter - 3.0, top), - Vec2::new(2.0, frame.row_height), - ); + let bar = + Rect::from_min_size(Pos2::new(left + style.gutter - 3.0, top), Vec2::new(2.0, frame.row_height)); painter.rect_filled(bar, 1.0, p.amber_text); } } @@ -632,10 +547,7 @@ pub(crate) fn selection_rects( let last = index + 1 == rows; if from < to || (last && past_end) { // A row's start is also the end of the row above when the line wraps there: on this one. - let start = CCursor { - index: from.into(), - prefer_next_row: true, - }; + let start = CCursor { index: from.into(), prefer_next_row: true }; let x0 = galley.pos_from_cursor(start).left(); let mut x1 = galley.pos_from_cursor(CCursor::new(to)).left(); if last && past_end { @@ -650,27 +562,18 @@ pub(crate) fn selection_rects( /// Cut, copy, paste, select all. Paste asks the window for the clipboard: it arrives at the next /// frame as an event the keys take. -fn menu( - response: &Response, - editor: &mut Editor, - keys: &input::Keys<'_>, - language: i18n::Language, -) -> Option { +fn menu(response: &Response, editor: &mut Editor, language: i18n::Language) -> Option { use i18n::keys::editor::menu as words; let mut edited = None; response.context_menu(|ui| { let tr = |key| i18n::translate(language, key, &[]); - let writable = !keys.read_only; let entries = [ - (words::CUT, "editor-menu-cut", writable), - (words::COPY, "editor-menu-copy", true), - (words::PASTE, "editor-menu-paste", writable), - (words::SELECT_ALL, "editor-menu-select-all", true), + (words::CUT, "editor-menu-cut"), + (words::COPY, "editor-menu-copy"), + (words::PASTE, "editor-menu-paste"), + (words::SELECT_ALL, "editor-menu-select-all"), ]; - for (key, author_id, shown) in entries { - if !shown { - continue; - } + for (key, author_id) in entries { let label = tr(key); if !crate::widgets::menu_entry(ui, &label, author_id, false, false, false).clicked() { continue; diff --git a/crates/ui/src/widgets/editor/tests.rs b/crates/ui/src/widgets/editor/tests.rs index 3fe3210c4..480da3ffa 100644 --- a/crates/ui/src/widgets/editor/tests.rs +++ b/crates/ui/src/widgets/editor/tests.rs @@ -8,37 +8,40 @@ use super::*; struct Screen { editor: Editor, changed: Vec, - read_only: bool, wrap: bool, + comment: Option<&'static str>, + /// The keys the text left to the rest of the window. + left: Vec, } fn screen(text: &str) -> Harness<'static, Screen> { let state = Screen { editor: Editor::new(text), changed: Vec::new(), - read_only: false, wrap: false, + comment: Some("#"), + left: Vec::new(), }; - crate::testing::harness() - .with_size(egui::vec2(600.0, 300.0)) - .build_ui_state( - |ui, screen: &mut Screen| { - let output = EditorView::new(&mut screen.editor, "Code", "code") - .indent_unit(" ") - .comment(Some("#")) - .read_only(screen.read_only) - .wrap(screen.wrap) - .show(ui); - screen.changed.extend(output.changed); - }, - state, - ) + crate::testing::harness().with_size(egui::vec2(600.0, 300.0)).build_ui_state( + |ui, screen: &mut Screen| { + let output = EditorView::new(&mut screen.editor, "Code", "code") + .indent_unit(" ") + .comment(screen.comment) + .wrap(screen.wrap) + .show(ui); + screen.changed.extend(output.changed); + let left = ui.input(|input| input.events.clone()); + screen.left.extend(left.iter().filter_map(|event| match event { + Event::Key { key, pressed: true, .. } => Some(*key), + _ => None, + })); + }, + state, + ) } fn focus(harness: &mut Harness<'_, Screen>) { - harness - .get_by(|node| node.author_id() == Some("code")) - .click(); + harness.get_by(|node| node.author_id() == Some("code")).click(); harness.run(); } @@ -60,9 +63,7 @@ fn typing_goes_into_the_text_and_says_from_which_line() { let mut harness = screen("a\nb"); focus(&mut harness); harness.state_mut().editor.buffer.move_to(3, false); - harness - .get_by(|node| node.author_id() == Some("code")) - .type_text("c"); + harness.get_by(|node| node.author_id() == Some("code")).type_text("c"); harness.run(); assert_eq!(text(&harness), "a\nbc"); @@ -75,145 +76,446 @@ fn typing_goes_into_the_text_and_says_from_which_line() { assert_eq!(value, "a\nbc"); } -#[test] -fn tab_stays_in_the_text_and_shift_tab_takes_it_back() { - let mut harness = screen("x"); +const NONE: Modifiers = Modifiers::NONE; +const SHIFT: Modifiers = Modifiers::SHIFT; +const ALT: Modifiers = Modifiers::ALT; +const CTRL: Modifiers = Modifiers::COMMAND; + +fn select(harness: &mut Harness<'_, Screen>, anchor: usize, head: usize) { + let selection = text::Selection { anchor, head }; + harness.state_mut().editor.buffer.select(selection); +} + +/// The text of `before` with `|` at the caret, `[` and `]` around what is selected. +fn marked(before: &str) -> (String, usize, usize) { + let mut plain = String::new(); + let (mut anchor, mut head) = (None, None); + for c in before.chars() { + match c { + '[' => anchor = Some(plain.chars().count()), + ']' | '|' => head = Some(plain.chars().count()), + c => plain.push(c), + } + } + let head = head.unwrap_or_default(); + (plain, anchor.unwrap_or(head), head) +} + +fn opened_at(before: &str) -> Harness<'static, Screen> { + let (plain, anchor, head) = marked(before); + let mut harness = screen(&plain); focus(&mut harness); - harness.state_mut().editor.buffer.move_to(0, false); - press(&mut harness, Modifiers::NONE, Key::Tab); - assert_eq!(text(&harness), " x"); - assert!( - harness - .get_by(|node| node.author_id() == Some("code")) - .is_focused(), - "the focus did not move on" - ); - press(&mut harness, Modifiers::SHIFT, Key::Tab); - assert_eq!(text(&harness), "x"); + select(&mut harness, anchor, head); + harness +} + +fn assert_shows(harness: &Harness<'_, Screen>, after: &str, why: &str) { + let (plain, anchor, head) = marked(after); + let selection = harness.state().editor.buffer.selection(); + let found = (text(harness), selection.anchor, selection.head); + assert_eq!(found, (plain, anchor, head), "{why}"); } +// The keys + #[test] -fn enter_keeps_the_indentation_of_the_line() { - let mut harness = screen(" if x:"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(7, false); - press(&mut harness, Modifiers::NONE, Key::Enter); - assert_eq!(text(&harness), " if x:\n "); +fn the_keys_move_the_caret() { + for (modifiers, key, before, after) in [ + (NONE, Key::ArrowLeft, "ab|c", "a|bc"), + (NONE, Key::ArrowRight, "a|bc", "ab|c"), + (NONE, Key::ArrowLeft, "a[bc]d", "a|bcd"), + (NONE, Key::ArrowRight, "a[bc]d", "abc|d"), + (CTRL, Key::ArrowLeft, "one two|", "one |two"), + (CTRL, Key::ArrowRight, "|one two", "one| two"), + (NONE, Key::ArrowUp, "abc\nab|c", "ab|c\nabc"), + (NONE, Key::ArrowDown, "ab|c\nabc", "abc\nab|c"), + (NONE, Key::ArrowUp, "ab|c\nabc", "|abc\nabc"), + (NONE, Key::ArrowDown, "abc\na|bc", "abc\nabc|"), + (NONE, Key::Home, " ab|c", " |abc"), + (NONE, Key::Home, " |abc", "| abc"), + (NONE, Key::Home, "| abc", " |abc"), + (NONE, Key::End, "a|bc\nd", "abc|\nd"), + (CTRL, Key::Home, "abc\nd|e", "|abc\nde"), + (CTRL, Key::End, "a|bc\nde", "abc\nde|"), + (CTRL, Key::A, "a|b\nc", "[ab\nc]"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + assert!(harness.state().changed.is_empty(), "{key:?} changed nothing"); + } } #[test] -fn shift_arrows_select_and_backspace_takes_the_selection() { - let mut harness = screen("hello world"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(11, false); - press( - &mut harness, - Modifiers::SHIFT | Modifiers::COMMAND, - Key::ArrowLeft, - ); - assert_eq!(harness.state().editor.buffer.selected_text(), "world"); - press(&mut harness, Modifiers::NONE, Key::Backspace); - assert_eq!(text(&harness), "hello "); - press(&mut harness, Modifiers::COMMAND, Key::Z); - assert_eq!(text(&harness), "hello world"); +fn shift_stretches_the_selection_to_where_the_key_goes() { + for (modifiers, key, before, after) in [ + (SHIFT, Key::ArrowRight, "a|bc", "a[b]c"), + (SHIFT, Key::ArrowRight, "a[b]c", "a[bc]"), + (SHIFT, Key::ArrowDown, "a|bc\nabc", "a[bc\na]bc"), + (SHIFT, Key::End, "a|bc", "a[bc]"), + (SHIFT | CTRL, Key::ArrowRight, "|one two", "[one] two"), + (SHIFT | CTRL, Key::End, "a|b\nc", "a[b\nc]"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + } +} + +#[test] +fn the_keys_edit_the_text() { + for (modifiers, key, before, after) in [ + (NONE, Key::Backspace, "ab|c", "a|c"), + (NONE, Key::Delete, "a|bc", "a|c"), + (NONE, Key::Backspace, "a[bc]d", "a|d"), + (CTRL, Key::Backspace, "one two|", "one |"), + (CTRL, Key::Delete, "|one two", "| two"), + (CTRL | SHIFT, Key::K, "one\nt|wo\nthree", "one\n|three"), + (NONE, Key::Enter, " if x:|", " if x:\n |"), + (NONE, Key::Enter, " | x", " \n | x"), + (NONE, Key::Tab, "|x", " |x"), + (SHIFT, Key::Tab, " |x", "|x"), + (ALT, Key::ArrowUp, "a\nb|", "b|\na"), + (ALT, Key::ArrowDown, "|a\nb", "b\n|a"), + (CTRL, Key::Slash, "a|b", "# a|b"), + ] { + let mut harness = opened_at(before); + press(&mut harness, modifiers, key); + assert_shows(&harness, after, &format!("{key:?} in {before:?}")); + assert!(!harness.state().changed.is_empty(), "{key:?} said the change"); + } +} + +#[test] +fn what_is_undone_is_redone_by_either_key() { + for (modifiers, key) in [(CTRL, Key::Y), (CTRL | SHIFT, Key::Z)] { + let mut harness = opened_at("ab|"); + press(&mut harness, NONE, Key::Backspace); + press(&mut harness, CTRL, Key::Z); + assert_eq!(text(&harness), "ab"); + press(&mut harness, modifiers, key); + assert_eq!(text(&harness), "a", "{key:?}"); + } } #[test] fn up_and_down_keep_the_column_across_a_short_line() { - let mut harness = screen("abcdef\nab\nabcdef"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(5, false); - press(&mut harness, Modifiers::NONE, Key::ArrowDown); - assert_eq!(caret(&harness), 9, "the short line's end"); - press(&mut harness, Modifiers::NONE, Key::ArrowDown); - assert_eq!(caret(&harness), 15, "back to column 5"); - press(&mut harness, Modifiers::NONE, Key::Home); - assert_eq!(caret(&harness), 10); - press(&mut harness, Modifiers::NONE, Key::End); - assert_eq!(caret(&harness), 16); - press(&mut harness, Modifiers::COMMAND, Key::Home); - assert_eq!(caret(&harness), 0); + let mut harness = opened_at("abcde|f\nab\nabcdef"); + press(&mut harness, NONE, Key::ArrowDown); + assert_shows(&harness, "abcdef\nab|\nabcdef", "the short line's end"); + press(&mut harness, NONE, Key::ArrowDown); + assert_shows(&harness, "abcdef\nab\nabcde|f", "back to its column"); } +/// The column is where the last move or the last edit left the caret, not where it once was. #[test] -fn alt_arrows_move_the_line_and_ctrl_slash_comments_it() { - let mut harness = screen("a\nb"); - focus(&mut harness); - harness.state_mut().editor.buffer.move_to(2, false); - press(&mut harness, Modifiers::ALT, Key::ArrowUp); - assert_eq!(text(&harness), "b\na"); - press(&mut harness, Modifiers::COMMAND, Key::Slash); - assert_eq!(text(&harness), "# b\na"); +fn a_move_or_an_edit_between_two_lines_forgets_the_column() { + for (key, lands) in [(Key::ArrowLeft, 8), (Key::End, 9), (Key::Backspace, 8)] { + let mut harness = opened_at("abcde|f\nab\nabcdef"); + press(&mut harness, NONE, Key::ArrowDown); + press(&mut harness, NONE, key); + assert_eq!(caret(&harness), lands, "{key:?}"); + press(&mut harness, NONE, Key::ArrowDown); + let line = harness.state().editor.buffer.line_start(2); + let column = lands - 7; + assert_eq!(caret(&harness) - line, column, "{key:?}"); + } } #[test] -fn a_composition_shows_until_it_commits_and_only_the_commit_is_typed() { - let mut harness = screen(""); - focus(&mut harness); - harness.event(Event::Ime(ImeEvent::Preedit { - text: "e".into(), - active_range_chars: None, - })); +fn a_page_goes_as_far_as_the_text_shown() { + let lines: Vec = (0..200).map(|n| format!("line {n}")).collect(); + let mut harness = opened_at(&format!("|{}", lines.join("\n"))); + let page = harness.state().editor.visible_lines().len(); + let line = |harness: &Harness<'_, Screen>| harness.state().editor.buffer.line_of(caret(harness)); + press(&mut harness, NONE, Key::PageDown); + let down = line(&harness); + assert!(down + 3 > page && down <= page, "{down} of {page}"); + + press(&mut harness, NONE, Key::PageUp); + assert_eq!(line(&harness), 0); + press(&mut harness, SHIFT, Key::PageDown); + assert!(!harness.state().editor.buffer.selection().is_empty()); +} + +/// Ctrl+Z is the text's and Ctrl+S the window's (D14). +#[test] +fn a_key_the_text_takes_is_not_left_to_the_window() { + let mut harness = opened_at("ab|"); + for (modifiers, key, left) in [ + (CTRL, Key::Z, false), + (NONE, Key::ArrowLeft, false), + (NONE, Key::Tab, false), + (CTRL, Key::Slash, false), + (CTRL, Key::S, true), + (CTRL, Key::Enter, true), + (CTRL, Key::ArrowDown, true), + (ALT, Key::ArrowLeft, true), + (CTRL, Key::K, true), + ] { + harness.state_mut().left.clear(); + press(&mut harness, modifiers, key); + assert_eq!(harness.state().left.contains(&key), left, "{modifiers:?} {key:?}"); + } +} + +#[test] +fn with_no_comment_to_put_ctrl_slash_is_left_to_the_window() { + let mut harness = opened_at("ab|"); + harness.state_mut().comment = None; + press(&mut harness, CTRL, Key::Slash); + + assert_eq!(text(&harness), "ab"); + assert!(harness.state().left.contains(&Key::Slash)); +} + +/// Not the next control: the focus stays in the text. +#[test] +fn tab_keeps_the_focus_in_the_text() { + let mut harness = opened_at("|x"); + press(&mut harness, NONE, Key::Tab); + + let code = harness.get_by(|node| node.author_id() == Some("code")); + assert!(code.is_focused()); +} + +#[test] +fn what_is_not_focused_takes_no_key() { + let mut harness = screen("abc"); + harness.event(Event::Text("x".into())); + press(&mut harness, NONE, Key::Delete); + + assert_eq!(text(&harness), "abc"); +} + +// The clipboard + +/// What the frames of `event` put on the clipboard. +fn copied(harness: &mut Harness<'_, Screen>, event: Event) -> Option { + harness.event(event); + harness.step(); + let commands = &harness.output().platform_output.commands; + commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) +} + +#[test] +fn a_copy_takes_what_is_selected_and_leaves_it() { + let mut harness = opened_at("a[bc]d"); + assert_eq!(copied(&mut harness, Event::Copy).as_deref(), Some("bc")); + assert_shows(&harness, "a[bc]d", "left"); +} + +#[test] +fn a_cut_takes_what_is_selected_out() { + let mut harness = opened_at("x\na[bc]d"); + assert_eq!(copied(&mut harness, Event::Cut).as_deref(), Some("bc")); harness.run(); - assert_eq!(text(&harness), ""); - assert_eq!(harness.state().editor.preedit, "e"); - harness.event(Event::Ime(ImeEvent::Commit("ê".into()))); + assert_shows(&harness, "x\na|d", "out"); + assert_eq!(harness.state().changed, [1]); +} + +/// The clipboard keeps what it holds. +#[test] +fn with_nothing_selected_there_is_nothing_to_copy_or_cut() { + for event in [Event::Copy, Event::Cut] { + let mut harness = opened_at("ab|c"); + assert_eq!(copied(&mut harness, event.clone()), None, "{event:?}"); + assert_eq!(text(&harness), "abc", "{event:?}"); + } +} + +#[test] +fn a_paste_replaces_what_is_selected() { + let mut harness = opened_at("a[bc]d"); + harness.event(Event::Paste("X\nY".into())); harness.run(); + + assert_shows(&harness, "aX\nY|d", "pasted"); +} + +// The input method + +fn ime(harness: &mut Harness<'_, Screen>, event: ImeEvent) { + harness.event(Event::Ime(event)); + harness.run(); +} + +fn preedit(words: &str) -> ImeEvent { + ImeEvent::Preedit { text: words.into(), active_range_chars: None } +} + +#[test] +fn a_composition_is_drawn_and_only_its_commit_is_typed() { + let mut harness = opened_at("|"); + ime(&mut harness, preedit("e")); + assert_eq!(text(&harness), ""); + assert!(crate::testing::painted(&harness).contains(&"e".to_owned())); + + ime(&mut harness, ImeEvent::Commit("ê".into())); assert_eq!(text(&harness), "ê"); assert!(harness.state().editor.preedit.is_empty()); } #[test] -fn a_focused_editor_asks_for_the_input_method_at_its_caret() { - let mut harness = screen("abc"); - focus(&mut harness); - let ime = harness.output().platform_output.ime; - assert!(ime.is_some()); +fn a_composition_given_up_types_nothing() { + let mut harness = opened_at("|"); + ime(&mut harness, preedit("e")); + ime(&mut harness, preedit("")); + assert!(harness.state().editor.preedit.is_empty()); + + ime(&mut harness, ImeEvent::Commit(String::new())); + assert!(text(&harness).is_empty() && harness.state().changed.is_empty()); } #[test] -fn a_read_only_text_moves_and_selects_but_takes_no_typing() { - let mut harness = screen("abc"); - harness.state_mut().read_only = true; - focus(&mut harness); - harness - .get_by(|node| node.author_id() == Some("code")) - .type_text("x"); - press(&mut harness, Modifiers::NONE, Key::Backspace); - press(&mut harness, Modifiers::COMMAND, Key::A); - assert_eq!(text(&harness), "abc"); - assert_eq!(harness.state().editor.buffer.selected_text(), "abc"); +fn the_input_method_takes_out_what_is_around_the_caret() { + for (before_chars, after_chars, after) in [(1, 0, "a|cd"), (0, 1, "ab|d"), (2, 1, "|d"), (9, 9, "|")] { + let mut harness = opened_at("ab|cd"); + ime(&mut harness, ImeEvent::DeleteSurrounding { before_chars, after_chars }); + assert_shows(&harness, after, &format!("{before_chars} and {after_chars}")); + } +} + +// The pointer + +fn pointer(harness: &mut Harness<'_, Screen>, at: egui::Pos2, pressed: bool, modifiers: Modifiers) { + harness.event(Event::PointerMoved(at)); + harness.event(Event::ModifiersChanged(modifiers)); + harness.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }); + harness.run(); +} + +fn click(harness: &mut Harness<'_, Screen>, at: egui::Pos2, modifiers: Modifiers) { + pointer(harness, at, true, modifiers); + pointer(harness, at, false, modifiers); + harness.event(Event::ModifiersChanged(NONE)); } #[test] -fn the_context_menu_selects_all() { - let mut harness = screen("one two"); - harness - .get_by(|node| node.author_id() == Some("code")) - .click_secondary(); +fn a_press_puts_the_caret_on_the_nearer_side_of_the_character() { + for (part, at) in [(0.2, 2), (0.8, 3)] { + let mut harness = screen("abcdef"); + harness.run(); + let pointed = point(&harness, "abcdef", 2, part); + click(&mut harness, pointed, NONE); + assert_eq!(caret(&harness), at, "{part}"); + assert!(harness.state().editor.buffer.selection().is_empty()); + } +} + +#[test] +fn a_press_with_shift_stretches_the_selection_to_it() { + let mut harness = opened_at("a|bcdef"); + let pointed = point(&harness, "abcdef", 4, 0.1); + click(&mut harness, pointed, SHIFT); + + assert_shows(&harness, "a[bcd]ef", "stretched"); +} + +#[test] +fn a_drag_selects_from_where_it_was_pressed() { + let mut harness = screen("abcdef\nsecond"); + harness.run(); + let from = point(&harness, "abcdef", 1, 0.1); + let to = point(&harness, "second", 3, 0.1); + pointer(&mut harness, from, true, NONE); + harness.event(Event::PointerMoved(to)); + harness.run(); + pointer(&mut harness, to, false, NONE); + + assert_shows(&harness, "a[bcdef\nsec]ond", "dragged"); +} + +/// Below the last line is the end of it, above the text its start. +#[test] +fn a_press_under_the_text_is_on_its_last_line() { + let mut harness = screen("abc\ndef"); + harness.run(); + click(&mut harness, egui::pos2(300.0, 250.0), NONE); + + assert_eq!(caret(&harness), 7); +} + +// The menu + +fn menu_of(harness: &mut Harness<'_, Screen>) { + let code = harness.get_by(|node| node.author_id() == Some("code")); + code.click_secondary(); harness.run(); +} + +fn choose(harness: &mut Harness<'_, Screen>, entry: &str) { + harness.get_by(|node| node.author_id() == Some(entry)).click(); + harness.step(); + harness.step(); +} + +fn offered(harness: &Harness<'_, Screen>) -> Vec { harness - .get_by(|node| node.author_id() == Some("editor-menu-select-all")) - .click(); + .query_all_by(|node| node.author_id().is_some_and(|id| id.starts_with("editor-menu-"))) + .filter_map(|node| node.accesskit_node().author_id().map(str::to_owned)) + .collect() +} + +#[test] +fn the_menu_offers_what_the_text_takes() { + let mut harness = screen("abc"); + menu_of(&mut harness); + assert_eq!( + offered(&harness), + ["editor-menu-cut", "editor-menu-copy", "editor-menu-paste", "editor-menu-select-all"] + ); +} + +#[test] +fn the_menu_copies_and_cuts_what_is_selected() { + for (entry, after) in [("editor-menu-copy", "a[bc]d"), ("editor-menu-cut", "a|d")] { + let mut harness = opened_at("a[bc]d"); + menu_of(&mut harness); + choose(&mut harness, entry); + harness.run(); + assert_shows(&harness, after, entry); + } +} + +#[test] +fn the_menu_asks_the_window_for_what_to_paste() { + let mut harness = opened_at("ab|"); + menu_of(&mut harness); + harness.get_by(|node| node.author_id() == Some("editor-menu-paste")).click(); + let mut asked = false; + for _ in 0..4 { + harness.step(); + asked |= harness + .output() + .viewport_output + .values() + .any(|viewport| viewport.commands.contains(&egui::ViewportCommand::RequestPaste)); + } + assert!(asked); +} + +#[test] +fn the_menu_selects_the_whole_text_and_gives_it_the_keys_back() { + let mut harness = screen("one two"); + menu_of(&mut harness); + choose(&mut harness, "editor-menu-select-all"); harness.run(); + assert_eq!(harness.state().editor.buffer.selected_text(), "one two"); + let code = harness.get_by(|node| node.author_id() == Some("code")); + assert!(code.is_focused()); } #[test] -fn a_paste_and_a_cut_go_through_the_text() { +fn a_focused_editor_asks_for_the_input_method_at_its_caret() { let mut harness = screen("abc"); focus(&mut harness); - harness - .state_mut() - .editor - .buffer - .select(text::Selection { anchor: 0, head: 1 }); - harness.event(Event::Cut); - harness.run(); - assert_eq!(text(&harness), "bc"); - harness.event(Event::Paste("a".into())); - harness.run(); - assert_eq!(text(&harness), "abc"); + let ime = harness.output().platform_output.ime; + assert!(ime.is_some()); } #[test] @@ -222,9 +524,7 @@ fn a_long_text_lays_out_only_what_is_on_screen() { let mut harness = screen(&lines.join("\n")); focus(&mut harness); press(&mut harness, Modifiers::COMMAND, Key::End); - harness - .get_by(|node| node.author_id() == Some("code")) - .type_text("!"); + harness.get_by(|node| node.author_id() == Some("code")).type_text("!"); harness.run(); assert!(text(&harness).ends_with("line 19999 = 19999;!")); assert_eq!(harness.state().changed, [19_999]); @@ -247,13 +547,7 @@ fn wrapped_rows_hang_under_their_line_s_indent() { }; let mut galley = None; let _ = ctx.run_ui(egui::RawInput::default(), |ui| { - galley = Some(geometry::galley( - ui, - &harness.state().editor.buffer, - 0, - &frame, - None, - )); + galley = Some(geometry::galley(ui, &harness.state().editor.buffer, 0, &frame, None)); }); let galley = galley.unwrap(); assert!(galley.rows.len() > 1); @@ -278,11 +572,7 @@ fn budgets() { harness.run(); println!("{size} bytes: opened in {:?}", opened.elapsed()); focus(&mut harness); - harness - .state_mut() - .editor - .buffer - .move_to(text.len() / 2, false); + harness.state_mut().editor.buffer.move_to(text.len() / 2, false); harness.run(); let mut frames = Vec::new(); for _ in 0..50 { @@ -292,10 +582,7 @@ fn budgets() { frames.push(started.elapsed()); } frames.sort(); - println!( - "{size} bytes: typing p50 {:?}, p95 {:?}", - frames[25], frames[47] - ); + println!("{size} bytes: typing p50 {:?}, p95 {:?}", frames[25], frames[47]); } } @@ -307,27 +594,88 @@ fn a_wrapped_line_selected_whole_is_lit_on_each_of_its_rows() { let mut laid = None; let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| { let body = egui::FontId::proportional(font::BODY); - let galley = - ctx.fonts_mut(|fonts| fonts.layout(text.clone(), body, egui::Color32::WHITE, 120.0)); + let galley = ctx.fonts_mut(|fonts| fonts.layout(text.clone(), body, egui::Color32::WHITE, 120.0)); laid = Some(galley); }); output.textures_delta.clear(); let galley = laid.unwrap(); - assert!( - galley.rows.len() >= 3, - "wrapped: {} rows", - galley.rows.len() - ); + assert!(galley.rows.len() >= 3, "wrapped: {} rows", galley.rows.len()); let rects = selection_rects(&galley, 0..length, false, 4.0); assert_eq!(rects.len(), galley.rows.len()); for (row, rect) in galley.rows.iter().zip(&rects) { assert!(rect.width() > 1.0, "{rect:?}"); - assert!( - (rect.left() - row.rect().left()).abs() < 0.5, - "from its own start: {rect:?}" - ); + assert!((rect.left() - row.rect().left()).abs() < 0.5, "from its own start: {rect:?}"); assert!((rect.center().y - row.rect().center().y).abs() < 0.5); } } + +/// Where the character at `at` of a line is drawn, `part` of its width along. +fn point(harness: &Harness<'_, Screen>, line: &str, at: usize, part: f32) -> egui::Pos2 { + let found = harness.output().shapes.iter().find_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) if text.galley.text() == line => { + let side = |at| text.galley.pos_from_cursor(CCursor::new(at)).center(); + let across = side(at).lerp(side(at + 1), part); + Some(text.pos + across.to_vec2()) + } + _ => None, + }); + found.unwrap_or_else(|| panic!("{line:?} is painted")) +} + +/// The bench gives each release a frame of its own, a quarter of a second: egui's delay between +/// two clicks is stretched to count them as one gesture. +fn clicks(harness: &mut Harness<'_, Screen>, at: egui::Pos2, count: usize) { + harness + .ctx + .options_mut(|options| options.input_options.max_double_click_delay = 0.7); + // A second of frames first: no click before this gesture counts in it. + for _ in 0..4 { + harness.step(); + } + harness.event(Event::PointerMoved(at)); + harness.step(); + for _ in 0..count { + for pressed in [true, false] { + harness.event(Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }); + } + } + harness.run(); +} + +#[test] +fn a_double_click_takes_the_word_under_the_pointer() { + for (at, part, word) in [ + (5, 0.5, "beta"), + (4, 0.2, "beta"), + (4, 0.8, "beta"), + (7, 0.8, "beta"), + (0, 0.2, "foo"), + (3, 0.5, " "), + (8, 0.5, "+="), + (10, 0.8, "1"), + ] { + let mut harness = screen("line\nfoo beta+=1"); + harness.run(); + let pointed = point(&harness, "foo beta+=1", at, part); + clicks(&mut harness, pointed, 2); + assert_eq!(harness.state().editor.buffer.selected_text(), word, "{at} {part}"); + } +} + +#[test] +fn a_triple_click_takes_the_line() { + for (line, taken) in [("one", "one\n"), ("two", "two")] { + let mut harness = screen("one\ntwo"); + harness.run(); + let pointed = point(&harness, line, 1, 0.5); + clicks(&mut harness, pointed, 3); + assert_eq!(harness.state().editor.buffer.selected_text(), taken); + } +} diff --git a/crates/ui/src/widgets/empty.rs b/crates/ui/src/widgets/empty.rs index ed76269dc..a9ea3238d 100644 --- a/crates/ui/src/widgets/empty.rs +++ b/crates/ui/src/widgets/empty.rs @@ -31,22 +31,15 @@ pub fn empty_state( .sum::() - gap::CONTROLS; let height = galley.size().y - + if actions.is_empty() { - 0.0 - } else { - gap::GROUPS + super::MIN_TARGET + gap::CONTROLS - }; + + if actions.is_empty() { 0.0 } else { gap::GROUPS + super::MIN_TARGET + gap::CONTROLS }; let top = if room.height().is_finite() && room.height() < 4_000.0 { (room.center().y - height / 2.0).max(room.top()) } else { room.top() + gap::PAGE }; let column_rect = Rect::from_min_max(pos2(room.left(), top), pos2(room.right(), top + height)); - let mut column = ui.new_child( - UiBuilder::new() - .max_rect(column_rect) - .layout(Layout::top_down(Align::Center)), - ); + let mut column = + ui.new_child(UiBuilder::new().max_rect(column_rect).layout(Layout::top_down(Align::Center))); column.spacing_mut().item_spacing.y = gap::GROUPS; let (rect, said) = column.allocate_exact_size(galley.size(), Sense::hover()); said.widget_info(|| WidgetInfo::labeled(Role::Label, true, words)); @@ -56,24 +49,15 @@ pub fn empty_state( ui.allocate_rect(column_rect, Sense::hover()); return None; } - let (row_rect, _) = column.allocate_exact_size( - Vec2::new(row.max(0.0), super::MIN_TARGET + gap::CONTROLS), - Sense::hover(), - ); - let mut buttons = column.new_child( - UiBuilder::new() - .max_rect(row_rect) - .layout(Layout::left_to_right(Align::Center)), - ); + let (row_rect, _) = column + .allocate_exact_size(Vec2::new(row.max(0.0), super::MIN_TARGET + gap::CONTROLS), Sense::hover()); + let mut buttons = + column.new_child(UiBuilder::new().max_rect(row_rect).layout(Layout::left_to_right(Align::Center))); buttons.spacing_mut().item_spacing.x = gap::CONTROLS; let mut clicked = None; for (rank, action) in actions.iter().enumerate() { let button = Button::new(action.label, action.author_id); - let button = if action.primary { - button.kind(Kind::Filled) - } else { - button - }; + let button = if action.primary { button.kind(Kind::Filled) } else { button }; if button.show(&mut buttons).clicked() { clicked = Some(rank); } diff --git a/crates/ui/src/widgets/field.rs b/crates/ui/src/widgets/field.rs index 656d061bf..1478a0c54 100644 --- a/crates/ui/src/widgets/field.rs +++ b/crates/ui/src/widgets/field.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Margin, Rect, Response, Role, Sense, Stroke, - StrokeKind, TextEdit, Ui, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, FontId, Margin, Rect, Response, Role, Sense, Stroke, StrokeKind, + TextEdit, Ui, Vec2, WidgetInfo, }; use super::{address, interact}; @@ -12,10 +12,7 @@ use crate::theme::icons::{self, Icon}; use crate::theme::palette; /// The reference's `.input`: 9 × 11, an 8 px corner on `bg-1`, red when the value is refused. -#[expect( - clippy::struct_excessive_bools, - reason = "each is its own display choice" -)] +#[expect(clippy::struct_excessive_bools, reason = "each is its own display choice")] pub struct TextField<'a> { value: &'a mut String, name: &'a str, @@ -84,11 +81,7 @@ impl<'a> TextField<'a> { } else { (14.0, 8, gap::margin(gap::INSET, gap::CONTROLS)) }; - let family = if self.mono { - FontFamily::Monospace - } else { - FontFamily::Proportional - }; + let family = if self.mono { FontFamily::Monospace } else { FontFamily::Proportional }; let frame = egui::Frame::new() .fill(p.bg_1) .stroke(Stroke::new(1.0, edge)) @@ -101,9 +94,7 @@ impl<'a> TextField<'a> { .frame(egui::Frame::new()) .margin(Margin::ZERO) .password(self.password) - .hint_text( - egui::RichText::new(self.hint).font(FontId::new(size, family.clone())), - ) + .hint_text(egui::RichText::new(self.hint).font(FontId::new(size, family.clone()))) .text_color(p.text_0) .font(FontId::new(size, family)) .desired_width(f32::INFINITY), @@ -131,11 +122,7 @@ fn forget_undo(ctx: &egui::Context, id: egui::Id) { /// click. pub fn switch(ui: &mut Ui, label: &str, author_id: &str, on: &mut bool, enabled: bool) -> Response { let p = palette(ui.ctx()); - let sense = if enabled { - Sense::click() - } else { - Sense::hover() - }; + let sense = if enabled { Sense::click() } else { Sense::hover() }; let mut response = interact( ui, Vec2::new(34.0, 24.0), @@ -149,11 +136,8 @@ pub fn switch(ui: &mut Ui, label: &str, author_id: &str, on: &mut bool, enabled: response.mark_changed(); } let track = Rect::from_center_size(response.rect.center(), Vec2::new(34.0, 18.0)); - let (fill, knob) = if *on { - (p.amber_fill.gamma_multiply(0.35), p.amber_text) - } else { - (p.bg_3, p.text_2) - }; + let (fill, knob) = + if *on { (p.amber_fill.gamma_multiply(0.35), p.amber_text) } else { (p.bg_3, p.text_2) }; let (fill, knob) = (super::dimmed(fill, enabled), super::dimmed(knob, enabled)); ui.painter().rect( track, @@ -162,13 +146,8 @@ pub fn switch(ui: &mut Ui, label: &str, author_id: &str, on: &mut bool, enabled: Stroke::new(1.0, p.line_soft), StrokeKind::Inside, ); - let x = if *on { - track.right() - 9.0 - } else { - track.left() + 9.0 - }; - ui.painter() - .circle_filled(egui::pos2(x, track.center().y), 6.0, knob); + let x = if *on { track.right() - 9.0 } else { track.left() + 9.0 }; + ui.painter().circle_filled(egui::pos2(x, track.center().y), 6.0, knob); response } @@ -293,19 +272,11 @@ impl<'a> SearchField<'a> { if let Some((label, author_id)) = self.clear && !self.value.is_empty() { - cleared = super::IconButton::new(Icon::X, label, author_id) - .show(ui) - .clicked(); + cleared = super::IconButton::new(Icon::X, label, author_id).show(ui).clicked(); } if let Some(matched) = self.matched { - let galley = super::text( - ui, - matched, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let galley = + super::text(ui, matched, font::META, 400.0, FontFamily::Proportional, p.text_2); let (rect, count) = ui.allocate_exact_size(galley.size(), Sense::hover()); count.widget_info(|| WidgetInfo::labeled(Role::Label, true, matched)); address(ui, &count, self.matched_id); @@ -313,10 +284,7 @@ impl<'a> SearchField<'a> { } else if let Some(key) = self.key { super::Kbd(key).show(ui); } - Searched { - field: response, - cleared, - } + Searched { field: response, cleared } }) .inner }) @@ -326,25 +294,14 @@ impl<'a> SearchField<'a> { /// Room for what follows the field: the cross, then the count or the key. fn trailing_width(&self, ui: &Ui) -> f32 { let gap = ui.spacing().item_spacing.x; - let cross = if self.clear.is_some() && !self.value.is_empty() { - super::MIN_TARGET + gap - } else { - 0.0 - }; + let cross = + if self.clear.is_some() && !self.value.is_empty() { super::MIN_TARGET + gap } else { 0.0 }; let words = self.matched.or(self.key).unwrap_or_default(); - let family = if self.matched.is_some() { - FontFamily::Proportional - } else { - FontFamily::Monospace - }; + let family = if self.matched.is_some() { FontFamily::Proportional } else { FontFamily::Monospace }; let after = if words.is_empty() { 0.0 } else { - super::text(ui, words, font::META, 400.0, family, Color32::WHITE) - .size() - .x - + gap - + gap + super::text(ui, words, font::META, 400.0, family, Color32::WHITE).size().x + gap + gap }; cross + after } @@ -366,12 +323,7 @@ pub struct Checkbox<'a> { impl<'a> Checkbox<'a> { pub fn new(checked: &'a mut bool, label: &'a str, author_id: &'a str) -> Self { - Self { - checked, - label, - author_id, - enabled: true, - } + Self { checked, label, author_id, enabled: true } } #[must_use] @@ -385,11 +337,7 @@ impl<'a> Checkbox<'a> { let mut response = interact( ui, Vec2::splat(super::MIN_TARGET), - if enabled { - Sense::click() - } else { - Sense::hover() - }, + if enabled { Sense::click() } else { Sense::hover() }, self.author_id, || WidgetInfo::selected(Role::CheckBox, enabled, checked, label), CornerRadius::same(radius::TAG), @@ -400,11 +348,8 @@ impl<'a> Checkbox<'a> { } let p = palette(ui.ctx()); let tick = Rect::from_center_size(response.rect.center(), Vec2::splat(16.0)); - let (fill, edge) = if *self.checked { - (p.amber_fill, p.amber_edge) - } else { - (Color32::TRANSPARENT, p.line) - }; + let (fill, edge) = + if *self.checked { (p.amber_fill, p.amber_edge) } else { (Color32::TRANSPARENT, p.line) }; ui.painter().rect( tick, CornerRadius::same(radius::TAG), diff --git a/crates/ui/src/widgets/in_place.rs b/crates/ui/src/widgets/in_place.rs index 5681f6c7d..f377109ef 100644 --- a/crates/ui/src/widgets/in_place.rs +++ b/crates/ui/src/widgets/in_place.rs @@ -29,10 +29,7 @@ pub fn ask_in_place( return asked.clicked().then_some(InPlace::Ask); }; let mut pressed = None; - if Button::new(cancel, &format!("{author_id}-cancel")) - .show(ui) - .clicked() - { + if Button::new(cancel, &format!("{author_id}-cancel")).show(ui).clicked() { pressed = Some(InPlace::Cancel); } if Button::new(word, &format!("{author_id}-confirm")) @@ -42,9 +39,7 @@ pub fn ask_in_place( { pressed = Some(InPlace::Confirm); } - let question = egui::RichText::new(question) - .size(font::BODY) - .color(palette(ui.ctx()).text_1); + let question = egui::RichText::new(question).size(font::BODY).color(palette(ui.ctx()).text_1); let said = ui.add(egui::Label::new(question)); address(ui, &said, &format!("{author_id}-count")); pressed diff --git a/crates/ui/src/widgets/json_explorer/graph.rs b/crates/ui/src/widgets/json_explorer/graph.rs index 89341cd1b..ae6e75a9b 100644 --- a/crates/ui/src/widgets/json_explorer/graph.rs +++ b/crates/ui/src/widgets/json_explorer/graph.rs @@ -7,8 +7,8 @@ use crate::theme::tokens::{gap, radius}; use egui::epaint::CubicBezierShape; use egui::{ - Color32, CornerRadius, CursorIcon, FontFamily, Key, Modifiers, Pos2, Rect, Response, Role, - Sense, Stroke, StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2, + Color32, CornerRadius, CursorIcon, FontFamily, Key, Modifiers, Pos2, Rect, Response, Role, Sense, Stroke, + StrokeKind, Ui, Vec2, WidgetInfo, pos2, vec2, }; use engine::json::model::{JsonGraph, JsonKind, JsonNode, JsonView}; use i18n::{Language, keys}; @@ -37,10 +37,7 @@ struct Cursor { /// What the ground keeps between frames. #[derive(Debug, Default)] -#[expect( - clippy::struct_excessive_bools, - reason = "four asks of the next frame, each on its own" -)] +#[expect(clippy::struct_excessive_bools, reason = "four asks of the next frame, each on its own")] pub(super) struct Ground { /// `None` until moved: the start, which the size of the ground does not change. pan: Option, @@ -59,11 +56,11 @@ pub(super) struct Ground { } impl Ground { - fn zoom(&self) -> f32 { + pub(super) fn zoom(&self) -> f32 { self.zoom.unwrap_or(1.0) } - fn pan(&self) -> Vec2 { + pub(super) fn pan(&self) -> Vec2 { self.pan.unwrap_or(START) } @@ -80,14 +77,10 @@ impl Ground { } let found = selected.and_then(|path| find(graph, path)); self.cursor = match found { - Some(super::Found::Node(node)) => Some(Cursor { - node: node.path.clone(), - row: None, - }), - Some(super::Found::Row { node, index, .. }) => Some(Cursor { - node: node.path.clone(), - row: Some(index), - }), + Some(super::Found::Node(node)) => Some(Cursor { node: node.path.clone(), row: None }), + Some(super::Found::Row { node, index, .. }) => { + Some(Cursor { node: node.path.clone(), row: Some(index) }) + } None => self .cursor .take() @@ -97,18 +90,13 @@ impl Ground { fn zoom_by(&mut self, ground: Rect, step: i32) { let zoom = self.zoom(); - let at = SCALES - .iter() - .position(|scale| *scale >= zoom) - .unwrap_or(SCALES.len() - 1); - let next = at - .saturating_add_signed(step as isize) - .min(SCALES.len() - 1); + let at = SCALES.iter().position(|scale| *scale >= zoom).unwrap_or(SCALES.len() - 1); + let next = at.saturating_add_signed(step as isize).min(SCALES.len() - 1); self.zoom_to(ground, SCALES[next]); } /// Around the middle of the ground, which is what stays put under the eye. - fn zoom_to(&mut self, ground: Rect, scale: f32) { + pub(super) fn zoom_to(&mut self, ground: Rect, scale: f32) { let middle = ground.size() / 2.0; let ratio = scale / self.zoom(); self.pan = Some(middle - (middle - self.pan()) * ratio); @@ -138,10 +126,7 @@ impl Plane { fn rect(&self, node: &JsonNode, offset: Vec2) -> Rect { let (x, y) = (as_f32(node.x) + offset.x, as_f32(node.y) + offset.y); - Rect::from_min_max( - self.at(x, y), - self.at(x + as_f32(node.width), y + as_f32(node.height)), - ) + Rect::from_min_max(self.at(x, y), self.at(x + as_f32(node.width), y + as_f32(node.height))) } } @@ -162,16 +147,12 @@ pub(super) fn show( let rect = ui.max_rect(); let ground = widgets::region(ui, rect, "json-graph", Sense::click_and_drag()); ground.widget_info(|| { - WidgetInfo::labeled( - Role::Group, - true, - i18n::translate(language, keys::json::TREE, &[]), - ) + WidgetInfo::labeled(Role::Group, true, i18n::translate(language, keys::json::TREE, &[])) }); address(ui, &ground, "json-graph"); paint_ground(ui, rect); - let column = ui - .fonts_mut(|fonts| fonts.glyph_width(&egui::FontId::new(FONT, FontFamily::Monospace), '0')); + let column = + ui.fonts_mut(|fonts| fonts.glyph_width(&egui::FontId::new(FONT, FontFamily::Monospace), '0')); if std::mem::take(&mut explorer.ground.fit) { fit(&mut explorer.ground, graph, &explorer.offsets, rect, column); } @@ -189,11 +170,7 @@ pub(super) fn show( } else if ground.hovered() { ui.ctx().set_cursor_icon(CursorIcon::Grab); } - let plane = Plane { - origin: rect.min + explorer.ground.pan(), - column, - zoom: explorer.ground.zoom(), - }; + let plane = Plane { origin: rect.min + explorer.ground.pan(), column, zoom: explorer.ground.zoom() }; let painter = ui.painter_at(rect); let lit = lit(graph, &explorer.ground); edges(&painter, graph, explorer, &plane, &lit); @@ -203,12 +180,7 @@ pub(super) fn show( if !placed.intersects(rect) { continue; } - let drawn = Drawn { - ground: rect, - plane: &plane, - lit: &lit, - language, - }; + let drawn = Drawn { ground: rect, plane: &plane, lit: &lit, language }; if let Some(chosen) = draw_node(ui, &drawn, explorer, view, (node, placed)) { picked = Some(chosen); ground.request_focus(); @@ -231,6 +203,7 @@ pub(super) fn show( ground.request_focus(); explorer.ground.reveal = true; } + widgets::keep_arrows(ui, &ground); if std::mem::take(&mut explorer.ground.reveal) && let Some(target) = cursor_rect(explorer, graph, &plane) { @@ -271,19 +244,10 @@ fn lit(graph: &JsonGraph, ground: &Ground) -> Vec { let Some(node) = graph.nodes.iter().find(|node| node.path == cursor.node) else { return Vec::new(); }; - lineage(graph, node) - .into_iter() - .map(|node| node.id) - .collect() + lineage(graph, node).into_iter().map(|node| node.id).collect() } -fn edges( - painter: &egui::Painter, - graph: &JsonGraph, - explorer: &Explorer, - plane: &Plane, - lit: &[u32], -) { +fn edges(painter: &egui::Painter, graph: &JsonGraph, explorer: &Explorer, plane: &Plane, lit: &[u32]) { let p = palette(painter.ctx()); for node in &graph.nodes { let from = placed_offset(explorer, &node.path); @@ -300,12 +264,7 @@ fn edges( let lit = lit.contains(&node.id) && lit.contains(&child.id); let colour = if lit { p.amber_edge } else { p.line }; painter.add(CubicBezierShape::from_points_stroke( - [ - plane.at(x1, y1), - plane.at(x1 + bend, y1), - plane.at(x2 - bend, y2), - plane.at(x2, y2), - ], + [plane.at(x1, y1), plane.at(x1 + bend, y1), plane.at(x2 - bend, y2), plane.at(x2, y2)], false, Color32::TRANSPARENT, Stroke::new(1.6, colour), @@ -341,8 +300,7 @@ fn draw_node( let painter = ui.painter_at(placed.intersect(ground)); let dragged = explorer.ground.dragged.as_ref(); if dragged.is_some_and(|(path, _)| *path == node.path) { - ui.painter_at(ground) - .add(p.shadow_dropdown.as_shape(placed, corner)); + ui.painter_at(ground).add(p.shadow_dropdown.as_shape(placed, corner)); } painter.rect_filled(placed, corner, p.bg_1); @@ -358,27 +316,18 @@ fn draw_node( painter.hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); } if draw_row(ui, drawn, explorer, (node, index), rect) && explorer.ground.dragged.is_none() { - explorer.ground.cursor = Some(Cursor { - node: node.path.clone(), - row: Some(index), - }); + explorer.ground.cursor = Some(Cursor { node: node.path.clone(), row: Some(index) }); explorer.toggle(view, &row.path, row.opens, row.child.is_some()); picked = Some(row.path.clone()); } } if node.hidden_rows > 0 { let top = head.bottom() + line * as_f32(u32::try_from(node.rows.len()).unwrap_or(0)); - let words = i18n::translate( - drawn.language, - keys::json::HIDDEN_ROWS, - &[("count", node.hidden_rows.into())], - ); + let words = + i18n::translate(drawn.language, keys::json::HIDDEN_ROWS, &[("count", node.hidden_rows.into())]); let size = FONT * drawn.plane.zoom; let more = text(ui, &words, size, 400.0, FontFamily::Monospace, p.text_2); - let at = pos2( - head.left() + 10.0 * drawn.plane.zoom, - top + (line - more.size().y) / 2.0, - ); + let at = pos2(head.left() + 10.0 * drawn.plane.zoom, top + (line - more.size().y) / 2.0); painter.galley(at, more, p.text_2); } let current = is_cursor(&explorer.ground, node, None); @@ -421,17 +370,8 @@ fn draw_head( let current = is_cursor(&explorer.ground, node, None); let painter = ui.painter_at(head.intersect(drawn.ground)); let corner = round(9.0 * zoom); - let fill = if current { - p.amber_fill.gamma_multiply(0.14) - } else { - p.bg_2 - }; - let top_corners = CornerRadius { - nw: corner, - ne: corner, - sw: 0, - se: 0, - }; + let fill = if current { p.amber_fill.gamma_multiply(0.14) } else { p.bg_2 }; + let top_corners = CornerRadius { nw: corner, ne: corner, sw: 0, se: 0 }; painter.rect_filled(head, top_corners, fill); painter.hline(head.x_range(), head.bottom(), Stroke::new(1.0, p.line_soft)); let salt = (&node.path, "head"); @@ -440,42 +380,18 @@ fn draw_head( address(ui, &response, "json-node-head"); describe(ui, &response, &node.path, None); let pad = 10.0 * zoom; - let ink = if current || drawn.lit.contains(&node.id) { - p.amber_text - } else { - p.text_0 - }; + let ink = if current || drawn.lit.contains(&node.id) { p.amber_text } else { p.text_0 }; let size_words = format!("{} {}", braces(node.kind), node.size); - let size = text( - ui, - &size_words, - 10.0 * zoom, - 400.0, - FontFamily::Monospace, - p.text_2, - ); - let size_at = pos2( - head.right() - pad - size.size().x, - head.center().y - size.size().y / 2.0, - ); - let name = text( - ui, - &node.label, - FONT * zoom, - 700.0, - FontFamily::Monospace, - ink, - ); + let size = text(ui, &size_words, 10.0 * zoom, 400.0, FontFamily::Monospace, p.text_2); + let size_at = pos2(head.right() - pad - size.size().x, head.center().y - size.size().y / 2.0); + let name = text(ui, &node.label, FONT * zoom, 700.0, FontFamily::Monospace, ink); let name_at = pos2(head.left() + pad, head.center().y - name.size().y / 2.0); painter.galley(name_at, name, ink); painter.galley(size_at, size, p.text_2); if !response.clicked() || explorer.ground.dragged.is_some() { return None; } - explorer.ground.cursor = Some(Cursor { - node: node.path.clone(), - row: None, - }); + explorer.ground.cursor = Some(Cursor { node: node.path.clone(), row: None }); explorer.select(&node.path); Some(node.path.clone()) } @@ -513,65 +429,38 @@ fn draw_row( } let pad = 10.0 * zoom; let middle = |height: f32| rect.center().y - height / 2.0; - let key = text( - ui, - &row.key, - FONT * zoom, - 400.0, - FontFamily::Monospace, - p.text_1, - ); + let key = text(ui, &row.key, FONT * zoom, 400.0, FontFamily::Monospace, p.text_1); let left = rect.left() + pad + key.size().x + 8.0 * zoom; painter.galley(pos2(rect.left() + pad, middle(key.size().y)), key, p.text_1); let mut right = rect.right() - pad; if row.opens { let chevron = if open { "‹" } else { "›" }; - let mark = text( - ui, - chevron, - FONT * zoom, - 400.0, - FontFamily::Monospace, - p.text_2, - ); + let mark = text(ui, chevron, FONT * zoom, 400.0, FontFamily::Monospace, p.text_2); right -= mark.size().x; painter.galley(pos2(right, middle(mark.size().y)), mark, p.text_2); right -= 8.0 * zoom; } let ink = kind_colour(p, row.kind); - let value = text( - ui, - &row.value, - FONT * zoom, - 400.0, - FontFamily::Monospace, - ink, - ); + let value = text(ui, &row.value, FONT * zoom, 400.0, FontFamily::Monospace, ink); let x = (right - value.size().x).max(left); let room = Rect::from_x_y_ranges(left..=right.max(left), rect.y_range()); - painter - .with_clip_rect(room.intersect(painter.clip_rect())) - .galley(pos2(x, middle(value.size().y)), value, ink); + painter.with_clip_rect(room.intersect(painter.clip_rect())).galley( + pos2(x, middle(value.size().y)), + value, + ink, + ); response.clicked() } fn round(value: f32) -> u8 { // A corner of a few points, never past a byte. - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "clamped first" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "clamped first")] let rounded = value.clamp(0.0, 255.0).round() as u8; rounded } fn braces(kind: JsonKind) -> &'static str { - if kind == JsonKind::Object { - "{ }" - } else { - "[ ]" - } + if kind == JsonKind::Object { "{ }" } else { "[ ]" } } /// The path, which a test and the e2e driver find an entry by — no translation touches it — and @@ -589,11 +478,7 @@ pub(super) fn describe(ui: &Ui, response: &Response, path: &str, open: Option Option< let node = graph.nodes.iter().find(|node| node.path == cursor.node)?; let placed = plane.rect(node, placed_offset(explorer, &node.path)); let line = ROW_PX * plane.zoom; - let row = cursor - .row - .map_or(0.0, |row| as_f32(u32::try_from(row + 1).unwrap_or(0))); - Some(Rect::from_min_size( - placed.min + vec2(0.0, row * line), - vec2(placed.width(), line), - )) + let row = cursor.row.map_or(0.0, |row| as_f32(u32::try_from(row + 1).unwrap_or(0))); + Some(Rect::from_min_size(placed.min + vec2(0.0, row * line), vec2(placed.width(), line))) } /// Pans just enough to bring the cursor inside the ground. @@ -758,21 +621,15 @@ fn keys_of(ui: &Ui, explorer: &mut Explorer, view: &JsonView, escaped: bool) -> } let Some(cursor) = explorer.ground.cursor.clone() else { let arrow = ui.input(|input| { - [ - Key::ArrowDown, - Key::ArrowUp, - Key::ArrowLeft, - Key::ArrowRight, - ] - .iter() - .any(|key| input.key_pressed(*key)) + [Key::ArrowDown, Key::ArrowUp, Key::ArrowLeft, Key::ArrowRight] + .iter() + .any(|key| input.key_pressed(*key)) }); let root = graph.nodes.first()?; return arrow.then(|| move_to(explorer, root, None)); }; let node = graph.nodes.iter().find(|node| node.path == cursor.node)?; - let pressed = - |modifiers: Modifiers, key: Key| ui.input_mut(|input| input.consume_key(modifiers, key)); + let pressed = |modifiers: Modifiers, key: Key| ui.input_mut(|input| input.consume_key(modifiers, key)); if escaped { if cursor.row.is_none() && node.parent.is_none() { return None; @@ -787,11 +644,7 @@ fn keys_of(ui: &Ui, explorer: &mut Explorer, view: &JsonView, escaped: bool) -> (Key::ArrowDown, vec2(0.0, NUDGE.y)), ] { if pressed(Modifiers::ALT, key) { - let from = explorer - .offsets - .get(&node.path) - .copied() - .unwrap_or(Vec2::ZERO); + let from = explorer.offsets.get(&node.path).copied().unwrap_or(Vec2::ZERO); explorer.move_node(&node.path, from + step); explorer.ground.reveal = true; return None; @@ -834,10 +687,7 @@ fn keys_of(ui: &Ui, explorer: &mut Explorer, view: &JsonView, escaped: bool) -> } fn move_to(explorer: &mut Explorer, node: &JsonNode, row: Option) -> String { - explorer.ground.cursor = Some(Cursor { - node: node.path.clone(), - row, - }); + explorer.ground.cursor = Some(Cursor { node: node.path.clone(), row }); let path = row .and_then(|at| node.rows.get(at)) .map_or_else(|| node.path.clone(), |row| row.path.clone()); @@ -846,12 +696,7 @@ fn move_to(explorer: &mut Explorer, node: &JsonNode, row: Option) -> Stri } /// From a row to its header, from a header to the row that opened it. -fn go_up( - explorer: &mut Explorer, - graph: &JsonGraph, - node: &JsonNode, - row: Option, -) -> Option { +fn go_up(explorer: &mut Explorer, graph: &JsonGraph, node: &JsonNode, row: Option) -> Option { if row.is_some() { return Some(move_to(explorer, node, None)); } diff --git a/crates/ui/src/widgets/json_explorer/mod.rs b/crates/ui/src/widgets/json_explorer/mod.rs index d48d2b0ae..11048bc1b 100644 --- a/crates/ui/src/widgets/json_explorer/mod.rs +++ b/crates/ui/src/widgets/json_explorer/mod.rs @@ -12,8 +12,8 @@ use crate::theme::tokens::{font, gap, radius}; use std::collections::HashMap; use egui::{ - Align, Color32, CornerRadius, FontFamily, Key, Layout, Modifiers, Rect, Role, Sense, Stroke, - StrokeKind, Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2, + Align, Color32, CornerRadius, FontFamily, Key, Layout, Modifiers, Rect, Role, Sense, Stroke, StrokeKind, + Ui, UiBuilder, Vec2, WidgetInfo, pos2, vec2, }; use engine::json::model::{JsonKind, JsonOpening, JsonQuery, JsonView}; use engine::json::parse::{JsonErrorReason, Span}; @@ -84,12 +84,7 @@ impl Default for Explorer { impl Explorer { /// What the core is asked of `text`. pub fn query(&self, text: String, format: StructureFormat) -> JsonQuery { - JsonQuery { - text, - format, - search: self.searched.trim().to_owned(), - opening: self.opening.clone(), - } + JsonQuery { text, format, search: self.searched.trim().to_owned(), opening: self.opening.clone() } } /// The selection while the view draws it; folded away, the nearest of what held it. @@ -119,10 +114,7 @@ impl Explorer { } else { paths.push(path.to_owned()); } - self.opening = JsonOpening::Paths { - paths, - reveal: None, - }; + self.opening = JsonOpening::Paths { paths, reveal: None }; } fn open_all(&mut self) { @@ -131,14 +123,8 @@ impl Explorer { /// Only the root open, which the core keeps open whatever is asked. fn collapse_all(&mut self, view: &JsonView) { - self.trail = self - .selected_path(view) - .map(|path| trail_of(view, &path)) - .unwrap_or_default(); - self.opening = JsonOpening::Paths { - paths: Vec::new(), - reveal: None, - }; + self.trail = self.selected_path(view).map(|path| trail_of(view, &path)).unwrap_or_default(); + self.opening = JsonOpening::Paths { paths: Vec::new(), reveal: None }; } /// To the next match or the previous one, opening what it sits in. @@ -147,7 +133,9 @@ impl Explorer { if count == 0 { return None; } - let index = match (self.match_index, forward) { + // Past the matches once the document lost some: from the start again. + let current = self.match_index.filter(|at| *at < count); + let index = match (current, forward) { (None, true) => 0, (None, false) => count - 1, (Some(at), true) => (at + 1) % count, @@ -156,10 +144,7 @@ impl Explorer { let path = view.matches[index].clone(); self.match_index = Some(index); self.select(&path); - self.opening = JsonOpening::Paths { - paths: open_paths(view), - reveal: Some(path.clone()), - }; + self.opening = JsonOpening::Paths { paths: open_paths(view), reveal: Some(path.clone()) }; self.ground.reveal = true; self.tree.reveal = true; Some(path) @@ -188,11 +173,7 @@ impl Explorer { } fn open_paths(view: &JsonView) -> Vec { - view.graph - .nodes - .iter() - .map(|node| node.path.clone()) - .collect() + view.graph.nodes.iter().map(|node| node.path.clone()).collect() } /// Shift with an arrow, on the graph or the tree: everything opens, or folds to the root. @@ -305,18 +286,14 @@ fn selection(explorer: &Explorer, view: &JsonView) -> Option { span: row.span, text: row.text.clone(), }), - None => view - .tree - .iter() - .find(|line| line.path == path) - .map(|line| Selected { - path: line.path.clone(), - kind: line.kind, - size: line.size, - preview: line.value.clone(), - span: line.span, - text: line.text.clone(), - }), + None => view.tree.iter().find(|line| line.path == path).map(|line| Selected { + path: line.path.clone(), + kind: line.kind, + size: line.size, + preview: line.value.clone(), + span: line.span, + text: line.text.clone(), + }), } } @@ -383,8 +360,7 @@ impl<'a> ExplorerView<'a> { let mut output = Output::default(); let now = ui.input(|input| input.time); if let Some(wait) = self.explorer.send_search(now) { - ui.ctx() - .request_repaint_after(std::time::Duration::from_secs_f64(wait)); + ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(wait)); } let whole = ui.max_rect(); let wide = whole.width() >= WIDE_FROM; @@ -396,11 +372,7 @@ impl<'a> ExplorerView<'a> { Rect::from_min_max(pos2(split, whole.top()), whole.max), ) } else { - let room = if selected.is_some() { - NARROW_ASIDE - } else { - 0.0 - }; + let room = if selected.is_some() { NARROW_ASIDE } else { 0.0 }; let split = whole.bottom() - room; ( Rect::from_min_max(whole.min, pos2(whole.right(), split)), @@ -433,8 +405,7 @@ impl<'a> ExplorerView<'a> { } else { rect }; - let mut surface_ui = - ui.new_child(UiBuilder::new().id_salt("json-surface").max_rect(surface)); + let mut surface_ui = ui.new_child(UiBuilder::new().id_salt("json-surface").max_rect(surface)); let picked = match self.mode { Mode::Graph => graph::show(&mut surface_ui, self.explorer, self.view, self.language), Mode::Tree => tree::show(&mut surface_ui, self.explorer, self.view, self.language), @@ -476,11 +447,7 @@ impl<'a> ExplorerView<'a> { .layout(Layout::top_down(Align::Center)), ); inner.add_space((rect.height() / 2.0 - 40.0).max(0.0)); - let label = inner.label( - egui::RichText::new(&said) - .size(font::READING) - .color(p.text_1), - ); + let label = inner.label(egui::RichText::new(&said).size(font::READING).color(p.text_1)); label.widget_info(|| WidgetInfo::labeled(Role::Status, true, &said)); address(&inner, &label, "json-invalid"); inner.add_space(gap::GROUPS); @@ -489,19 +456,14 @@ impl<'a> ExplorerView<'a> { .show(&mut inner) .clicked() { - output.show_in_code = Some(Span { - start: error.offset, - end: error.offset, - }); + output.show_in_code = Some(Span { start: error.offset, end: error.offset }); } } /// The search and the folding, over the surface's top-left corner. fn tools(&mut self, ui: &mut Ui, surface: Rect, output: &mut Output) { - let at = Rect::from_min_size( - surface.min + vec2(16.0, 12.0), - vec2(surface.width() - 32.0, TOOL_HEIGHT), - ); + let at = + Rect::from_min_size(surface.min + vec2(16.0, 12.0), vec2(surface.width() - 32.0, TOOL_HEIGHT)); let mut row = ui.new_child( UiBuilder::new() .id_salt("json-tools") @@ -513,7 +475,8 @@ impl<'a> ExplorerView<'a> { let name = self.tr(keys::json::SEARCH); let hint = self.tr(keys::json::SEARCH_PLACEHOLDER); let count = self.view.match_count; - let matched = match self.explorer.match_index { + let found = self.view.matches.len(); + let matched = match self.explorer.match_index.filter(|at| *at < found) { None => count.to_string(), Some(at) => format!("{} / {count}", at + 1), }; @@ -531,37 +494,28 @@ impl<'a> ExplorerView<'a> { } if field.lost_focus() && row.input(|input| input.key_pressed(Key::Enter)) { let back = row.input(|input| input.modifiers.shift); - output.chosen = self - .explorer - .step(self.view, !back) - .or(output.chosen.take()); + output.chosen = self.explorer.step(self.view, !back).or(output.chosen.take()); field.request_focus(); } - if field.has_focus() + // egui lets go on Escape before it is read. + if field.lost_focus() && searching && row.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)) { self.explorer.search.clear(); self.explorer.search_due = Some(row.input(|input| input.time)); + field.request_focus(); } if searching { - if IconButton::new( - Icon::ArrowUp, - &self.tr(keys::json::PREVIOUS_MATCH), - "json-match-previous", - ) - .show(&mut row) - .clicked() + if IconButton::new(Icon::ArrowUp, &self.tr(keys::json::PREVIOUS_MATCH), "json-match-previous") + .show(&mut row) + .clicked() { output.chosen = self.explorer.step(self.view, false); } - if IconButton::new( - Icon::ArrowDown, - &self.tr(keys::json::NEXT_MATCH), - "json-match-next", - ) - .show(&mut row) - .clicked() + if IconButton::new(Icon::ArrowDown, &self.tr(keys::json::NEXT_MATCH), "json-match-next") + .show(&mut row) + .clicked() { output.chosen = self.explorer.step(self.view, true); } @@ -570,15 +524,12 @@ impl<'a> ExplorerView<'a> { if super::tooltip(open, &self.tr(keys::json::OPEN_ALL_KEYS)).clicked() { self.explorer.open_all(); } - let collapse = - Button::new(&self.tr(keys::json::COLLAPSE_ALL), "json-collapse-all").show(&mut row); + let collapse = Button::new(&self.tr(keys::json::COLLAPSE_ALL), "json-collapse-all").show(&mut row); if super::tooltip(collapse, &self.tr(keys::json::COLLAPSE_ALL_KEYS)).clicked() { self.explorer.collapse_all(self.view); } if self.mode == Mode::Graph - && Button::new(&self.tr(keys::json::FIT), "json-fit") - .show(&mut row) - .clicked() + && Button::new(&self.tr(keys::json::FIT), "json-fit").show(&mut row).clicked() { self.explorer.ground.fit(); } @@ -588,16 +539,10 @@ impl<'a> ExplorerView<'a> { let p = palette(ui.ctx()); let words = self.tr(keys::json::FOLDED); let show = self.tr(keys::json::SHOW_TREE); - let width = text( - ui, - &words, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ) - .size() - .x + Button::width(ui, &show) + let width = text(ui, &words, font::LABEL, 400.0, FontFamily::Proportional, p.text_1) + .size() + .x + + Button::width(ui, &show) + 40.0; let at = Rect::from_center_size( pos2(surface.center().x, surface.bottom() - 56.0 - 20.0), @@ -617,16 +562,9 @@ impl<'a> ExplorerView<'a> { .layout(Layout::left_to_right(Align::Center)), ); inner.spacing_mut().item_spacing.x = gap::GROUPS; - let said = inner.label( - egui::RichText::new(&words) - .size(font::LABEL) - .color(p.text_1), - ); + let said = inner.label(egui::RichText::new(&words).size(font::LABEL).color(p.text_1)); address(&inner, &said, "json-folded"); - if Button::new(&show, "json-show-tree") - .show(&mut inner) - .clicked() - { + if Button::new(&show, "json-show-tree").show(&mut inner).clicked() { output.tree_proposed = true; } } @@ -634,13 +572,9 @@ impl<'a> ExplorerView<'a> { fn crumbs(&mut self, ui: &mut Ui, bar: Rect, output: &mut Output) { let p = palette(ui.ctx()); ui.painter().rect_filled(bar, CornerRadius::ZERO, p.bg_1); - ui.painter() - .hline(bar.x_range(), bar.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(bar.x_range(), bar.top(), Stroke::new(1.0, p.line_soft)); let graph = &self.view.graph; - let found = self - .explorer - .selected_path(self.view) - .and_then(|path| find(graph, &path)); + let found = self.explorer.selected_path(self.view).and_then(|path| find(graph, &path)); let Some(node) = found.map(Found::node).or_else(|| graph.nodes.first()) else { return; }; @@ -665,23 +599,14 @@ impl<'a> ExplorerView<'a> { address(&row, &response, "json-crumbs"); let last = chain.len() - 1; for (index, (label, path)) in chain.iter().enumerate() { - let ink = if index == last { - p.amber_text - } else { - p.text_2 - }; + let ink = if index == last { p.amber_text } else { p.text_2 }; let galley = text(&row, label, font::LABEL, 400.0, FontFamily::Monospace, ink); - let (rect, crumb) = row.allocate_exact_size( - galley.size().max(vec2(0.0, super::MIN_TARGET)), - Sense::click(), - ); + let (rect, crumb) = + row.allocate_exact_size(galley.size().max(vec2(0.0, super::MIN_TARGET)), Sense::click()); crumb.widget_info(|| WidgetInfo::labeled(Role::Link, true, *label)); let ink = if crumb.hovered() { p.text_0 } else { ink }; - row.painter().galley( - pos2(rect.left(), rect.center().y - galley.size().y / 2.0), - galley, - ink, - ); + row.painter() + .galley(pos2(rect.left(), rect.center().y - galley.size().y / 2.0), galley, ink); if crumb.clicked() { self.explorer.select(path); output.chosen = Some((*path).to_owned()); @@ -697,11 +622,9 @@ impl<'a> ExplorerView<'a> { let rect = ui.max_rect(); ui.painter().rect_filled(rect, CornerRadius::ZERO, p.bg_1); if wide { - ui.painter() - .vline(rect.left(), rect.y_range(), Stroke::new(1.0, p.line_soft)); + ui.painter().vline(rect.left(), rect.y_range(), Stroke::new(1.0, p.line_soft)); } else { - ui.painter() - .hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); + ui.painter().hline(rect.x_range(), rect.top(), Stroke::new(1.0, p.line_soft)); } let mut inner = ui.new_child( UiBuilder::new() @@ -713,17 +636,15 @@ impl<'a> ExplorerView<'a> { let label = self.tr(keys::json::SELECTION_LABEL); response.widget_info(|| WidgetInfo::labeled(Role::Group, true, &label)); address(&inner, &response, "json-selection"); - egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .show(&mut inner, |ui| { - ui.spacing_mut().item_spacing.y = gap::INSET; - if let Some(selected) = selected { - self.selected(ui, wide, selected, output); - } - if wide { - self.document(ui); - } - }); + egui::ScrollArea::vertical().auto_shrink([false, false]).show(&mut inner, |ui| { + ui.spacing_mut().item_spacing.y = gap::INSET; + if let Some(selected) = selected { + self.selected(ui, wide, selected, output); + } + if wide { + self.document(ui); + } + }); } fn selected(&self, ui: &mut Ui, wide: bool, selected: &Selected, output: &mut Output) { @@ -735,10 +656,7 @@ impl<'a> ExplorerView<'a> { .fill(p.bg_0) .stroke(Stroke::new(1.0, p.line)) .corner_radius(CornerRadius::same(radius::CONTROL)) - .inner_margin(gap::margin( - gap::INSET, - if wide { gap::CONTROLS } else { gap::SNUG }, - )) + .inner_margin(gap::margin(gap::INSET, if wide { gap::CONTROLS } else { gap::SNUG })) .show(ui, |ui| { ui.set_width(ui.available_width()); let path = ui.add( @@ -763,11 +681,8 @@ impl<'a> ExplorerView<'a> { { ui.ctx().copy_text(selected.path.clone()); } - let kind = i18n::translate( - self.language, - kind_words(selected.kind), - &[("count", selected.size.into())], - ); + let kind = + i18n::translate(self.language, kind_words(selected.kind), &[("count", selected.size.into())]); let said = ui.label(egui::RichText::new(kind).size(font::BODY).color(p.text_1)); address(ui, &said, "json-selected-kind"); let previewed = ui.add( @@ -791,10 +706,7 @@ impl<'a> ExplorerView<'a> { { ui.ctx().copy_text(selected.path.clone()); } - if Button::new(©_value, "json-copy-value") - .show(ui) - .clicked() - { + if Button::new(©_value, "json-copy-value").show(ui).clicked() { let value = selected .text .clone() @@ -805,20 +717,15 @@ impl<'a> ExplorerView<'a> { output.show_in_code = Some(selected.span); } if self.extractable - && Button::new(&self.tr(keys::json::EXTRACT), "json-extract") - .show(ui) - .clicked() + && Button::new(&self.tr(keys::json::EXTRACT), "json-extract").show(ui).clicked() { output.extract = Some(selected.path.clone()); } }); if wide { ui.add_space(gap::TIGHT); - ui.painter().hline( - ui.max_rect().x_range(), - ui.cursor().top(), - Stroke::new(1.0, p.line_soft), - ); + ui.painter() + .hline(ui.max_rect().x_range(), ui.cursor().top(), Stroke::new(1.0, p.line_soft)); } } @@ -848,14 +755,9 @@ impl<'a> ExplorerView<'a> { }); } }); - let said: Vec = rows - .iter() - .map(|(name, value)| format!("{name} {value}")) - .collect(); + let said: Vec = rows.iter().map(|(name, value)| format!("{name} {value}")).collect(); let said = said.join(" · "); - figures - .response - .widget_info(|| WidgetInfo::labeled(Role::List, true, &said)); + figures.response.widget_info(|| WidgetInfo::labeled(Role::List, true, &said)); address(ui, &figures.response, "json-stats"); for notice in &self.view.notices { let words = match notice { @@ -872,12 +774,7 @@ impl<'a> ExplorerView<'a> { if let Some(key) = format_note { note(ui, &self.tr(key), p.text_2, "json-format-note"); } - note( - ui, - &self.tr(keys::json::LIMIT_NOTE), - p.text_2, - "json-limit-note", - ); + note(ui, &self.tr(keys::json::LIMIT_NOTE), p.text_2, "json-limit-note"); } } @@ -893,8 +790,7 @@ fn title(ui: &mut Ui, words: &str) { } fn note(ui: &mut Ui, words: &str, colour: Color32, author_id: &str) { - let said = - ui.add(egui::Label::new(egui::RichText::new(words).size(font::LABEL).color(colour)).wrap()); + let said = ui.add(egui::Label::new(egui::RichText::new(words).size(font::LABEL).color(colour)).wrap()); address(ui, &said, author_id); } @@ -914,3 +810,5 @@ fn size_words(bytes: u32, language: Language) -> String { #[cfg(test)] mod tests; +#[cfg(test)] +mod view_tests; diff --git a/crates/ui/src/widgets/json_explorer/reads.rs b/crates/ui/src/widgets/json_explorer/reads.rs index f7fb70d36..7889844d6 100644 --- a/crates/ui/src/widgets/json_explorer/reads.rs +++ b/crates/ui/src/widgets/json_explorer/reads.rs @@ -8,11 +8,7 @@ use engine::json::parse::Span; #[derive(Debug, Clone, Copy)] pub(super) enum Found<'a> { Node(&'a JsonNode), - Row { - node: &'a JsonNode, - row: &'a JsonRow, - index: usize, - }, + Row { node: &'a JsonNode, row: &'a JsonRow, index: usize }, } impl<'a> Found<'a> { @@ -29,11 +25,7 @@ pub(super) fn find<'a>(graph: &'a JsonGraph, path: &str) -> Option> { } graph.nodes.iter().find_map(|node| { let index = node.rows.iter().position(|row| row.path == path)?; - Some(Found::Row { - node, - row: &node.rows[index], - index, - }) + Some(Found::Row { node, row: &node.rows[index], index }) }) } @@ -106,11 +98,7 @@ pub(super) fn preview(node: &JsonNode) -> String { JsonKind::Array => "[ … ]", _ => row.value.as_str(), }; - if object { - format!(" {}: {value}", quoted(&row.key)) - } else { - format!(" {value}") - } + if object { format!(" {}: {value}", quoted(&row.key)) } else { format!(" {value}") } }) .collect(); if node.hidden_rows > 0 { @@ -133,11 +121,7 @@ pub fn span_of(view: &JsonView, path: &str) -> Option { match find(&view.graph, path) { Some(Found::Node(node)) => Some(node.span), Some(Found::Row { row, .. }) => Some(row.span), - None => view - .tree - .iter() - .find(|line| line.path == path) - .map(|line| line.span), + None => view.tree.iter().find(|line| line.path == path).map(|line| line.span), } } diff --git a/crates/ui/src/widgets/json_explorer/tests.rs b/crates/ui/src/widgets/json_explorer/tests.rs index a59646853..ac1e47c25 100644 --- a/crates/ui/src/widgets/json_explorer/tests.rs +++ b/crates/ui/src/widgets/json_explorer/tests.rs @@ -45,10 +45,7 @@ fn the_innermost_entry_holds_the_caret() { let view = view(EVENT, JsonOpening::All); let at = EVENT.find("Pro").unwrap(); let offset = u32::try_from(EVENT[..at].encode_utf16().count()).unwrap(); - assert_eq!( - entry_at(&view, offset), - Some("$.data.object.lines[0].description") - ); + assert_eq!(entry_at(&view, offset), Some("$.data.object.lines[0].description")); let span = span_of(&view, "$.data.object.lines[0].description").unwrap(); assert_eq!(utf16_slice(EVENT, span), "\"Pro · mensuel\""); } @@ -63,16 +60,8 @@ fn a_span_is_read_back_in_utf16_units_past_a_wide_character() { #[test] fn the_preview_shows_one_level_its_containers_folded() { let view = view(EVENT, JsonOpening::All); - let data = view - .graph - .nodes - .iter() - .find(|node| node.path == "$.data.object") - .unwrap(); - assert_eq!( - preview(data), - "{\n \"amount\": 4900,\n \"lines\": [ … ]\n}" - ); + let data = view.graph.nodes.iter().find(|node| node.path == "$.data.object").unwrap(); + assert_eq!(preview(data), "{\n \"amount\": 4900,\n \"lines\": [ … ]\n}"); } #[test] @@ -81,18 +70,9 @@ fn folded_away_the_selection_falls_back_to_what_held_it_and_comes_back() { let mut explorer = Explorer::default(); explorer.select("$.data.object.amount"); explorer.collapse_all(&open); - let folded = view( - EVENT, - JsonOpening::Paths { - paths: Vec::new(), - reveal: None, - }, - ); + let folded = view(EVENT, JsonOpening::Paths { paths: Vec::new(), reveal: None }); assert_eq!(explorer.selected_path(&folded).as_deref(), Some("$.data")); - assert_eq!( - explorer.selected_path(&open).as_deref(), - Some("$.data.object.amount") - ); + assert_eq!(explorer.selected_path(&open).as_deref(), Some("$.data.object.amount")); } #[test] @@ -112,3 +92,23 @@ fn stepping_to_a_match_reveals_it_and_wraps_around() { JsonOpening::Paths { reveal: Some(path), .. } if path == "$.a" )); } + +#[test] +fn the_count_starts_over_when_the_document_lost_the_match_it_was_on() { + let found = |text: &str| { + explore(&JsonQuery { + text: text.to_owned(), + format: StructureFormat::Json, + search: "x".to_owned(), + opening: JsonOpening::All, + }) + }; + let mut explorer = Explorer::default(); + let before = found(r#"{"a":"x","b":"x","c":"x"}"#); + for path in ["$.a", "$.b", "$.c"] { + assert_eq!(explorer.step(&before, true).as_deref(), Some(path)); + } + let after = found(r#"{"a":"x","b":"x"}"#); + + assert_eq!(explorer.step(&after, true).as_deref(), Some("$.a")); +} diff --git a/crates/ui/src/widgets/json_explorer/tree.rs b/crates/ui/src/widgets/json_explorer/tree.rs index a177f4b7a..909755f69 100644 --- a/crates/ui/src/widgets/json_explorer/tree.rs +++ b/crates/ui/src/widgets/json_explorer/tree.rs @@ -3,9 +3,7 @@ //! tab stop; the arrows walk it, → and ← open and close. use crate::theme::tokens::font; -use egui::{ - CornerRadius, FontFamily, Key, Modifiers, Role, Sense, Ui, Vec2, WidgetInfo, pos2, vec2, -}; +use egui::{CornerRadius, FontFamily, Key, Modifiers, Role, Sense, Ui, Vec2, WidgetInfo, pos2, vec2}; use engine::json::model::{JsonKind, JsonLine, JsonView}; use i18n::{Language, keys}; @@ -40,18 +38,11 @@ pub(super) fn show( ) -> Option { let lines = &view.tree; let selected = explorer.selected_path(view); - let cursor = lines - .iter() - .position(|line| Some(&line.path) == selected.as_ref()) - .unwrap_or(0); + let cursor = lines.iter().position(|line| Some(&line.path) == selected.as_ref()).unwrap_or(0); let rect = ui.max_rect(); let list = widgets::region(ui, rect, "json-tree", Sense::focusable_noninteractive()); list.widget_info(|| { - WidgetInfo::labeled( - Role::Tree, - true, - i18n::translate(language, keys::json::TREE, &[]), - ) + WidgetInfo::labeled(Role::Tree, true, i18n::translate(language, keys::json::TREE, &[])) }); address(ui, &list, "json-tree"); let p = palette(ui.ctx()); @@ -75,21 +66,14 @@ pub(super) fn show( .id_salt("json-tree-rows") .max_rect(rect.with_min_y(rect.top() + TOOLS_ROOM)), ); - let shown = area.show_rows( - &mut inner, - LINE, - lines.len() + usize::from(view.tree_truncated), - |ui, range| { - ui.spacing_mut().item_spacing = Vec2::ZERO; + // The rows are counted with the spacing around the list, and drawn with the one inside it. + inner.spacing_mut().item_spacing = Vec2::ZERO; + let shown = + area.show_rows(&mut inner, LINE, lines.len() + usize::from(view.tree_truncated), |ui, range| { for index in range { let Some(line) = lines.get(index) else { let note = i18n::translate(language, keys::json::TREE_TRUNCATED, &[]); - ui.label( - egui::RichText::new(note) - .size(font::LABEL) - .italics() - .color(p.text_2), - ); + ui.label(egui::RichText::new(note).size(font::LABEL).italics().color(p.text_2)); continue; }; let response = draw_line(ui, line, index == cursor); @@ -98,8 +82,7 @@ pub(super) fn show( list.request_focus(); } } - }, - ); + }); explorer.tree.offset = shown.state.clamped_offset().y; explorer.tree.height = shown.inner_rect.height(); @@ -113,6 +96,7 @@ pub(super) fn show( list.request_focus(); explorer.tree.reveal = true; } + widgets::keep_arrows(ui, &list); picked } @@ -156,20 +140,14 @@ fn draw_line(ui: &mut Ui, line: &JsonLine, current: bool) -> egui::Response { let mut paint = |words: &str, colour, gap: f32| { let galley = text(ui, words, FONT, 400.0, FontFamily::Monospace, colour); let width = galley.size().x; - ui.painter().with_clip_rect(rect).galley( - pos2(x, middle - galley.size().y / 2.0), - galley, - colour, - ); + ui.painter() + .with_clip_rect(rect) + .galley(pos2(x, middle - galley.size().y / 2.0), galley, colour); x += width + gap; }; paint(&line.key, p.text_1, 10.0); if line.opens { - let braces = if line.kind == JsonKind::Object { - "{ }" - } else { - "[ ]" - }; + let braces = if line.kind == JsonKind::Object { "{ }" } else { "[ ]" }; paint(&format!("{braces} {}", line.size), p.text_2, 0.0); } else { paint(&line.value, kind_colour(p, line.kind), 0.0); @@ -221,8 +199,5 @@ fn keys_of(ui: &Ui, explorer: &mut Explorer, view: &JsonView, cursor: usize) -> fn parent_of(lines: &[JsonLine], index: usize) -> usize { let depth = lines[index].depth; - lines[..index] - .iter() - .rposition(|line| line.depth < depth) - .unwrap_or(index) + lines[..index].iter().rposition(|line| line.depth < depth).unwrap_or(index) } diff --git a/crates/ui/src/widgets/json_explorer/view_tests.rs b/crates/ui/src/widgets/json_explorer/view_tests.rs new file mode 100644 index 000000000..81cc6944c --- /dev/null +++ b/crates/ui/src/widgets/json_explorer/view_tests.rs @@ -0,0 +1,786 @@ +//! The explorer on screen, over what the core answers of the text at each frame. + +use egui::{Event, Key, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use engine::json::model::{JsonView, explore}; +use engine::json::parse::JsonErrorReason; +use engine::json::read::StructureFormat; +use i18n::Language; + +use super::{Explorer, ExplorerView, Mode, Output, graph, reason, size_words}; +use crate::testing; + +const ORDER: &str = r#"{"id":7,"paid":true,"lines":[{"name":"Pro"},{"name":"Basic"}],"note":null}"#; + +struct Screen { + explorer: Explorer, + text: String, + format: StructureFormat, + mode: Mode, + with_code: bool, + extractable: bool, + /// What the frames answered since it was last read. + said: Output, +} + +impl Screen { + fn view(&self) -> JsonView { + explore(&self.explorer.query(self.text.clone(), self.format)) + } + + fn selected(&self) -> Option { + self.explorer.selected_path(&self.view()) + } +} + +fn screen(text: &str, mode: Mode) -> Harness<'static, Screen> { + sized(text, mode, vec2(1_100.0, 800.0)) +} + +fn sized(text: &str, mode: Mode, size: egui::Vec2) -> Harness<'static, Screen> { + let state = Screen { + explorer: Explorer::default(), + text: text.to_owned(), + format: StructureFormat::Json, + mode, + with_code: true, + extractable: false, + said: Output::default(), + }; + let mut harness = testing::harness().with_size(size).build_ui_state( + |ui, screen: &mut Screen| { + let view = screen.view(); + let output = ExplorerView::new(&mut screen.explorer, &view, &screen.text) + .mode(screen.mode) + .format(screen.format) + .with_code(screen.with_code) + .extractable(screen.extractable) + .language(Language::En) + .show(ui); + let said = &mut screen.said; + said.chosen = output.chosen.or(said.chosen.take()); + said.show_in_code = output.show_in_code.or(said.show_in_code); + said.extract = output.extract.or(said.extract.take()); + said.tree_proposed |= output.tree_proposed; + }, + state, + ); + harness.run(); + harness +} + +fn graph_of(text: &str) -> Harness<'static, Screen> { + screen(text, Mode::Graph) +} + +fn tree_of(text: &str) -> Harness<'static, Screen> { + screen(text, Mode::Tree) +} + +fn present(harness: &Harness<'_, Screen>, author_id: &str) -> bool { + harness + .query_all_by(|node| node.author_id() == Some(author_id)) + .next() + .is_some() +} + +fn click(harness: &mut Harness<'_, Screen>, author_id: &str) { + harness.get_by(|node| node.author_id() == Some(author_id)).click(); + harness.run(); +} + +fn said(harness: &Harness<'_, Screen>, author_id: &str) -> String { + let node = harness.get_by(|node| node.author_id() == Some(author_id)); + let node = node.accesskit_node(); + node.value().or_else(|| node.label()).unwrap_or_default() +} + +/// The entries on screen: nodes, rows or lines, by their path. +fn shown(harness: &Harness<'_, Screen>) -> Vec { + harness + .query_all_by(|node| matches!(node.author_id(), Some("json-node-head" | "json-row" | "json-line"))) + .filter_map(|node| node.accesskit_node().description()) + .collect() +} + +fn entry<'a>(harness: &'a Harness<'_, Screen>, author_id: &'a str, path: &'a str) -> egui_kittest::Node<'a> { + harness.get_by(|node| node.author_id() == Some(author_id) && node.description().as_deref() == Some(path)) +} + +fn pick(harness: &mut Harness<'_, Screen>, author_id: &str, path: &str) { + entry(harness, author_id, path).click(); + harness.run(); +} + +fn press(harness: &mut Harness<'_, Screen>, modifiers: Modifiers, key: Key) { + harness.key_press_modifiers(modifiers, key); + harness.run(); +} + +fn walk(harness: &mut Harness<'_, Screen>, steps: &[(Key, &str)]) { + for (at, (key, path)) in steps.iter().enumerate() { + press(harness, Modifiers::NONE, *key); + let selected = harness.state().selected(); + assert_eq!(selected.as_deref(), Some(*path), "step {at}, {key:?}"); + } +} + +fn copied(harness: &mut Harness<'_, Screen>, author_id: &str) -> Option { + harness.get_by(|node| node.author_id() == Some(author_id)).click(); + let mut copied = None; + for _ in 0..4 { + harness.step(); + let commands = &harness.output().platform_output.commands; + copied = copied.or_else(|| { + commands.iter().find_map(|command| match command { + egui::OutputCommand::CopyText(text) => Some(text.clone()), + _ => None, + }) + }); + } + copied +} + +fn searches(harness: &mut Harness<'_, Screen>, words: &str) { + harness.get_by(|node| node.author_id() == Some("json-search")).click(); + harness.run(); + harness.get_by(|node| node.author_id() == Some("json-search")).type_text(words); + for _ in 0..6 { + harness.step(); + } + harness.run(); +} + +// The graph + +#[test] +fn a_node_clicked_is_the_selection() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$.lines"); + + assert_eq!(said(&harness, "json-selected-path"), "$.lines"); + assert_eq!(harness.state().said.chosen.as_deref(), Some("$.lines")); +} + +#[test] +fn a_row_that_holds_a_value_is_selected_and_one_that_opens_folds_and_unfolds() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.id"); + assert_eq!(said(&harness, "json-selected-path"), "$.id"); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned())); + + pick(&mut harness, "json-row", "$.lines"); + assert!(!shown(&harness).contains(&"$.lines[0]".to_owned())); + pick(&mut harness, "json-row", "$.lines"); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned())); +} + +/// Down the rows and no further, into a child, back to the row that opened it. +#[test] +fn the_arrows_walk_the_graph() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$"); + walk( + &mut harness, + &[ + (Key::ArrowUp, "$"), + (Key::ArrowDown, "$.id"), + (Key::ArrowUp, "$"), + (Key::ArrowRight, "$.id"), + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.paid"), + (Key::ArrowDown, "$.lines"), + (Key::ArrowRight, "$.lines"), + (Key::ArrowDown, "$.lines[0]"), + (Key::ArrowDown, "$.lines[1]"), + (Key::ArrowDown, "$.lines[1]"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$"), + (Key::ArrowLeft, "$"), + ], + ); +} + +#[test] +fn the_first_arrow_puts_the_cursor_on_the_root() { + for key in [Key::ArrowDown, Key::ArrowUp, Key::ArrowLeft, Key::ArrowRight] { + let mut harness = graph_of(ORDER); + harness.get_by(|node| node.author_id() == Some("json-graph")).focus(); + harness.run(); + walk(&mut harness, &[(key, "$")]); + } +} + +#[test] +fn a_row_is_opened_by_the_right_arrow_and_either_by_enter_or_space() { + for (key, then) in [(Key::Enter, false), (Key::Space, false), (Key::ArrowRight, true)] { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$"); + for _ in 0..3 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + press(&mut harness, Modifiers::NONE, Key::Enter); + assert!(!shown(&harness).contains(&"$.lines[0]".to_owned()), "folded"); + press(&mut harness, Modifiers::NONE, key); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned()), "{key:?}"); + press(&mut harness, Modifiers::NONE, key); + assert_eq!(shown(&harness).contains(&"$.lines[0]".to_owned()), then, "{key:?}"); + } +} + +/// It goes up until the root, whose Escape is the window's. +#[test] +fn escape_goes_back_up_the_graph() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.lines[0]"); + let names: Vec<_> = (0..4) + .map(|_| { + press(&mut harness, Modifiers::NONE, Key::Escape); + harness.state().selected().unwrap() + }) + .collect(); + + assert_eq!(names, ["$.lines", "$.lines", "$", "$"]); +} + +#[test] +fn shift_and_an_arrow_fold_everything_or_open_it() { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(ORDER, mode); + let first = if mode == Mode::Graph { "json-node-head" } else { "json-line" }; + pick(&mut harness, first, if mode == Mode::Graph { "$" } else { "$.id" }); + press(&mut harness, Modifiers::SHIFT, Key::ArrowLeft); + assert!(!shown(&harness).contains(&"$.lines[0]".to_owned()), "{mode:?}"); + press(&mut harness, Modifiers::SHIFT, Key::ArrowRight); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned()), "{mode:?}"); + } +} + +#[test] +fn the_buttons_fold_everything_and_open_it() { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(ORDER, mode); + click(&mut harness, "json-collapse-all"); + assert!(!shown(&harness).contains(&"$.lines[0]".to_owned()), "{mode:?}"); + click(&mut harness, "json-open-all"); + assert!(shown(&harness).contains(&"$.lines[0]".to_owned()), "{mode:?}"); + } +} + +#[test] +fn alt_and_an_arrow_move_the_node_and_the_layout_is_reset() { + for (key, step) in [ + (Key::ArrowLeft, vec2(-2.0, 0.0)), + (Key::ArrowRight, vec2(2.0, 0.0)), + (Key::ArrowUp, vec2(0.0, -1.0)), + (Key::ArrowDown, vec2(0.0, 1.0)), + ] { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-reset-layout")); + pick(&mut harness, "json-node-head", "$.lines"); + press(&mut harness, Modifiers::ALT, key); + assert_eq!(harness.state().explorer.offsets["$.lines"], step, "{key:?}"); + + click(&mut harness, "json-reset-layout"); + assert!(harness.state().explorer.offsets.is_empty()); + } +} + +/// Moved back where it was placed, there is nothing to reset. +#[test] +fn a_node_moved_there_and_back_is_not_moved() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-node-head", "$.lines"); + press(&mut harness, Modifiers::ALT, Key::ArrowLeft); + press(&mut harness, Modifiers::ALT, Key::ArrowRight); + + assert!(!present(&harness, "json-reset-layout")); +} + +fn drag(harness: &mut Harness<'_, Screen>, from: Pos2, by: egui::Vec2) { + let button = |pos, pressed| Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }; + harness.event(Event::PointerMoved(from)); + harness.event(button(from, true)); + harness.run(); + for part in 1..=4_u8 { + harness.event(Event::PointerMoved(from + by * (f32::from(part) / 4.0))); + harness.run(); + } + harness.event(button(from + by, false)); + harness.run(); +} + +fn centre(node: &egui_kittest::Node<'_>) -> Pos2 { + node.rect().center() +} + +#[test] +fn a_node_dragged_is_moved_and_not_clicked() { + let mut harness = graph_of(ORDER); + let from = centre(&entry(&harness, "json-node-head", "$.lines")); + drag(&mut harness, from, vec2(40.0, 48.0)); + + let moved = harness.state().explorer.offsets["$.lines"]; + assert!((moved.y - 2.0).abs() < 0.3 && moved.x > 1.0, "{moved:?}"); + assert_eq!(harness.state().said.chosen, None); + let after = centre(&entry(&harness, "json-node-head", "$.lines")); + assert!((after - from - vec2(40.0, 48.0)).length() < 8.0, "{after:?}"); +} + +#[test] +fn the_ground_dragged_or_scrolled_pans_the_graph() { + let mut harness = graph_of(ORDER); + let before = centre(&entry(&harness, "json-node-head", "$")); + drag(&mut harness, egui::pos2(500.0, 700.0), vec2(30.0, -20.0)); + let panned = centre(&entry(&harness, "json-node-head", "$")); + assert!((panned - before - vec2(30.0, -20.0)).length() < 8.0, "{before:?} {panned:?}"); + assert!(harness.state().explorer.offsets.is_empty()); + + scroll(&mut harness, 25.0); + let scrolled = centre(&entry(&harness, "json-node-head", "$")); + assert!((scrolled - panned - vec2(0.0, 25.0)).length() < 2.0, "{panned:?} {scrolled:?}"); +} + +fn scroll(harness: &mut Harness<'_, Screen>, by: f32) { + harness.event(Event::PointerMoved(egui::pos2(500.0, 600.0))); + harness.event(Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, by), + modifiers: Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }); + for _ in 0..30 { + harness.step(); + } +} + +fn zoom(harness: &Harness<'_, Screen>) -> String { + said(harness, "json-zoom-reset") +} + +#[test] +fn the_zoom_goes_by_steps_between_its_two_ends() { + let mut harness = graph_of(ORDER); + assert_eq!(zoom(&harness), "100 %"); + let mut seen = Vec::new(); + for _ in 0..4 { + click(&mut harness, "json-zoom-in"); + seen.push(zoom(&harness)); + } + assert_eq!(seen, ["125 %", "150 %", "200 %", "200 %"]); + click(&mut harness, "json-zoom-reset"); + assert_eq!(zoom(&harness), "100 %"); + seen.clear(); + for _ in 0..6 { + click(&mut harness, "json-zoom-out"); + seen.push(zoom(&harness)); + } + assert_eq!(seen, ["80 %", "67 %", "50 %", "40 %", "25 %", "25 %"]); +} + +/// Around the middle of the ground: what is under the eye stays there. +#[test] +fn the_zoom_keeps_the_middle_where_it_is() { + let rect = egui::Rect::from_min_size(egui::pos2(100.0, 50.0), vec2(400.0, 300.0)); + let mut ground = graph::Ground::default(); + let middle = |ground: &graph::Ground| (rect.size() / 2.0 - ground.pan()) / ground.zoom(); + let before = middle(&ground); + ground.zoom_to(rect, 2.0); + + assert!((middle(&ground) - before).length() < 0.01); +} + +#[test] +fn fit_brings_the_whole_graph_in() { + let many: Vec = (0..6).map(|n| format!(r#""k{n}":{{"a":{{"b":[1]}}}}"#)).collect(); + let mut harness = sized(&format!("{{{}}}", many.join(",")), Mode::Graph, vec2(700.0, 400.0)); + let nodes = harness.state().view().graph.nodes.len(); + let heads = |harness: &Harness<'_, Screen>| { + harness.query_all_by(|node| node.author_id() == Some("json-node-head")).count() + }; + assert!(heads(&harness) < nodes); + + click(&mut harness, "json-fit"); + assert_eq!(heads(&harness), nodes); +} + +#[test] +fn fit_never_goes_past_the_size_of_the_text() { + let mut harness = graph_of(ORDER); + click(&mut harness, "json-zoom-in"); + click(&mut harness, "json-fit"); + + assert_eq!(zoom(&harness), "100 %"); +} + +/// However large, it stays readable: the rest is panned to. +#[test] +fn fit_never_goes_under_the_smallest_zoom() { + let many: Vec = (0..60).map(|n| format!(r#""k{n}":{{"a":{{"b":[1]}}}}"#)).collect(); + let mut harness = graph_of(&format!("{{{}}}", many.join(","))); + click(&mut harness, "json-open-all"); + click(&mut harness, "json-fit"); + + assert_eq!(zoom(&harness), "25 %"); +} + +#[test] +fn rows_past_what_a_node_shows_are_counted() { + let many: Vec = (0..260).map(|n| n.to_string()).collect(); + let mut harness = sized(&format!("[{}]", many.join(",")), Mode::Graph, vec2(1_100.0, 5_300.0)); + harness.run(); + + let painted = testing::painted(&harness); + assert!(painted.iter().any(|words| words.contains("60")), "{painted:?}"); + assert!(shown(&harness).contains(&"$[199]".to_owned())); + assert!(!shown(&harness).contains(&"$[200]".to_owned())); +} + +#[test] +fn a_graph_too_large_is_folded_and_proposes_the_tree() { + let objects = vec![r#"{"a":1}"#; 200].join(","); + let arrays: Vec = (0..11).map(|n| format!(r#""k{n}":[{objects}]"#)).collect(); + let mut harness = graph_of(&format!("{{{}}}", arrays.join(","))); + click(&mut harness, "json-open-all"); + assert!(present(&harness, "json-folded")); + + click(&mut harness, "json-show-tree"); + assert!(harness.state().said.tree_proposed); +} + +/// Its cursor out of sight, the ground pans to it. +#[test] +fn the_cursor_is_brought_into_view() { + let rows: Vec = (0..60).map(|n| format!(r#""k{n}":{n}"#)).collect(); + let mut harness = graph_of(&format!("{{{}}}", rows.join(","))); + pick(&mut harness, "json-node-head", "$"); + for _ in 0..50 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + let low = entry(&harness, "json-row", "$.k49").rect(); + assert!(low.bottom() < 764.0 && low.top() > 60.0, "{low:?}"); + for _ in 0..50 { + press(&mut harness, Modifiers::NONE, Key::ArrowUp); + } + let head = entry(&harness, "json-node-head", "$").rect(); + assert!(head.top() >= 59.0, "{head:?}"); +} + +#[test] +fn the_breadcrumb_names_what_holds_the_selection_and_goes_there() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.lines[1]"); + let crumbs = harness.get_by(|node| node.author_id() == Some("json-crumbs")); + let named = crumbs.accesskit_node().label().unwrap_or_default(); + assert_eq!(named.split(" › ").count(), 3, "{named}"); + + let label = named.split(" › ").next().unwrap().to_owned(); + harness + .get_by(|node| { + node.role() == egui::accesskit::Role::Link && node.label().as_deref() == Some(label.as_str()) + }) + .click(); + harness.run(); + assert_eq!(harness.state().selected().as_deref(), Some("$")); +} + +// The tree + +/// ← folds a line open and goes to what holds one that is not; → opens it, then goes into it. +#[test] +fn the_arrows_walk_the_tree() { + let mut harness = tree_of(ORDER); + pick(&mut harness, "json-line", "$.id"); + walk( + &mut harness, + &[ + (Key::ArrowUp, "$"), + (Key::ArrowUp, "$"), + (Key::ArrowDown, "$.id"), + (Key::ArrowRight, "$.id"), + (Key::ArrowDown, "$.paid"), + (Key::ArrowDown, "$.lines"), + (Key::ArrowRight, "$.lines[0]"), + (Key::ArrowLeft, "$.lines[0]"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$.lines"), + (Key::ArrowLeft, "$"), + (Key::ArrowLeft, "$"), + ], + ); +} + +#[test] +fn a_line_is_opened_and_folded_by_a_click_and_by_the_keys() { + let mut harness = tree_of(ORDER); + let open = |harness: &Harness<'_, Screen>| shown(harness).contains(&"$.lines[0]".to_owned()); + assert!(open(&harness)); + pick(&mut harness, "json-line", "$.lines"); + assert!(!open(&harness)); + for (key, then) in [(Key::ArrowRight, true), (Key::Enter, false), (Key::Space, true)] { + press(&mut harness, Modifiers::NONE, key); + assert_eq!(open(&harness), then, "{key:?}"); + } +} + +#[test] +fn the_tree_stops_at_its_last_line() { + let mut harness = tree_of(r#"{"a":1}"#); + pick(&mut harness, "json-line", "$.a"); + walk(&mut harness, &[(Key::ArrowDown, "$.a")]); +} + +#[test] +fn the_line_reached_by_the_keys_is_scrolled_into_view() { + let rows: Vec = (0..80).map(|n| format!(r#""k{n}":{n}"#)).collect(); + let mut harness = tree_of(&format!("{{{}}}", rows.join(","))); + pick(&mut harness, "json-line", "$.k0"); + for _ in 0..70 { + press(&mut harness, Modifiers::NONE, Key::ArrowDown); + } + let low = entry(&harness, "json-line", "$.k70").rect(); + assert!(low.bottom() <= 801.0 && low.top() > 56.0, "{low:?}"); + for _ in 0..70 { + press(&mut harness, Modifiers::NONE, Key::ArrowUp); + } + let high = entry(&harness, "json-line", "$.k0").rect(); + assert!(high.top() > 50.0, "{high:?}"); +} + +#[test] +fn a_tree_cut_short_says_so() { + let many: Vec = (0..5_100).map(|n| n.to_string()).collect(); + let mut harness = tree_of(&format!("[{}]", many.join(","))); + let last = harness.state().view().tree.last().unwrap().path.clone(); + harness.state_mut().explorer.select(&last); + harness.state_mut().explorer.tree.reveal = true; + harness.run(); + scroll(&mut harness, -200.0); + + let words = i18n::translate(Language::En, i18n::keys::json::TREE_TRUNCATED, &[]); + assert!(testing::painted(&harness).contains(&words)); +} + +// The search + +#[test] +fn a_search_waits_for_a_pause_then_counts_its_matches() { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-match-next")); + searches(&mut harness, "name"); + + assert_eq!(harness.state().view().match_count, 2); + assert_eq!(said(&harness, "json-match-count"), "2"); +} + +#[test] +fn the_matches_are_walked_by_the_buttons_and_by_enter() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "name"); + let (first, second) = ("$.lines[0].name", "$.lines[1].name"); + let goes = |harness: &Harness<'_, Screen>| harness.state().selected().unwrap_or_default(); + + click(&mut harness, "json-match-next"); + assert_eq!((goes(&harness).as_str(), said(&harness, "json-match-count").as_str()), (first, "1 / 2")); + click(&mut harness, "json-match-next"); + assert_eq!(goes(&harness), second); + click(&mut harness, "json-match-next"); + assert_eq!(goes(&harness), first); + click(&mut harness, "json-match-previous"); + assert_eq!(goes(&harness), second); + click(&mut harness, "json-match-previous"); + assert_eq!(goes(&harness), first); + + harness.get_by(|node| node.author_id() == Some("json-search")).focus(); + harness.run(); + press(&mut harness, Modifiers::NONE, Key::Enter); + assert_eq!(goes(&harness), second); + press(&mut harness, Modifiers::SHIFT, Key::Enter); + assert_eq!(goes(&harness), first); + assert!(harness.get_by(|node| node.author_id() == Some("json-search")).is_focused()); +} + +#[test] +fn with_no_match_there_is_nowhere_to_go() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "nowhere"); + click(&mut harness, "json-match-next"); + + assert_eq!(harness.state().said.chosen, None); + assert_eq!(said(&harness, "json-match-count"), "0"); +} + +#[test] +fn escape_empties_the_search() { + let mut harness = graph_of(ORDER); + searches(&mut harness, "name"); + press(&mut harness, Modifiers::NONE, Key::Escape); + for _ in 0..6 { + harness.step(); + } + + assert!(!present(&harness, "json-match-next")); + assert_eq!(harness.state().view().match_count, 0); +} + +// The selection and the document + +#[test] +fn with_nothing_chosen_the_root_is_described() { + let harness = graph_of(ORDER); + + assert_eq!(said(&harness, "json-selected-path"), "$"); + assert!(said(&harness, "json-selected-kind").contains('4')); +} + +#[test] +fn each_kind_is_said() { + let text = r#"{"o":{"a":1},"l":[1,2],"s":"x","n":1.5,"b":true,"z":null}"#; + for (path, kind) in [ + ("$.o", "Object"), + ("$.l", "Array"), + ("$.s", "String"), + ("$.n", "Number"), + ("$.b", "Boolean"), + ("$.z", "Null"), + ] { + for mode in [Mode::Graph, Mode::Tree] { + let mut harness = screen(text, mode); + harness.state_mut().explorer.select(path); + harness.run(); + let words = said(&harness, "json-selected-kind").to_lowercase(); + assert!(words.contains(&kind.to_lowercase()), "{path}: {words}"); + } + } + let mut harness = screen("at = 1979-05-27T07:32:00Z\n", Mode::Graph); + harness.state_mut().format = StructureFormat::Toml; + harness.state_mut().explorer.select("$.at"); + harness.run(); + assert!(said(&harness, "json-selected-kind").to_lowercase().contains("date")); +} + +/// A string without its quotes, anything else as it is written. +#[test] +fn the_path_and_the_value_are_copied() { + let text = r#"{"s":"a \"b\"","l":[1, 2]}"#; + for (path, value) in [("$.s", r#"a "b""#), ("$.l", "[1, 2]")] { + for width in [1_100.0, 500.0] { + let mut harness = sized(text, Mode::Tree, vec2(width, 800.0)); + harness.state_mut().explorer.select(path); + harness.run(); + assert_eq!(copied(&mut harness, "json-copy-path").as_deref(), Some(path), "{width}"); + assert_eq!(copied(&mut harness, "json-copy-value").as_deref(), Some(value), "{width}"); + } + } +} + +#[test] +fn it_is_shown_in_the_code_where_there_is_one() { + let mut harness = graph_of(ORDER); + pick(&mut harness, "json-row", "$.id"); + click(&mut harness, "json-show-in-code"); + let span = harness.state().said.show_in_code.unwrap(); + assert_eq!(super::utf16_slice(ORDER, span), "7"); + + harness.state_mut().with_code = false; + harness.run(); + assert!(!present(&harness, "json-show-in-code")); +} + +#[test] +fn an_entry_is_extracted_under_an_answer_alone() { + let mut harness = graph_of(ORDER); + assert!(!present(&harness, "json-extract")); + harness.state_mut().extractable = true; + pick(&mut harness, "json-row", "$.id"); + click(&mut harness, "json-extract"); + + assert_eq!(harness.state().said.extract.as_deref(), Some("$.id")); +} + +#[test] +fn narrow_the_panel_keeps_the_path_and_its_actions() { + let harness = sized(ORDER, Mode::Graph, vec2(500.0, 800.0)); + + assert!(present(&harness, "json-selected-path") && present(&harness, "json-copy-value")); + assert!(!present(&harness, "json-selected-kind") && !present(&harness, "json-stats")); +} + +#[test] +fn the_document_is_measured() { + let harness = graph_of(ORDER); + let stats = said(&harness, "json-stats"); + + assert_eq!(stats, "Keys 6 · Depth 2 · Size 74 B"); +} + +#[test] +fn a_size_is_written_in_the_unit_it_reaches() { + for (bytes, words) in + [(0, "0 B"), (1_023, "1,023 B"), (1_024, "1 KB"), (1_536, "1.5 KB"), (1_048_576, "1 MB")] + { + assert_eq!(size_words(bytes, Language::En), words); + } +} + +#[test] +fn what_the_format_drops_is_said() { + for (format, text, says) in [ + (StructureFormat::Json, r#"{"a":1}"#, false), + (StructureFormat::Yaml, "a: 1", true), + (StructureFormat::Toml, "a = 1", true), + (StructureFormat::Xml, "", true), + ] { + let mut harness = graph_of(text); + harness.state_mut().format = format; + harness.run(); + assert_eq!(present(&harness, "json-format-note"), says, "{format:?}"); + assert!(!present(&harness, "json-notice")); + } + let mut harness = graph_of("a: 1\n---\nb: 2\n"); + harness.state_mut().format = StructureFormat::Yaml; + harness.run(); + assert!(present(&harness, "json-notice"), "the second document is not read"); +} + +#[test] +fn a_text_that_cannot_be_read_says_where_and_goes_there() { + let mut harness = graph_of(r#"{"a":}"#); + let words = said(&harness, "json-invalid"); + assert!(words.contains("JSON") && words.contains('6'), "{words}"); + assert!(!present(&harness, "json-search")); + + click(&mut harness, "json-error-show"); + let span = harness.state().said.show_in_code.unwrap(); + assert_eq!((span.start, span.end), (5, 5)); +} + +#[test] +fn every_reason_has_its_own_words() { + use JsonErrorReason as Reason; + let mut said: Vec = [ + Reason::UnexpectedEnd, + Reason::UnexpectedCharacter, + Reason::InvalidNumber, + Reason::InvalidEscape, + Reason::ControlCharacter, + Reason::TrailingCharacters, + Reason::TooDeep, + Reason::Malformed, + Reason::TooLarge, + ] + .map(|each| i18n::translate(Language::En, reason(each), &[])) + .to_vec(); + said.sort(); + said.dedup(); + + assert_eq!(said.len(), 9); +} diff --git a/crates/ui/src/widgets/layout.rs b/crates/ui/src/widgets/layout.rs index cb57f5c0a..53fd9e9f7 100644 --- a/crates/ui/src/widgets/layout.rs +++ b/crates/ui/src/widgets/layout.rs @@ -2,8 +2,7 @@ use crate::theme::tokens::font; use egui::{ - CursorIcon, Key, Modifiers, Rect, Response, Role, Sense, Stroke, Ui, UiBuilder, Vec2, - WidgetInfo, + CursorIcon, Key, Modifiers, Rect, Response, Role, Sense, Stroke, Ui, UiBuilder, Vec2, WidgetInfo, }; use super::{address, hovered, towards}; @@ -34,11 +33,7 @@ fn fitted(setting: u16, region: Rect) -> u16 { if setting != RAIL_DEFAULT { return setting; } - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "a window's width" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "a window's width")] let share = (region.width() * DEFAULT_SHARE) as u16; setting.min(share).max(RAIL_WIDTH.0) } @@ -91,11 +86,7 @@ impl RailWidth { /// The width to write, once the edge rests somewhere else than where it was taken from. pub fn rested(&self, ui: &Ui) -> Option { let (from, width) = self.0?; - #[expect( - clippy::cast_possible_truncation, - clippy::cast_sign_loss, - reason = "within RAIL_WIDTH" - )] + #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "within RAIL_WIDTH")] let rested = width.round() as u16; (rested != from && !ui.input(|input| input.pointer.any_down())).then_some(rested) } @@ -119,6 +110,7 @@ pub fn split_handle(ui: &mut Ui, author_id: &str) -> f32 { } let mut moved = response.drag_delta().x; if super::takes_keys(ui, &response) { + super::keep_arrows(ui, &response); ui.input_mut(|input| { if input.consume_key(Modifiers::NONE, Key::ArrowLeft) { moved -= STEP; @@ -165,22 +157,18 @@ mod tests { #[test] fn a_rail_is_widened_within_its_bounds() { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(800.0, 400.0)) - .build_ui_state( - |ui, width: &mut RailWidth| { - let region = ui.max_rect(); - width.show(ui, region, (160, (160, 520)), "rail-edge", |ui| { - ui.label("Bibliothèque"); - }); - }, - RailWidth::default(), - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(800.0, 400.0)).build_ui_state( + |ui, width: &mut RailWidth| { + let region = ui.max_rect(); + width.show(ui, region, (160, (160, 520)), "rail-edge", |ui| { + ui.label("Bibliothèque"); + }); + }, + RailWidth::default(), + ); harness.run(); - harness - .get_by(|node| node.author_id() == Some("rail-edge")) - .focus(); + harness.get_by(|node| node.author_id() == Some("rail-edge")).focus(); harness.run(); harness.key_press(Key::ArrowRight); harness.run(); @@ -193,6 +181,32 @@ mod tests { assert_eq!(harness.state().0, Some((160, 520.0))); } + /// Beside it, what it resizes: egui would take the focus there. + #[test] + fn a_handle_focused_is_moved_by_every_arrow() { + let mut harness = crate::testing::harness().with_size(egui::vec2(800.0, 400.0)).build_ui_state( + |ui, moved: &mut f32| { + ui.horizontal(|ui| { + crate::widgets::Button::new("Avant", "before").show(ui); + *moved += split_handle(ui, "edge"); + crate::widgets::Button::new("Après", "after").show(ui); + }); + }, + 0.0, + ); + harness.run(); + harness.get_by(|node| node.author_id() == Some("edge")).focus(); + harness.run(); + for (key, then) in + [(Key::ArrowRight, 16.0), (Key::ArrowRight, 32.0), (Key::ArrowLeft, 16.0), (Key::ArrowLeft, 0.0)] + { + harness.key_press(key); + harness.run(); + let moved = *harness.state(); + assert!((moved - then).abs() < 0.01, "{key:?}: {moved}"); + } + } + #[test] fn the_default_rail_fits_a_narrow_window_and_a_chosen_width_stays() { let narrow = Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(640.0, 400.0)); @@ -205,27 +219,40 @@ mod tests { #[test] fn a_rail_drawn_narrower_than_its_setting_writes_nothing_until_moved() { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(640.0, 400.0)) - .build_ui_state( - |ui, (width, rested): &mut (RailWidth, Option)| { - let region = ui.max_rect(); - width.beside(ui, region, (true, RAIL_DEFAULT), "rail-edge", |ui| { - ui.label("Bibliothèque"); - }); - *rested = width.rested(ui); - }, - (RailWidth::default(), None), - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(640.0, 400.0)).build_ui_state( + |ui, (width, rested): &mut (RailWidth, Option)| { + let region = ui.max_rect(); + width.beside(ui, region, (true, RAIL_DEFAULT), "rail-edge", |ui| { + ui.label("Bibliothèque"); + }); + *rested = width.rested(ui); + }, + (RailWidth::default(), None), + ); harness.run(); assert_eq!(harness.state().1, None); - harness - .get_by(|node| node.author_id() == Some("rail-edge")) - .focus(); + harness.get_by(|node| node.author_id() == Some("rail-edge")).focus(); harness.run(); harness.key_press(Key::ArrowRight); harness.run(); assert_eq!(harness.state().1, Some(RAIL_WIDTH.0 + 16)); } + + #[test] + fn a_rail_put_away_leaves_the_whole_region() { + let mut harness = crate::testing::harness().with_size(egui::vec2(800.0, 400.0)).build_ui_state( + |ui, (shown, left): &mut (bool, Rect)| { + let region = ui.max_rect(); + *left = RailWidth::default().beside(ui, region, (*shown, 200), "rail-edge", |_| ()); + }, + (false, Rect::NOTHING), + ); + harness.run(); + let whole = harness.state().1.width(); + harness.state_mut().0 = true; + harness.run(); + + assert!((whole - harness.state().1.width() - 208.0).abs() < 0.5); + } } diff --git a/crates/ui/src/widgets/list.rs b/crates/ui/src/widgets/list.rs index 03bc3e592..3c87c8d8b 100644 --- a/crates/ui/src/widgets/list.rs +++ b/crates/ui/src/widgets/list.rs @@ -8,21 +8,17 @@ use super::text; use crate::theme::palette; /// `count` rows of `height`, `row(ui, index)` called for the rows in view alone. -pub fn virtual_list( - ui: &mut Ui, - id: &str, - height: f32, - count: usize, - mut row: impl FnMut(&mut Ui, usize), -) { - egui::ScrollArea::vertical() - .id_salt(id) - .auto_shrink([false, false]) - .show_rows(ui, height, count, |ui, range| { +pub fn virtual_list(ui: &mut Ui, id: &str, height: f32, count: usize, mut row: impl FnMut(&mut Ui, usize)) { + egui::ScrollArea::vertical().id_salt(id).auto_shrink([false, false]).show_rows( + ui, + height, + count, + |ui, range| { for index in range { row(ui, index); } - }); + }, + ); } /// A read-only listing: line numbers in `line_no`, the code in the monospace face. The lines @@ -30,48 +26,23 @@ pub fn virtual_list( pub fn code_viewer(ui: &mut Ui, id: &str, lines: &[&str]) { let p = palette(ui.ctx()); let digits = lines.len().max(1).ilog10() + 1; - let gutter = text( - ui, - &"8".repeat(digits as usize), - font::BODY, - 400.0, - FontFamily::Monospace, - p.line_no, - ) - .size() - .x + 16.0; + let gutter = text(ui, &"8".repeat(digits as usize), font::BODY, 400.0, FontFamily::Monospace, p.line_no) + .size() + .x + + 16.0; egui::Frame::new() .fill(p.bg_1) .corner_radius(egui::CornerRadius::same(radius::MENU)) .show(ui, |ui| { virtual_list(ui, id, ROW, lines.len(), |ui, index| { - let (rect, _) = ui.allocate_exact_size( - Vec2::new(ui.available_width(), ROW), - egui::Sense::hover(), - ); - let number = text( - ui, - &(index + 1).to_string(), - font::BODY, - 400.0, - FontFamily::Monospace, - p.line_no, - ); - let numbered = egui::pos2( - rect.left() + gutter - 8.0 - number.size().x, - rect.top() + 2.0, - ); + let (rect, _) = + ui.allocate_exact_size(Vec2::new(ui.available_width(), ROW), egui::Sense::hover()); + let number = + text(ui, &(index + 1).to_string(), font::BODY, 400.0, FontFamily::Monospace, p.line_no); + let numbered = egui::pos2(rect.left() + gutter - 8.0 - number.size().x, rect.top() + 2.0); ui.painter().galley(numbered, number, Color32::TRANSPARENT); - let code = text( - ui, - lines[index], - font::BODY, - 400.0, - FontFamily::Monospace, - p.text_0, - ); - let clip = - Rect::from_min_max(egui::pos2(rect.left() + gutter, rect.top()), rect.max); + let code = text(ui, lines[index], font::BODY, 400.0, FontFamily::Monospace, p.text_0); + let clip = Rect::from_min_max(egui::pos2(rect.left() + gutter, rect.top()), rect.max); ui.painter().with_clip_rect(clip).galley( egui::pos2(clip.left(), rect.top() + 2.0), code, @@ -92,26 +63,20 @@ mod tests { #[test] fn only_the_rows_in_view_are_drawn() { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(300.0, 200.0)) - .build_ui_state( - |ui, drawn: &mut Drawn| { - drawn.0.clear(); - virtual_list(ui, "rows", 20.0, 30_000, |ui, index| { - drawn.0.push(index); - ui.label(format!("row {index}")); - }); - }, - Drawn::default(), - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(300.0, 200.0)).build_ui_state( + |ui, drawn: &mut Drawn| { + drawn.0.clear(); + virtual_list(ui, "rows", 20.0, 30_000, |ui, index| { + drawn.0.push(index); + ui.label(format!("row {index}")); + }); + }, + Drawn::default(), + ); harness.run(); let drawn = &harness.state().0; - assert!( - !drawn.is_empty() && drawn.len() < 20, - "{} rows drawn", - drawn.len() - ); + assert!(!drawn.is_empty() && drawn.len() < 20, "{} rows drawn", drawn.len()); assert_eq!(drawn[0], 0); } diff --git a/crates/ui/src/widgets/menu.rs b/crates/ui/src/widgets/menu.rs index 4043a3026..8c1dc051a 100644 --- a/crates/ui/src/widgets/menu.rs +++ b/crates/ui/src/widgets/menu.rs @@ -3,8 +3,8 @@ use crate::theme::tokens::{font, gap, radius}; use egui::{ - Color32, CornerRadius, FontFamily, Id, Key, Modifiers, Popup, PopupCloseBehavior, RectAlign, - Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, + Color32, CornerRadius, FontFamily, Id, Key, Modifiers, Popup, PopupCloseBehavior, RectAlign, Response, + Role, Sense, Stroke, Ui, Vec2, WidgetInfo, }; use engine::notes::view::fold; @@ -25,12 +25,7 @@ pub struct MenuItem<'a> { impl<'a> MenuItem<'a> { pub const fn new(label: &'a str, author_id: &'a str) -> Self { - Self { - label, - author_id, - children: &[], - destructive: false, - } + Self { label, author_id, children: &[], destructive: false } } #[must_use] @@ -77,9 +72,7 @@ pub fn fitted(ui: &mut Ui, trigger: f32, content: impl FnOnce(&mut Ui) -> R) data.insert_temp(key.with("next"), 0.0_f32); }); let inner = content(ui); - let next: f32 = ui - .data(|data| data.get_temp(key.with("next"))) - .unwrap_or(0.0); + let next: f32 = ui.data(|data| data.get_temp(key.with("next"))).unwrap_or(0.0); ui.data_mut(|data| { data.insert_temp(key, next); if let Some(outer) = outer { @@ -122,14 +115,8 @@ fn entries<'a>(ui: &mut Ui, items: &'a [MenuItem<'a>]) -> Option<&'a str> { let mut picked = None; let mut ids = Vec::with_capacity(items.len()); for item in items { - let response = entry( - ui, - item.label, - item.author_id, - item.destructive, - false, - !item.children.is_empty(), - ); + let response = + entry(ui, item.label, item.author_id, item.destructive, false, !item.children.is_empty()); ids.push(response.id); if item.children.is_empty() { if response.clicked() { @@ -166,11 +153,7 @@ struct SubMenu { /// The menu to the side of `parent`, open while the pointer is on either or the focus is in it. /// → opens it and walks in, ← closes it. -pub fn sub_menu( - ui: &mut Ui, - parent: &Response, - content: impl FnOnce(&mut Ui) -> R, -) -> Option { +pub fn sub_menu(ui: &mut Ui, parent: &Response, content: impl FnOnce(&mut Ui) -> R) -> Option { let id = parent.id.with("children"); let pass = ui.ctx().cumulative_pass_nr(); let mut held: SubMenu = ui @@ -260,9 +243,7 @@ pub fn arrows(ui: &Ui, ids: &[Id]) { let Some(first) = ids.first().copied() else { return; }; - let inside = ui - .memory(egui::Memory::focused) - .is_some_and(|focused| ids.contains(&focused)); + let inside = ui.memory(egui::Memory::focused).is_some_and(|focused| ids.contains(&focused)); if !inside && ui.memory(egui::Memory::focused).is_none() { ui.memory_mut(|memory| memory.request_focus(first)); } @@ -302,14 +283,7 @@ fn drawn( tail: f32, ) -> Response { let p = palette(ui.ctx()); - let probe = text( - ui, - label, - font::LABEL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let probe = text(ui, label, font::LABEL, 400.0, FontFamily::Proportional, p.text_1); let lead_room = if lead.is_some() { 22.0 } else { 0.0 }; let chevron_room = if opens { 20.0 } else { 0.0 }; needs(ui, 16.0 + lead_room + probe.size().x + chevron_room); @@ -326,21 +300,14 @@ fn drawn( .max(if response.has_focus() { 1.0 } else { 0.0 }) .max(if on { 1.0 } else { 0.0 }); let rest = if destructive { p.red } else { p.text_1 }; - let ink = if destructive { - rest - } else { - towards(rest, p.text_0, hover) - }; + let ink = if destructive { rest } else { towards(rest, p.text_0, hover) }; if hover > 0.0 { - ui.painter() - .rect_filled(response.rect, corner, p.bg_3.gamma_multiply(hover)); + ui.painter().rect_filled(response.rect, corner, p.bg_3.gamma_multiply(hover)); } let mut left = response.rect.left() + 8.0; if let Some((icon, colour)) = lead { - let glyph = egui::Rect::from_center_size( - egui::pos2(left + 7.0, response.rect.center().y), - Vec2::splat(14.0), - ); + let glyph = + egui::Rect::from_center_size(egui::pos2(left + 7.0, response.rect.center().y), Vec2::splat(14.0)); crate::theme::icons::paint(ui, glyph, icon, colour.unwrap_or(ink)); left += 22.0; } @@ -367,8 +334,7 @@ fn drawn( pub fn line(ui: &mut Ui) { let (rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 9.0), Sense::hover()); let colour = palette(ui.ctx()).line_soft; - ui.painter() - .hline(rect.x_range(), rect.center().y, Stroke::new(1.0, colour)); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, colour)); } /// The menus that name their value: `Value` shows the current choice on the control, `Label` @@ -380,7 +346,7 @@ pub enum Naming { } /// From this many entries, a filter sits at the top and takes the focus. -pub const FILTER_FROM: usize = 9; +const FILTER_FROM: usize = 9; /// A filtered menu keeps its size whatever it holds: the entries scroll under the field. const FILTERED_WIDTH: f32 = 240.0; pub(super) const FILTERED_HEIGHT: f32 = 240.0; @@ -402,9 +368,9 @@ pub(super) fn filter_field( query_id: Id, (label, author_id, placeholder): (&str, &str, &str), ) -> Filter { + start_over_once_opened(ui, query_id); let mut query: String = ui.data(|data| data.get_temp(query_id)).unwrap_or_default(); - let emptied = - !query.is_empty() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); + let emptied = !query.is_empty() && ui.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); if emptied { query.clear(); } @@ -423,12 +389,20 @@ pub(super) fn filter_field( field.request_focus(); } ui.data_mut(|data| data.insert_temp(query_id, query.clone())); - Filter { - query, - step, - entered, - height: field.rect.height(), - } + Filter { query, step, entered, height: field.rect.height() } +} + +/// What was typed and walked to is of one opening: not drawn at the pass before, it starts over. +fn start_over_once_opened(ui: &Ui, query_id: Id) { + let now = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|data| { + let drawn: Option = data.get_temp(query_id.with("drawn")); + if drawn.is_none_or(|last| last + 1 < now) { + data.remove::(query_id); + data.remove::(query_id.with("walked")); + } + data.insert_temp(query_id.with("drawn"), now); + }); } /// The entry the arrows stand on: the one they left, or the current one, or the first. @@ -441,14 +415,9 @@ pub(super) fn walk( ) -> Option { let held: Option = ui.data(|data| data.get_temp(walked_id)); let place = |entry: usize| shown.iter().position(|index| *index == entry); - let start = held - .and_then(place) - .or_else(|| current.and_then(place)) - .unwrap_or(0); + let start = held.and_then(place).or_else(|| current.and_then(place)).unwrap_or(0); let last = shown.len().saturating_sub(1); - let walked = shown - .get(start.saturating_add_signed(step).min(last)) - .copied(); + let walked = shown.get(start.saturating_add_signed(step).min(last)).copied(); ui.data_mut(|data| { if let Some(walked) = walked { data.insert_temp(walked_id, walked); @@ -468,14 +437,7 @@ pub struct ChoiceMenu<'a, T> { impl<'a, T: PartialEq + Copy> ChoiceMenu<'a, T> { pub fn new(label: &'a str, author_id: &'a str, options: &'a [(T, &'a str)]) -> Self { - Self { - label, - author_id, - options, - naming: Naming::Value, - hints: &[], - language: None, - } + Self { label, author_id, options, naming: Naming::Value, hints: &[], language: None } } #[must_use] @@ -506,23 +468,12 @@ impl<'a, T: PartialEq + Copy> ChoiceMenu<'a, T> { /// The control and its menu; the response is changed when another value was picked. pub fn show(self, ui: &mut Ui, selected: &mut T) -> Response { let p = palette(ui.ctx()); - let current = self - .options - .iter() - .find(|(value, _)| value == selected) - .map(|(_, name)| *name); + let current = self.options.iter().find(|(value, _)| value == selected).map(|(_, name)| *name); let shown = match self.naming { Naming::Value => current.unwrap_or(self.label), Naming::Label => self.label, }; - let probe = text( - ui, - shown, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_1, - ); + let probe = text(ui, shown, font::CONTROL, 400.0, FontFamily::Proportional, p.text_1); let corner = CornerRadius::same(radius::CONTROL); let label = self.label; let mut response = interact( @@ -551,10 +502,7 @@ impl<'a, T: PartialEq + Copy> ChoiceMenu<'a, T> { if galley.elided { response = tooltip(response, shown); } - let at = egui::pos2( - response.rect.left() + 8.0, - response.rect.center().y - galley.size().y / 2.0, - ); + let at = egui::pos2(response.rect.left() + 8.0, response.rect.center().y - galley.size().y / 2.0); ui.painter().galley(at, galley, Color32::TRANSPARENT); let glyph = egui::Rect::from_center_size( egui::pos2(response.rect.right() - 12.0, response.rect.center().y), @@ -582,12 +530,11 @@ impl<'a, T: PartialEq + Copy> ChoiceMenu<'a, T> { } }) .and_then(|shown| shown.inner); - if let Some(value) = picked { - ui.data_mut(|data| data.remove::(query_id)); - if value != *selected { - *selected = value; - response.mark_changed(); - } + if let Some(value) = picked + && value != *selected + { + *selected = value; + response.mark_changed(); } response } @@ -713,15 +660,13 @@ pub(super) fn walked_ring(ui: &Ui, row: egui::Rect) { #[cfg(test)] mod tests { - use egui_kittest::kittest::Queryable; + use egui_kittest::kittest::{NodeT, Queryable}; use super::*; use crate::widgets::Button; - const EXPORT: [MenuItem<'static>; 2] = [ - MenuItem::new("Markdown", "export-markdown"), - MenuItem::new("JSON", "export-json"), - ]; + const EXPORT: [MenuItem<'static>; 2] = + [MenuItem::new("Markdown", "export-markdown"), MenuItem::new("JSON", "export-json")]; const ITEMS: [MenuItem<'static>; 3] = [ MenuItem::new("Renommer", "rename"), MenuItem::new("Exporter", "export").children(&EXPORT), @@ -729,53 +674,37 @@ mod tests { ]; fn harness() -> egui_kittest::Harness<'static, Option> { - crate::testing::harness() - .with_size(egui::vec2(600.0, 400.0)) - .build_ui_state( - |ui, picked: &mut Option| { - let anchor = Button::new("Actions", "actions").show(ui); - if let Some(chosen) = menu(&anchor, &ITEMS) { - *picked = Some(chosen.to_string()); - } - }, - None, - ) + crate::testing::harness().with_size(egui::vec2(600.0, 400.0)).build_ui_state( + |ui, picked: &mut Option| { + let anchor = Button::new("Actions", "actions").show(ui); + if let Some(chosen) = menu(&anchor, &ITEMS) { + *picked = Some(chosen.to_string()); + } + }, + None, + ) } fn open(harness: &mut egui_kittest::Harness<'static, Option>) { harness.run(); - harness - .get_by(|node| node.author_id() == Some("actions")) - .click(); + harness.get_by(|node| node.author_id() == Some("actions")).click(); harness.run(); } /// A choice menu over `options`, its control showing `label`: the control's width, and its /// entries'. fn choice_width(options: &'static [(u8, &'static str)], label: &'static str) -> (f32, f32) { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(900.0, 500.0)) - .build_ui_state( - move |ui, chosen: &mut u8| { - ChoiceMenu::new(label, "choice", options) - .naming(Naming::Label) - .show(ui, chosen); - }, - 0, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(900.0, 500.0)).build_ui_state( + move |ui, chosen: &mut u8| { + ChoiceMenu::new(label, "choice", options).naming(Naming::Label).show(ui, chosen); + }, + 0, + ); harness.run(); - harness - .get_by(|node| node.author_id() == Some("choice")) - .click(); + harness.get_by(|node| node.author_id() == Some("choice")).click(); harness.run(); - let control = harness - .get_by(|node| node.author_id() == Some("choice")) - .rect() - .width(); - let entry = harness - .get_by(|node| node.author_id() == Some("choice-0")) - .rect() - .width(); + let control = harness.get_by(|node| node.author_id() == Some("choice")).rect().width(); + let entry = harness.get_by(|node| node.author_id() == Some("choice-0")).rect().width(); (control, entry) } @@ -783,10 +712,8 @@ mod tests { fn a_menu_is_as_wide_as_its_longest_entry_within_its_bounds() { const SHORT: [(u8, &str); 3] = [(0, "GET"), (1, "PUT"), (2, "HEAD")]; const LONG: [(u8, &str); 2] = [(0, "Convertir en liste de tâches"), (1, "Note")]; - const ENDLESS: [(u8, &str); 1] = [( - 0, - "Une entrée bien plus longue que tout ce qu'un menu déroulant devrait jamais montrer", - )]; + const ENDLESS: [(u8, &str); 1] = + [(0, "Une entrée bien plus longue que tout ce qu'un menu déroulant devrait jamais montrer")]; let (_, short) = choice_width(&SHORT, "Verb"); assert!(short < 100.0, "{short}"); @@ -821,27 +748,18 @@ mod tests { harness.key_press(Key::ArrowRight); harness.run(); - assert!( - harness - .query_by(|node| node.author_id() == Some("export-json")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("export-json")).is_some()); } fn point(harness: &mut egui_kittest::Harness<'static, Option>, author_id: &str) { - let centre = harness - .get_by(|node| node.author_id() == Some(author_id)) - .rect() - .center(); + let centre = harness.get_by(|node| node.author_id() == Some(author_id)).rect().center(); harness.event(egui::Event::PointerMoved(centre)); harness.run(); harness.run(); } fn sub_menu_shown(harness: &egui_kittest::Harness<'static, Option>) -> bool { - harness - .query_by(|node| node.author_id() == Some("export-json")) - .is_some() + harness.query_by(|node| node.author_id() == Some("export-json")).is_some() } #[test] @@ -912,60 +830,35 @@ mod tests { fn escape_closes_the_menu() { let mut harness = harness(); open(&mut harness); - assert!( - harness - .query_by(|node| node.author_id() == Some("rename")) - .is_some() - ); + assert!(harness.query_by(|node| node.author_id() == Some("rename")).is_some()); harness.key_press(Key::Escape); harness.run(); - assert!( - harness - .query_by(|node| node.author_id() == Some("rename")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("rename")).is_none()); } #[test] fn nine_choices_bring_a_filter() { - const NAMES: [&str; 9] = [ - "UTC", "Paris", "Londres", "Tokyo", "Lima", "Oslo", "Rome", "Dakar", "Sydney", - ]; + const NAMES: [&str; 9] = + ["UTC", "Paris", "Londres", "Tokyo", "Lima", "Oslo", "Rome", "Dakar", "Sydney"]; let options: Vec<(usize, &str)> = NAMES.iter().copied().enumerate().collect(); - let mut harness = crate::testing::harness() - .with_size(egui::vec2(600.0, 600.0)) - .build_ui_state( - move |ui, selected: &mut usize| { - ChoiceMenu::new("Fuseau", "zone", &options).show(ui, selected); - }, - 0, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(600.0, 600.0)).build_ui_state( + move |ui, selected: &mut usize| { + ChoiceMenu::new("Fuseau", "zone", &options).show(ui, selected); + }, + 0, + ); harness.run(); - harness - .get_by(|node| node.author_id() == Some("zone")) - .click(); + harness.get_by(|node| node.author_id() == Some("zone")).click(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("zone-filter")) - .type_text("lo"); + harness.get_by(|node| node.author_id() == Some("zone-filter")).type_text("lo"); harness.run(); - assert!( - harness - .query_by(|node| node.author_id() == Some("zone-2")) - .is_some() - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("zone-3")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("zone-2")).is_some()); + assert!(harness.query_by(|node| node.author_id() == Some("zone-3")).is_none()); - harness - .get_by(|node| node.author_id() == Some("zone-5")) - .click(); + harness.get_by(|node| node.author_id() == Some("zone-5")).click(); harness.run(); assert_eq!(*harness.state(), 5); } @@ -984,36 +877,18 @@ mod tests { (10, "MD"), (11, "TXT"), ]; - const NAMES: [&str; 12] = [ - "", - "JavaScript", - "TypeScript", - "Python", - "Rust", - "Go", - "", - "", - "", - "Shell", - "Markdown", - "", - ]; + const NAMES: [&str; 12] = + ["", "JavaScript", "TypeScript", "Python", "Rust", "Go", "", "", "", "Shell", "Markdown", ""]; fn opened() -> egui_kittest::Harness<'static, usize> { - let mut harness = crate::testing::harness() - .with_size(egui::vec2(900.0, 900.0)) - .build_ui_state( - |ui, selected: &mut usize| { - ChoiceMenu::new("Format", "format", &LANGUAGES) - .hints(&NAMES) - .show(ui, selected); - }, - 0, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(900.0, 900.0)).build_ui_state( + |ui, selected: &mut usize| { + ChoiceMenu::new("Format", "format", &LANGUAGES).hints(&NAMES).show(ui, selected); + }, + 0, + ); harness.run(); - harness - .get_by(|node| node.author_id() == Some("format")) - .click(); + harness.get_by(|node| node.author_id() == Some("format")).click(); harness.run(); harness.run(); harness @@ -1026,33 +901,18 @@ mod tests { .get_by(|node| node.author_id() == Some("format-filter")) .type_text("rus"); harness.run(); - assert!( - harness - .query_by(|node| node.author_id() == Some("format-4")) - .is_some() - ); - assert!( - harness - .query_by(|node| node.author_id() == Some("format-3")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("format-4")).is_some()); + assert!(harness.query_by(|node| node.author_id() == Some("format-3")).is_none()); } #[test] fn a_filtered_menu_keeps_its_size_and_scrolls() { let harness = opened(); let filter = harness.get_by(|node| node.author_id() == Some("format-filter")); - assert!( - filter.rect().width() <= FILTERED_WIDTH, - "{:?}", - filter.rect() - ); + assert!(filter.rect().width() <= FILTERED_WIDTH, "{:?}", filter.rect()); let last = harness.get_by(|node| node.author_id() == Some("format-11")); let bottom = filter.rect().top() + FILTERED_HEIGHT; - assert!( - last.rect().bottom() > bottom, - "the last entry lies under the fold" - ); + assert!(last.rect().bottom() > bottom, "the last entry lies under the fold"); } #[test] @@ -1064,9 +924,7 @@ mod tests { harness.run(); assert_eq!(*harness.state(), 2); assert!( - harness - .query_by(|node| node.author_id() == Some("format-filter")) - .is_none(), + harness.query_by(|node| node.author_id() == Some("format-filter")).is_none(), "the menu closed" ); } @@ -1074,14 +932,10 @@ mod tests { #[test] fn a_click_in_the_filter_keeps_the_menu_open_and_a_click_on_an_entry_closes_it() { let shown = |harness: &egui_kittest::Harness<'static, usize>| { - harness - .query_by(|node| node.author_id() == Some("format-filter")) - .is_some() + harness.query_by(|node| node.author_id() == Some("format-filter")).is_some() }; let mut harness = opened(); - harness - .get_by(|node| node.author_id() == Some("format-filter")) - .click(); + harness.get_by(|node| node.author_id() == Some("format-filter")).click(); harness.run(); assert!(shown(&harness), "the click closed the menu"); @@ -1089,9 +943,7 @@ mod tests { .get_by(|node| node.author_id() == Some("format-filter")) .type_text("rus"); harness.run(); - harness - .get_by(|node| node.author_id() == Some("format-4")) - .click(); + harness.get_by(|node| node.author_id() == Some("format-4")).click(); harness.run(); assert_eq!(*harness.state(), 4); assert!(!shown(&harness)); @@ -1116,29 +968,20 @@ mod tests { fn a_long_name_is_cut_at_the_edge_of_the_menu_and_said_whole_on_hover() { let long = format!("Drawing {}", "of the whole architecture ".repeat(8)); let names: Vec = (0..12).map(|rank| format!("{long}{rank}")).collect(); - let mut harness = crate::testing::harness() - .with_size(egui::vec2(900.0, 500.0)) - .build_ui_state( - move |ui, selected: &mut usize| { - let options: Vec<(usize, &str)> = - names.iter().map(String::as_str).enumerate().collect(); - ChoiceMenu::new("Insert", "drawings", &options).show(ui, selected); - }, - 0, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(900.0, 500.0)).build_ui_state( + move |ui, selected: &mut usize| { + let options: Vec<(usize, &str)> = names.iter().map(String::as_str).enumerate().collect(); + ChoiceMenu::new("Insert", "drawings", &options).show(ui, selected); + }, + 0, + ); harness.run(); - harness - .get_by(|node| node.author_id() == Some("drawings")) - .click(); + harness.get_by(|node| node.author_id() == Some("drawings")).click(); harness.run(); harness.run(); - let row = harness - .get_by(|node| node.author_id() == Some("drawings-1")) - .rect(); - let control = harness - .get_by(|node| node.author_id() == Some("drawings")) - .rect(); + let row = harness.get_by(|node| node.author_id() == Some("drawings-1")).rect(); + let control = harness.get_by(|node| node.author_id() == Some("drawings")).rect(); let edge = row.right().max(control.right()); for right in rights(&harness, "Drawing") { assert!(right <= edge, "a name ends at {right}, past {edge}"); @@ -1165,17 +1008,58 @@ mod tests { harness.key_press(Key::Escape); harness.run(); assert!( - harness - .query_by(|node| node.author_id() == Some("format-3")) - .is_some(), + harness.query_by(|node| node.author_id() == Some("format-3")).is_some(), "every entry is back" ); harness.key_press(Key::Escape); harness.run(); - assert!( - harness - .query_by(|node| node.author_id() == Some("format-filter")) - .is_none() - ); + assert!(harness.query_by(|node| node.author_id() == Some("format-filter")).is_none()); + } + + /// Opened again, it is the whole list, at what is selected. + #[test] + fn what_was_typed_and_walked_to_does_not_outlive_the_menu() { + let mut harness = opened(); + harness + .get_by(|node| node.author_id() == Some("format-filter")) + .type_text("rus"); + harness.run(); + harness.key_press(Key::Escape); + harness.run(); + harness.key_press(Key::ArrowDown); + harness.run(); + harness.get_by(|node| node.author_id() == Some("format-filter")).type_text("s"); + harness.run(); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: egui::pos2(700.0, 700.0), + button: egui::PointerButton::Primary, + pressed, + modifiers: Modifiers::NONE, + }); + } + harness.run(); + harness.get_by(|node| node.author_id() == Some("format")).click(); + harness.run(); + harness.run(); + + let filter = harness.get_by(|node| node.author_id() == Some("format-filter")); + assert_eq!(filter.accesskit_node().value().unwrap_or_default(), ""); + harness.key_press(Key::Enter); + harness.run(); + assert_eq!(*harness.state(), 0); + } + + #[test] + fn a_filter_that_finds_nothing_says_so_and_picks_nothing() { + let mut harness = opened(); + harness + .get_by(|node| node.author_id() == Some("format-filter")) + .type_text("zzz"); + harness.run(); + harness.key_press(Key::Enter); + harness.run(); + + assert_eq!(*harness.state(), 0); } } diff --git a/crates/ui/src/widgets/mod.rs b/crates/ui/src/widgets/mod.rs index 1e2e6ad31..aeb0bbfc5 100644 --- a/crates/ui/src/widgets/mod.rs +++ b/crates/ui/src/widgets/mod.rs @@ -24,22 +24,18 @@ pub mod rich; pub use badge::{Chip, Kbd, hue_badge, priority_dot, spinner}; pub use button::{Button, IconButton, Kind, SquareButton}; -pub use dialog::{ - Cross, DialogStack, Layer, Shown, dialog, dialog_title, framed_dialog, modal_panel, -}; +pub use dialog::{Cross, DialogStack, Layer, Shown, dialog, dialog_title, framed_dialog, modal_panel}; pub use empty::{EmptyAction, empty_state}; -pub use field::{Checkbox, SearchField, Searched, TextField, switch}; +pub use field::{Checkbox, SearchField, TextField, switch}; pub use in_place::{InPlace, ask_in_place}; pub use layout::{RailWidth, area_room, kept_together, split_handle, tooltip, wrap_before}; pub use list::{code_viewer, virtual_list}; pub use menu::{ - ChoiceMenu, FILTER_FROM, MenuItem, Naming, arrows as menu_arrows, entry as menu_entry, - fitted as fitted_menu, frame as menu_frame, icon_entry, line as menu_line, menu, - needs as menu_needs, sub_menu, + ChoiceMenu, MenuItem, Naming, arrows as menu_arrows, entry as menu_entry, fitted as fitted_menu, + frame as menu_frame, icon_entry, line as menu_line, menu, needs as menu_needs, sub_menu, }; pub use picker::{Lead, Place, place_picker}; pub use release_notes::release_notes; -pub use rich::{Read, rich_reader}; pub(crate) use rich::{append_coloured, syntax_of}; pub use segmented::Segmented; pub use split::{SplitButton, SplitKind}; @@ -47,8 +43,7 @@ pub use split::{SplitButton, SplitKind}; use std::sync::Arc; use egui::{ - Color32, CornerRadius, FontFamily, FontId, Galley, Response, RichText, Sense, Ui, Vec2, - WidgetInfo, + Color32, CornerRadius, FontFamily, FontId, Galley, Response, RichText, Sense, Ui, Vec2, WidgetInfo, }; use crate::theme::icons::Icon; @@ -67,11 +62,7 @@ pub fn interact( info: impl Fn() -> WidgetInfo, corner: CornerRadius, ) -> Response { - let size = if sense.senses_click() { - size.max(Vec2::splat(MIN_TARGET)) - } else { - size - }; + let size = if sense.senses_click() { size.max(Vec2::splat(MIN_TARGET)) } else { size }; let (_, response) = ui.allocate_exact_size(size, sense); response.widget_info(info); address(ui, &response, author_id); @@ -115,6 +106,14 @@ pub fn takes_keys(ui: &Ui, response: &Response) -> bool { ui.memory(|memory| memory.has_focus(response.id)) } +/// The arrows of the frame are the focused `response`'s: egui would move the focus itself. Not its +/// event filter, which a focus just asked for does not have until the frame after. +pub fn keep_arrows(ui: &Ui, response: &Response) { + if takes_keys(ui, response) { + ui.memory_mut(|memory| memory.move_focus(egui::FocusDirection::None)); + } +} + /// Room at a place already decided — a node on a ground, a pane — under an id that `salt` /// keeps whatever is drawn before it. pub fn region(ui: &mut Ui, rect: egui::Rect, salt: impl egui::AsIdSalt, sense: Sense) -> Response { @@ -202,13 +201,7 @@ impl Wrapped { } /// `words` at a CSS weight, wrapped at `width`, their arrows painted as `arrowed` paints them. -pub(crate) fn wrapped( - ui: &Ui, - words: &str, - (size, weight): (f32, f32), - ink: Color32, - width: f32, -) -> Wrapped { +pub(crate) fn wrapped(ui: &Ui, words: &str, (size, weight): (f32, f32), ink: Color32, width: f32) -> Wrapped { let mut laid = String::with_capacity(words.len()); let mut rank = 0; let mut arrows = Vec::new(); @@ -252,32 +245,17 @@ pub(crate) fn arrow_of(glyph: char) -> Option { /// ▾ or ▸, drawn: the glyphs are in none of the embedded faces. pub(crate) fn triangle(ui: &Ui, centre: egui::Pos2, open: bool, ink: Color32) { let points = if open { - vec![ - centre + egui::vec2(-4.0, -2.0), - centre + egui::vec2(4.0, -2.0), - centre + egui::vec2(0.0, 3.0), - ] + vec![centre + egui::vec2(-4.0, -2.0), centre + egui::vec2(4.0, -2.0), centre + egui::vec2(0.0, 3.0)] } else { - vec![ - centre + egui::vec2(-2.0, -4.0), - centre + egui::vec2(3.0, 0.0), - centre + egui::vec2(-2.0, 4.0), - ] + vec![centre + egui::vec2(-2.0, -4.0), centre + egui::vec2(3.0, 0.0), centre + egui::vec2(-2.0, 4.0)] }; - ui.painter() - .add(egui::Shape::convex_polygon(points, ink, egui::Stroke::NONE)); + ui.painter().add(egui::Shape::convex_polygon(points, ink, egui::Stroke::NONE)); } /// Words whose arrows (← ↑ → ↓ ↔, ↵ ⌫) are painted as icons: none of the embedded faces has them, /// the emoji face boxes ↔, and the system's are a different hand. Laid out from `left` on the line through `middle`; /// answers the width taken, which `at = None` measures without painting. -pub(crate) fn arrowed( - ui: &Ui, - at: Option, - words: &str, - size: f32, - ink: Color32, -) -> f32 { +pub(crate) fn arrowed(ui: &Ui, at: Option, words: &str, size: f32, ink: Color32) -> f32 { let mut width = 0.0; let mut rest = words; loop { @@ -290,8 +268,7 @@ pub(crate) fn arrowed( let piece_width = galley.size().x; if let Some(at) = at { let top = at.y - galley.size().y / 2.0; - ui.painter() - .galley(egui::pos2(at.x + width, top), galley, ink); + ui.painter().galley(egui::pos2(at.x + width, top), galley, ink); } width += piece_width; } @@ -299,10 +276,8 @@ pub(crate) fn arrowed( return width; }; if let Some(at) = at { - let glyph = egui::Rect::from_center_size( - egui::pos2(at.x + width + size / 2.0, at.y), - Vec2::splat(size), - ); + let glyph = + egui::Rect::from_center_size(egui::pos2(at.x + width + size / 2.0, at.y), Vec2::splat(size)); crate::theme::icons::paint(ui, glyph, icon, ink); } width += size; @@ -323,11 +298,7 @@ pub(crate) fn towards(from: Color32, to: Color32, t: f32) -> Color32 { /// A disabled control is drawn at half strength. fn dimmed(colour: Color32, enabled: bool) -> Color32 { - if enabled { - colour - } else { - colour.gamma_multiply(0.5) - } + if enabled { colour } else { colour.gamma_multiply(0.5) } } #[cfg(test)] diff --git a/crates/ui/src/widgets/picker.rs b/crates/ui/src/widgets/picker.rs index afe59c7d4..0e929eab8 100644 --- a/crates/ui/src/widgets/picker.rs +++ b/crates/ui/src/widgets/picker.rs @@ -38,11 +38,7 @@ pub struct Place { impl Place { /// Its whole path: what a reader hears, and what the filter reads. fn path(&self) -> String { - if self.within.is_empty() { - self.name.clone() - } else { - format!("{} › {}", self.within, self.name) - } + if self.within.is_empty() { self.name.clone() } else { format!("{} › {}", self.within, self.name) } } } @@ -67,29 +63,16 @@ pub fn place_picker( }) .collect(); let here = places.iter().position(|place| place.here && !place.again); - let walked = walk( - ui, - query_id.with("walked"), - &shown, - filter.step, - here.filter(|_| wanted.is_empty()), - ); + let walked = walk(ui, query_id.with("walked"), &shown, filter.step, here.filter(|_| wanted.is_empty())); if shown.is_empty() { let none = i18n::translate(language, keys::choice_menu::NO_RESULTS, &[]); let ink = palette(ui.ctx()).text_2; ui.label(egui::RichText::new(none).size(font::LABEL).color(ink)); } let searched = !wanted.is_empty(); - let picked = rows( - ui, - places, - &shown, - (walked, filter.step != 0, searched), - author_id, - ); + let picked = rows(ui, places, &shown, (walked, filter.step != 0, searched), author_id); let picked = picked.or(walked.filter(|_| filter.entered)); if picked.is_some() { - ui.data_mut(|data| data.remove::(query_id)); ui.close(); } picked @@ -112,10 +95,7 @@ fn rows( .show_rows(ui, ROW, shown.len(), |ui, range| { let top = ui.cursor().top(); let mut picked = None; - if moved - && let Some(at) = - walked.and_then(|walked| shown.iter().position(|one| *one == walked)) - { + if moved && let Some(at) = walked.and_then(|walked| shown.iter().position(|one| *one == walked)) { #[expect(clippy::cast_precision_loss, reason = "a row's rank")] let down = (at as f32 - range.start as f32) * ROW; let min = pos2(ui.cursor().left(), top + down); @@ -148,8 +128,7 @@ fn row(ui: &mut Ui, place: &Place, author_id: &str, (walked, searched): (bool, b let lit = walked || place.here; let hover = hovered(ui, &response).max(if lit { 1.0 } else { 0.0 }); if hover > 0.0 { - ui.painter() - .rect_filled(response.rect, corner, p.bg_3.gamma_multiply(hover)); + ui.painter().rect_filled(response.rect, corner, p.bg_3.gamma_multiply(hover)); } if walked { walked_ring(ui, response.rect); @@ -157,11 +136,7 @@ fn row(ui: &mut Ui, place: &Place, author_id: &str, (walked, searched): (bool, b let ink = towards(p.text_1, p.text_0, hover); let flat = searched || place.again; #[expect(clippy::cast_precision_loss, reason = "a level of nesting")] - let indent = if flat { - 0.0 - } else { - place.depth as f32 * INDENT - }; + let indent = if flat { 0.0 } else { place.depth as f32 * INDENT }; let mut left = response.rect.left() + 8.0 + indent; let middle = response.rect.center().y; match place.lead { @@ -173,8 +148,7 @@ fn row(ui: &mut Ui, place: &Place, author_id: &str, (walked, searched): (bool, b } Lead::Dot(colour) => { let dot = Rect::from_center_size(pos2(left + 4.0, middle), Vec2::splat(8.0)); - ui.painter() - .rect_filled(dot, CornerRadius::same(radius::TAG), colour); + ui.painter().rect_filled(dot, CornerRadius::same(radius::TAG), colour); left += 16.0; } } @@ -187,19 +161,9 @@ fn row(ui: &mut Ui, place: &Place, author_id: &str, (walked, searched): (bool, b ui.painter().galley(at, name, Color32::TRANSPARENT); if flat && !place.within.is_empty() { let rest = room - width - gap::CONTROLS; - let within = text( - ui, - &place.within, - font::META, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let within = text(ui, &place.within, font::META, 400.0, FontFamily::Proportional, p.text_2); if within.size().x <= rest { - let at = pos2( - response.rect.right() - 8.0 - within.size().x, - middle - within.size().y / 2.0, - ); + let at = pos2(response.rect.right() - 8.0 - within.size().x, middle - within.size().y / 2.0); ui.painter().galley(at, within, Color32::TRANSPARENT); } else { cut = true; @@ -244,17 +208,15 @@ mod tests { fn harness() -> egui_kittest::Harness<'static, Option> { let places = library(); - let mut harness = crate::testing::harness() - .with_size(egui::vec2(600.0, 500.0)) - .build_ui_state( - move |ui, picked: &mut Option| { - let language = i18n::Language::En; - if let Some(chosen) = place_picker(ui, &places, ("Move to", "move"), language) { - *picked = Some(chosen); - } - }, - None, - ); + let mut harness = crate::testing::harness().with_size(egui::vec2(600.0, 500.0)).build_ui_state( + move |ui, picked: &mut Option| { + let language = i18n::Language::En; + if let Some(chosen) = place_picker(ui, &places, ("Move to", "move"), language) { + *picked = Some(chosen); + } + }, + None, + ); harness.run(); harness } @@ -271,10 +233,7 @@ mod tests { let harness = harness(); let rows = rows(&harness); assert!(rows.len() < 14, "{} rows drawn", rows.len()); - let bottom = rows - .iter() - .map(|(_, rect)| rect.bottom()) - .fold(0.0, f32::max); + let bottom = rows.iter().map(|(_, rect)| rect.bottom()).fold(0.0, f32::max); assert!(bottom < 300.0, "{bottom}"); assert!(rows.iter().all(|(_, rect)| rect.width() <= WIDTH)); } @@ -300,12 +259,7 @@ mod tests { harness.run(); } let shown: Vec = rows(&harness).into_iter().map(|(label, _)| label).collect(); - assert!( - shown - .iter() - .any(|label| label.starts_with("Work › Folder 29 ")), - "{shown:?}" - ); + assert!(shown.iter().any(|label| label.starts_with("Work › Folder 29 ")), "{shown:?}"); harness.key_press(Key::Enter); harness.run(); assert_eq!(*harness.state(), Some(30)); @@ -322,4 +276,31 @@ mod tests { harness.run(); assert_eq!(*harness.state(), Some(2)); } + + #[test] + fn what_is_found_nowhere_is_said() { + let mut harness = harness(); + harness + .get_by(|node| node.author_id() == Some("move-filter")) + .type_text("nowhere"); + harness.run(); + + assert!(rows(&harness).is_empty()); + let none = i18n::translate(Language::En, keys::choice_menu::NO_RESULTS, &[]); + assert!(crate::testing::painted(&harness).contains(&none)); + harness.key_press(Key::Enter); + harness.run(); + assert_eq!(*harness.state(), None); + } + + #[test] + fn a_place_is_found_by_what_it_is_in() { + let mut harness = harness(); + harness + .get_by(|node| node.author_id() == Some("move-filter")) + .type_text("work › folder 299"); + harness.run(); + + assert_eq!(rows(&harness).len(), 1); + } } diff --git a/crates/ui/src/widgets/release_notes.rs b/crates/ui/src/widgets/release_notes.rs index c5af4eea8..e24dcb0c0 100644 --- a/crates/ui/src/widgets/release_notes.rs +++ b/crates/ui/src/widgets/release_notes.rs @@ -42,11 +42,7 @@ pub fn release_notes(ui: &mut Ui, release: &ChangelogRelease) { } fn format(colour: Color32, family: FontFamily, fill: Option) -> TextFormat { - let size = if family == FontFamily::Monospace { - 11.5 - } else { - 12.5 - }; + let size = if family == FontFamily::Monospace { 11.5 } else { 12.5 }; TextFormat { font_id: FontId::new(size, family), color: colour, diff --git a/crates/ui/src/widgets/rich.rs b/crates/ui/src/widgets/rich.rs index 1a7a63ca1..b6b5cabf3 100644 --- a/crates/ui/src/widgets/rich.rs +++ b/crates/ui/src/widgets/rich.rs @@ -10,8 +10,8 @@ use std::sync::Arc; use egui::text::LayoutJob; use egui::{ - Align2, Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Sense, Stroke, - StrokeKind, TextFormat, Ui, Vec2, pos2, vec2, + Align2, Color32, CornerRadius, FontFamily, FontId, Galley, Pos2, Rect, Sense, Stroke, StrokeKind, + TextFormat, Ui, Vec2, pos2, vec2, }; use richtext::picture::drawing_id; use richtext::{Block, Document, Inline, Item, ListKind, Marks, Selection}; @@ -27,18 +27,6 @@ const GAP: f32 = 0.7; const INDENT: f32 = 1.4; const CODE_SIZE: f32 = 12.5; -/// What a frame of the reader was asked: a link clicked. -#[derive(Debug, Default)] -pub struct Read { - pub link: Option, -} - -/// The document read at `scale` (1 in a Note; Present's slides read larger). -pub fn rich_reader(ui: &mut Ui, document: &Document, scale: f32) -> Read { - let painted = RichView::new(document).scale(scale).show(ui); - Read { link: painted.link } -} - /// A leaf as this frame laid it out. pub struct Laid { pub path: Vec, @@ -114,14 +102,7 @@ struct Frame<'a> { impl<'a> RichView<'a> { pub fn new(document: &'a Document) -> Self { - Self { - document, - scale: 1.0, - found: &[], - pictures: None, - selection: None, - slide: None, - } + Self { document, scale: 1.0, found: &[], pictures: None, selection: None, slide: None } } /// Presented: text no wider than `widest`, a code block no wider than its code, its lines @@ -239,10 +220,8 @@ fn draw_block(ui: &mut Ui, block: &Block, path: &mut Vec, frame: &mut Fra } } Block::Rule => { - let (rect, _) = - ui.allocate_exact_size(vec2(ui.available_width(), size), Sense::hover()); - ui.painter() - .hline(rect.x_range(), rect.center().y, Stroke::new(1.0, p.line)); + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), size), Sense::hover()); + ui.painter().hline(rect.x_range(), rect.center().y, Stroke::new(1.0, p.line)); } } } @@ -260,13 +239,7 @@ struct Style { impl Style { fn body(p: &Palette, size: f32) -> Self { - Self { - size, - weight: 400.0, - line_height: LINE_HEIGHT, - colour: p.text_0, - struck: false, - } + Self { size, weight: 400.0, line_height: LINE_HEIGHT, colour: p.text_0, struck: false } } } @@ -315,11 +288,7 @@ fn format(p: &Palette, marks: &Marks, style: Style) -> TextFormat { color: colour, italics: marks.italic, line_height: Some(style.size * style.line_height), - background: if marks.code { - p.bg_3 - } else { - Color32::TRANSPARENT - }, + background: if marks.code { p.bg_3 } else { Color32::TRANSPARENT }, ..TextFormat::default() }; let weight = if marks.bold { 650.0 } else { style.weight }; @@ -338,37 +307,51 @@ fn paragraph(ui: &mut Ui, content: &[Inline], style: Style, path: &[usize], fram let widest = frame.slide.map_or(f32::INFINITY, |slide| slide.widest); let (job, links) = job(p, content, style, ui.available_width().min(widest)); let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); - let reading = frame.selection.is_none(); - let sense = if reading && !links.is_empty() { - Sense::click() - } else { - Sense::hover() - }; - let (rect, response) = ui.allocate_exact_size(galley.size(), sense); - if reading { + let (rect, response) = ui.allocate_exact_size(galley.size(), sense_of(&links, frame)); + if frame.selection.is_none() { let plain = richtext::inlines::plain(content); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, &plain)); } - if let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|at| rect.contains(*at)) { - let at = galley.cursor_from_pos(pointer - rect.min).index.0; - if let Some((_, href)) = links.iter().find(|(range, _)| range.contains(&at)) { - let ctrl = ui.input(|input| input.modifiers.command); - if reading || ctrl { - ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); - } - let clicked = if reading { - response.clicked() - } else { - ctrl && ui.input(|input| input.pointer.primary_clicked()) - }; - if clicked && is_web(href) { - frame.painted.link = Some(href.clone()); - } - } - } + follow(ui, &response, (&galley, rect.min), &links, frame); paint_leaf(ui, path, rect.min, galley, style.colour, frame); } +/// Read, a leaf that holds a link takes the click; edited, the surface under it does. +fn sense_of(links: &Links, frame: &Frame<'_>) -> Sense { + if frame.selection.is_none() && !links.is_empty() { Sense::click() } else { Sense::hover() } +} + +/// The link under the pointer, followed by a click; edited, by Ctrl and a click. +fn follow( + ui: &Ui, + response: &egui::Response, + (galley, origin): (&Galley, Pos2), + links: &Links, + frame: &mut Frame<'_>, +) { + let within = Rect::from_min_size(origin, galley.size()); + let Some(pointer) = ui.ctx().pointer_hover_pos().filter(|at| within.contains(*at)) else { + return; + }; + let local = pointer - origin; + let cursor = galley.cursor_from_pos(local); + let before = local.x < galley.pos_from_cursor(cursor).center().x; + let under = cursor.index.0.saturating_sub(usize::from(before)); + let Some((_, href)) = links.iter().find(|(range, _)| range.contains(&under)) else { + return; + }; + let reading = frame.selection.is_none(); + let ctrl = ui.input(|input| input.modifiers.command); + if reading || ctrl { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + let clicked = + if reading { response.clicked() } else { ctrl && ui.input(|input| input.pointer.primary_clicked()) }; + if clicked && is_web(href) { + frame.painted.link = Some(href.clone()); + } +} + /// The selection under the text, then the text; the leaf kept for the editor. fn paint_leaf( ui: &Ui, @@ -381,8 +364,7 @@ fn paint_leaf( let p = palette(ui.ctx()); for (_, range) in frame.found.iter().filter(|(at, _)| at.as_slice() == path) { for rect in crate::widgets::editor::selection_rects(&galley, range.clone(), false, 4.0) { - ui.painter() - .rect_filled(rect.translate(origin.to_vec2()), 2.0, p.bg_3); + ui.painter().rect_filled(rect.translate(origin.to_vec2()), 2.0, p.bg_3); } } if let Some(selection) = frame.selection { @@ -390,26 +372,17 @@ fn paint_leaf( let path = path.to_vec(); if start.path <= path && path <= end.path && start != end { let from = if path == start.path { start.offset } else { 0 }; - let to = if path == end.path { - end.offset - } else { - galley.text().chars().count() - }; + let to = if path == end.path { end.offset } else { galley.text().chars().count() }; let past_end = path != end.path; let fill = p.amber_fill.gamma_multiply(0.3); for rect in crate::widgets::editor::selection_rects(&galley, from..to, past_end, 4.0) { - ui.painter() - .rect_filled(rect.translate(origin.to_vec2()), 2.0, fill); + ui.painter().rect_filled(rect.translate(origin.to_vec2()), 2.0, fill); } } } ui.painter().galley(origin, Arc::clone(&galley), colour); if frame.selection.is_some() { - frame.painted.leaves.push(Laid { - path: path.to_vec(), - origin, - galley, - }); + frame.painted.leaves.push(Laid { path: path.to_vec(), origin, galley }); } } @@ -422,11 +395,7 @@ fn is_web(href: &str) -> bool { fn list(ui: &mut Ui, kind: ListKind, items: &[Item], path: &mut Vec, frame: &mut Frame<'_>) { let p = palette(ui.ctx()); let size = frame.size; - let indent = if kind == ListKind::Task { - 14.0 * size / BODY + 8.0 - } else { - INDENT * size - }; + let indent = if kind == ListKind::Task { 14.0 * size / BODY + 8.0 } else { INDENT * size }; for (at, item) in items.iter().enumerate() { if at > 0 { ui.add_space(0.2 * size); @@ -438,8 +407,7 @@ fn list(ui: &mut Ui, kind: ListKind, items: &[Item], path: &mut Vec, fram match kind { ListKind::Bullet => { let centre = pos2(marker.right() - 0.6 * size, marker.center().y); - ui.painter() - .circle_filled(centre, 2.5 * size / BODY, p.text_1); + ui.painter().circle_filled(centre, 2.5 * size / BODY, p.text_1); } ListKind::Ordered { start } => { let number = format!("{}.", start + u64::try_from(at).unwrap_or(0)); @@ -453,13 +421,8 @@ fn list(ui: &mut Ui, kind: ListKind, items: &[Item], path: &mut Vec, fram } ListKind::Task => { let rect = checkbox(ui, marker, item.checked, size); - let sense = if frame.selection.is_some() { - Sense::click() - } else { - Sense::hover() - }; - let response = - crate::widgets::region(ui, rect.expand(3.0), path.clone(), sense); + let sense = if frame.selection.is_some() { Sense::click() } else { Sense::hover() }; + let response = crate::widgets::region(ui, rect.expand(3.0), path.clone(), sense); let checked = item.checked; let name = match item.blocks.first() { Some(Block::Paragraph(content)) if !content.is_empty() => { @@ -486,10 +449,7 @@ fn list(ui: &mut Ui, kind: ListKind, items: &[Item], path: &mut Vec, fram path.push(index); match block { Block::Paragraph(content) if kind == ListKind::Task => { - let style = Style { - struck: item.checked, - ..Style::body(p, size) - }; + let style = Style { struck: item.checked, ..Style::body(p, size) }; paragraph(ui, content, style, path, frame); } _ => draw_block(ui, block, path, frame), @@ -506,10 +466,7 @@ fn list(ui: &mut Ui, kind: ListKind, items: &[Item], path: &mut Vec, fram fn checkbox(ui: &Ui, marker: Rect, checked: bool, size: f32) -> Rect { let p = palette(ui.ctx()); let edge = 14.0 * size / BODY; - let rect = Rect::from_min_size( - pos2(marker.left(), marker.center().y - edge / 2.0), - Vec2::splat(edge), - ); + let rect = Rect::from_min_size(pos2(marker.left(), marker.center().y - edge / 2.0), Vec2::splat(edge)); let corner = CornerRadius::same(radius::TAG); if checked { ui.painter().rect_filled(rect, corner, p.amber_fill); @@ -518,8 +475,7 @@ fn checkbox(ui: &Ui, marker: Rect, checked: bool, size: f32) -> Rect { pos2(rect.left() + edge * 0.43, rect.bottom() - edge * 0.28), pos2(rect.right() - edge * 0.22, rect.top() + edge * 0.3), ]; - ui.painter() - .line(tick.to_vec(), Stroke::new(1.6, p.amber_ink)); + ui.painter().line(tick.to_vec(), Stroke::new(1.6, p.amber_ink)); } else { ui.painter() .rect_stroke(rect, corner, Stroke::new(1.0, p.line), StrokeKind::Inside); @@ -543,10 +499,7 @@ fn quote(ui: &mut Ui, inner: &[Block], path: &mut Vec, frame: &mut Frame< path.push(at); match block { Block::Paragraph(content) => { - let style = Style { - colour: p.text_1, - ..Style::body(p, size) - }; + let style = Style { colour: p.text_1, ..Style::body(p, size) }; paragraph(ui, content, style, path, frame); } _ => draw_block(ui, block, path, frame), @@ -559,8 +512,7 @@ fn quote(ui: &mut Ui, inner: &[Block], path: &mut Vec, frame: &mut Frame< let bottom = ui.cursor().top(); let left = ui.max_rect().left(); let bar = Rect::from_min_max(pos2(left, top), pos2(left + 3.0, bottom)); - ui.painter() - .rect_filled(bar, CornerRadius::ZERO, p.amber_dim); + ui.painter().rect_filled(bar, CornerRadius::ZERO, p.amber_dim); } fn code_block(ui: &mut Ui, language: &str, text: &str, path: &[usize], frame: &mut Frame<'_>) { @@ -578,11 +530,7 @@ fn code_block(ui: &mut Ui, language: &str, text: &str, path: &[usize], frame: &m } let padding = vec2(14.0, 12.0); let column = ui.available_width(); - job.wrap.max_width = if frame.slide.is_some() { - column - 2.0 * padding.x - } else { - f32::INFINITY - }; + job.wrap.max_width = if frame.slide.is_some() { column - 2.0 * padding.x } else { f32::INFINITY }; let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); let width = if frame.slide.is_some() { (galley.size().x + 2.0 * padding.x + fence_room(ui, language)).min(column) @@ -618,10 +566,7 @@ fn code_block(ui: &mut Ui, language: &str, text: &str, path: &[usize], frame: &m let mut clipped = ui.new_child(egui::UiBuilder::new().max_rect(rect)); // ⚠️ Within the scroll area's clip, never instead of it: a block scrolled under the top of // the body was painted over the editor's header. - clipped.set_clip_rect( - rect.shrink2(vec2(0.0, padding.y - 2.0)) - .intersect(ui.clip_rect()), - ); + clipped.set_clip_rect(rect.shrink2(vec2(0.0, padding.y - 2.0)).intersect(ui.clip_rect())); paint_leaf(&clipped, path, rect.min + padding, galley, p.text_0, frame); } @@ -631,9 +576,7 @@ fn fence_room(ui: &Ui, language: &str) -> f32 { return 0.0; } let font = FontId::monospace(font::CAPTION); - let word = ui - .painter() - .layout_no_wrap(language.to_owned(), font, Color32::PLACEHOLDER); + let word = ui.painter().layout_no_wrap(language.to_owned(), font, Color32::PLACEHOLDER); word.size().x + 10.0 } @@ -660,11 +603,7 @@ pub(crate) fn append_coloured( job.append(line, 0.0, plain(p.text_0)); return; }; - let byte = |chars: usize| { - line.char_indices() - .nth(chars) - .map_or(line.len(), |(at, _)| at) - }; + let byte = |chars: usize| line.char_indices().nth(chars).map_or(line.len(), |(at, _)| at); let mut from = 0; for (range, token) in tokens { let (start, end) = (byte(range.start), byte(range.end)); @@ -672,10 +611,7 @@ pub(crate) fn append_coloured( job.append(&line[from..start], 0.0, plain(p.text_0)); } let (colour, leans) = crate::services::highlight::colour(p, *token); - let format = TextFormat { - italics: leans, - ..plain(colour) - }; + let format = TextFormat { italics: leans, ..plain(colour) }; job.append(&line[start..end.max(start)], 0.0, format); from = end.max(start); } @@ -696,37 +632,39 @@ fn table(ui: &mut Ui, rows: &[Vec], path: &[usize], frame: &mut let padding = vec2(10.0, 6.0); for (at, row) in rows.iter().enumerate() { let header = at == 0; - let style = Style { - weight: if header { 600.0 } else { 400.0 }, - ..Style::body(p, size) - }; - let galleys: Vec<_> = (0..columns) + let style = Style { weight: if header { 600.0 } else { 400.0 }, ..Style::body(p, size) }; + let cells: Vec<_> = (0..columns) .map(|index| { - let cell = row.get(index).map_or(&[][..], Vec::as_slice); - let (job, _) = job(p, cell, style, column - 2.0 * padding.x); - ui.fonts_mut(|fonts| fonts.layout_job(job)) + let content = row.get(index).map_or(&[][..], Vec::as_slice); + let (job, links) = job(p, content, style, column - 2.0 * padding.x); + let galley = ui.fonts_mut(|fonts| fonts.layout_job(job)); + (content, galley, links) }) .collect(); - let height = galleys + let height = cells .iter() - .map(|galley| galley.size().y) + .map(|(_, galley, _)| galley.size().y) .fold(size * LINE_HEIGHT, f32::max) + 2.0 * padding.y; let (rect, _) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); - for (index, galley) in galleys.into_iter().enumerate() { + for (index, (content, galley, links)) in cells.into_iter().enumerate() { let left = rect.left() + column * f32::from(u16::try_from(index).unwrap_or(0)); let cell = Rect::from_min_size(pos2(left, rect.top()), vec2(column, height)); if header { ui.painter().rect_filled(cell, CornerRadius::ZERO, p.bg_2); } - ui.painter().rect_stroke( - cell, - CornerRadius::ZERO, - Stroke::new(1.0, p.line), - StrokeKind::Middle, - ); + ui.painter() + .rect_stroke(cell, CornerRadius::ZERO, Stroke::new(1.0, p.line), StrokeKind::Middle); let cell_path = [path, &[at, index]].concat(); - paint_leaf(ui, &cell_path, cell.min + padding, galley, p.text_0, frame); + let sense = sense_of(&links, frame); + let response = crate::widgets::region(ui, cell, &cell_path, sense); + if frame.selection.is_none() { + let plain = richtext::inlines::plain(content); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Cell, true, &plain)); + } + let origin = cell.min + padding; + follow(ui, &response, (&galley, origin), &links, frame); + paint_leaf(ui, &cell_path, origin, galley, p.text_0, frame); } } } @@ -745,11 +683,7 @@ impl Drawn { /// An image's room: edited, a click picks it. fn image_room(ui: &mut Ui, size: Vec2, words: &str, frame: &Frame<'_>) -> egui::Response { - let sense = if frame.selection.is_some() { - Sense::CLICK - } else { - Sense::hover() - }; + let sense = if frame.selection.is_some() { Sense::CLICK } else { Sense::hover() }; let (_, response) = ui.allocate_exact_size(size, sense); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, words)); crate::widgets::address(ui, &response, "rich-embed"); @@ -781,10 +715,7 @@ fn picture_of( Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE, ); - Drawn { - response, - whole: Some(whole), - } + Drawn { response, whole: Some(whole) } } /// Where a picture is coming, or says it will not. @@ -807,10 +738,7 @@ fn placeholder(ui: &mut Ui, words: &str, frame: &Frame<'_>) -> Drawn { FontId::proportional(font::LABEL), p.text_2, ); - Drawn { - response, - whole: None, - } + Drawn { response, whole: None } } /// A drawing embedded by `devnotes:drawing/`, its picture read by id where it is shown; any @@ -837,88 +765,4 @@ fn image(ui: &mut Ui, alt: &str, (src, width): (&str, Option), frame: &mut F } #[cfg(test)] -mod tests { - use egui_kittest::kittest::{NodeT, Queryable}; - - use super::*; - - fn shown(markdown: &'static str) -> egui_kittest::Harness<'static, Option> { - let document = richtext::read(markdown); - let mut harness = crate::testing::harness() - .with_size(vec2(700.0, 900.0)) - .build_ui_state( - move |ui, link: &mut Option| { - if let Some(href) = rich_reader(ui, &document, 1.0).link { - *link = Some(href); - } - }, - None, - ); - harness.run(); - harness - } - - fn says(harness: &egui_kittest::Harness<'_, T>, words: &str) -> bool { - harness - .query_all_by(|node| { - node.label() - .or_else(|| node.value()) - .is_some_and(|said| said.contains(words)) - }) - .next() - .is_some() - } - - #[test] - fn every_sample_note_reads_in_both_languages() { - let fr = i18n::translate( - i18n::Language::Fr, - i18n::keys::notes::samples::release::CONTENT, - &[], - ); - let en = i18n::translate( - i18n::Language::En, - i18n::keys::notes::samples::release::CONTENT, - &[], - ); - for content in [fr, en] { - let document = richtext::read(&content); - let mut harness = crate::testing::harness() - .with_size(vec2(700.0, 900.0)) - .build_ui(move |ui| { - rich_reader(ui, &document, 1.0); - }); - harness.run(); - let code = harness.get_by(|node| node.role() == egui::accesskit::Role::Code); - assert!( - code.accesskit_node() - .label() - .unwrap_or_default() - .starts_with("kubectl rollout") - ); - } - } - - #[test] - fn headings_lists_tasks_quotes_and_tables_are_read() { - let harness = shown( - "# Titre\n\n- un\n - deux\n\n1. premier\n\n- [x] fait\n\n> cité\n\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\n---", - ); - for words in ["Titre", "un", "deux", "premier", "fait", "cité"] { - assert!(says(&harness, words), "{words} is read"); - } - } - - #[test] - fn a_web_link_is_answered_and_another_scheme_is_not() { - let mut harness = shown("[le site](https://exemple.fr)"); - harness.get_by_label("le site").click(); - harness.run(); - assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); - - let mut harness = shown("[un fichier](file:///etc/passwd)"); - harness.get_by_label("un fichier").click(); - harness.run(); - assert!(harness.state().is_none(), "never a file"); - } -} +mod tests; diff --git a/crates/ui/src/widgets/rich/tests.rs b/crates/ui/src/widgets/rich/tests.rs new file mode 100644 index 000000000..21b1d3e3c --- /dev/null +++ b/crates/ui/src/widgets/rich/tests.rs @@ -0,0 +1,513 @@ +use egui_kittest::kittest::{NodeT, Queryable}; + +use super::*; + +fn shown(markdown: &'static str) -> egui_kittest::Harness<'static, Option> { + let document = richtext::read(markdown); + let mut harness = crate::testing::harness().with_size(vec2(700.0, 900.0)).build_ui_state( + move |ui, link: &mut Option| { + if let Some(href) = RichView::new(&document).show(ui).link { + *link = Some(href); + } + }, + None, + ); + harness.run(); + harness +} + +fn says(harness: &egui_kittest::Harness<'_, T>, words: &str) -> bool { + harness + .query_all_by(|node| node.label().or_else(|| node.value()).is_some_and(|said| said.contains(words))) + .next() + .is_some() +} + +#[test] +fn every_sample_note_reads_in_both_languages() { + let fr = i18n::translate(i18n::Language::Fr, i18n::keys::notes::samples::release::CONTENT, &[]); + let en = i18n::translate(i18n::Language::En, i18n::keys::notes::samples::release::CONTENT, &[]); + for content in [fr, en] { + let document = richtext::read(&content); + let mut harness = crate::testing::harness().with_size(vec2(700.0, 900.0)).build_ui(move |ui| { + RichView::new(&document).show(ui); + }); + harness.run(); + let code = harness.get_by(|node| node.role() == egui::accesskit::Role::Code); + assert!(code.accesskit_node().label().unwrap_or_default().starts_with("kubectl rollout")); + } +} + +#[test] +fn headings_lists_tasks_quotes_and_tables_are_read() { + let harness = shown( + "# Titre\n\n- un\n - deux\n\n1. premier\n\n- [x] fait\n\n> cité\n\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\n---", + ); + for words in ["Titre", "un", "deux", "premier", "fait", "cité"] { + assert!(says(&harness, words), "{words} is read"); + } +} + +#[test] +fn a_web_link_is_answered_and_another_scheme_is_not() { + let mut harness = shown("[le site](https://exemple.fr)"); + harness.get_by_label("le site").click(); + harness.run(); + assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); + + let mut harness = shown("[un fichier](file:///etc/passwd)"); + harness.get_by_label("un fichier").click(); + harness.run(); + assert!(harness.state().is_none(), "never a file"); +} + +#[test] +fn a_link_in_a_table_is_read_and_answered() { + let mut harness = shown("| a | b |\n| --- | --- |\n| un | [le site](https://exemple.fr) |"); + assert!(says(&harness, "un")); + let at = harness.get_by_label("le site").rect().left_top() + vec2(16.0, 14.0); + harness.hover_at(at); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); + assert_eq!(harness.state().as_deref(), Some("https://exemple.fr")); +} + +/// Edited, the click is the caret's: the link wants Ctrl, in a table as elsewhere. +#[test] +fn edited_a_link_is_followed_with_ctrl_alone() { + for markdown in ["[site](https://exemple.fr)", "| [site](https://exemple.fr) |\n| --- |\n| b |"] { + for (modifiers, link) in + [(egui::Modifiers::NONE, None), (egui::Modifiers::COMMAND, Some("https://exemple.fr"))] + { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness().with_size(vec2(700.0, 300.0)).build_ui_state( + move |ui, painted: &mut Painted| { + let now = RichView::new(&document).editing(&selection).show(ui); + painted.link = now.link.or(painted.link.take()); + painted.leaves = now.leaves; + }, + Painted::default(), + ); + harness.run(); + let at = harness.state().leaves[0].origin + vec2(12.0, 10.0); + harness.event(egui::Event::ModifiersChanged(modifiers)); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers, + }); + } + harness.run(); + assert_eq!(harness.state().link.as_deref(), link, "{markdown}"); + } + } +} + +// What a run is written with + +fn ink() -> &'static Palette { + palette(&egui::Context::default()) +} + +fn run(markdown: &str) -> TextFormat { + let document = richtext::read(markdown); + let Block::Paragraph(content) = &document.blocks[0] else { + panic!("a paragraph"); + }; + let (job, _) = job(ink(), content, Style::body(ink(), 14.0), 500.0); + job.sections[0].format.clone() +} + +fn weight(format: &TextFormat) -> f32 { + let set = format + .coords + .as_ref() + .iter() + .find(|(tag, _)| *tag == egui::epaint::text::Tag::new(b"wght")); + set.map_or(0.0, |(_, value)| *value) +} + +#[test] +fn a_mark_changes_what_it_says_and_nothing_else() { + let plain = run("mot"); + assert_eq!(plain.font_id, FontId::proportional(BODY)); + assert_eq!((plain.color, plain.italics), (ink().text_0, false)); + assert!((weight(&plain) - 400.0).abs() < 0.5); + + assert!((weight(&run("**mot**")) - 650.0).abs() < 0.5); + assert!(run("*mot*").italics); + + let struck = run("~~mot~~"); + assert_eq!((struck.color, struck.strikethrough.width), (ink().text_2, 1.0)); + let code = run("`mot`"); + assert_eq!((code.font_id, code.background), (FontId::monospace(BODY * 0.88), ink().bg_3)); + let link = run("[mot](https://a.fr)"); + assert_eq!((link.color, link.underline.width), (ink().amber_text, 1.0)); + assert!(plain.strikethrough.width == 0.0 && plain.underline.width == 0.0); +} + +#[test] +fn a_link_covers_its_own_characters() { + let document = richtext::read("été [le site](https://a.fr) et [x](https://b.fr)"); + let Block::Paragraph(content) = &document.blocks[0] else { + panic!("a paragraph"); + }; + let (_, links) = job(ink(), content, Style::body(ink(), 14.0), 500.0); + + assert_eq!(links, [(4..11, "https://a.fr".to_owned()), (15..16, "https://b.fr".to_owned())]); +} + +#[test] +fn an_empty_paragraph_keeps_the_height_of_a_line() { + let (job, links) = job(ink(), &[], Style::body(ink(), 14.0), 500.0); + + assert!(links.is_empty()); + assert_eq!(job.sections.len(), 1); + assert_eq!(job.sections[0].format.line_height, Some(14.0 * LINE_HEIGHT)); +} + +#[test] +fn three_levels_of_heading_are_larger_than_the_text() { + let sizes = [1, 2, 3, 4, 6].map(|level| heading_size(level, 14.0)); + + assert_eq!(sizes.map(|size| size.to_string()), ["22", "18", "15", "14", "14"]); +} + +#[test] +fn a_heading_larger_than_the_text_stands_further_from_what_is_above() { + let heading = |level| Block::Heading { level, content: Vec::new() }; + assert!((gap_before(&heading(1), 14.0) - 1.1 * 22.0).abs() < 0.01); + for block in [heading(4), Block::Rule] { + assert!((gap_before(&block, 14.0) - GAP * 14.0).abs() < 0.01); + } +} + +#[test] +fn a_fence_names_its_language_by_its_tag_or_by_a_shell_s_name() { + let shell = syntax_of("sh"); + assert!(shell.is_some()); + for (fence, syntax) in [ + ("bash", shell), + ("shell", shell), + ("ZSH", shell), + ("RS", syntax_of("rs")), + ("nowhere", None), + ("", None), + ] { + assert_eq!(syntax_of(fence), syntax, "{fence}"); + } + assert_ne!(syntax_of("rs"), None); +} + +#[test] +fn a_web_address_is_one_whatever_its_case() { + for (href, web) in [ + ("https://a.fr", true), + ("HTTP://A.FR", true), + ("file:///etc/passwd", false), + ("javascript:alert(1)", false), + ("mailto:a@b.fr", false), + ("a.fr/http://b.fr", false), + ] { + assert_eq!(is_web(href), web, "{href}"); + } +} + +// Read + +fn painted(markdown: &'static str) -> Vec { + crate::testing::painted(&shown(markdown)) +} + +#[test] +fn an_ordered_list_counts_from_its_start() { + let words = painted("3. trois\n4. quatre"); + + assert!(words.contains(&"3.".to_owned()) && words.contains(&"4.".to_owned()), "{words:?}"); +} + +#[test] +fn a_task_is_named_by_its_text_or_by_its_place() { + let harness = shown("- [x] fait\n- [ ] "); + let tasks: Vec<(String, bool)> = harness + .query_all_by(|node| node.author_id() == Some("rich-task")) + .map(|node| { + let node = node.accesskit_node(); + let checked = node.toggled() == Some(egui::accesskit::Toggled::True); + (node.label().unwrap_or_default(), checked) + }) + .collect(); + + assert_eq!(tasks, [("fait".to_owned(), true), ("2".to_owned(), false)]); +} + +#[test] +fn a_block_of_code_names_its_language_in_its_corner() { + assert!(painted("```rust\nlet a = 1;\n```").contains(&"rust".to_owned())); + let bare = painted("```\nlet a = 1;\n```"); + assert_eq!(bare, ["let a = 1;"]); +} + +#[test] +fn another_image_than_a_drawing_is_written_as_it_was() { + assert!(painted("![alt](https://a.fr/b.png)").contains(&"![alt](https://a.fr/b.png)".to_owned())); + let drawing = painted("![Le plan](devnotes:drawing/abc)"); + assert!(drawing.contains(&"Le plan".to_owned()), "{drawing:?}"); +} + +// Edited + +/// What the frames of an editor answered, over `markdown`. +fn edited(markdown: &str) -> egui_kittest::Harness<'static, Painted> { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness().with_size(vec2(700.0, 900.0)).build_ui_state( + move |ui, painted: &mut Painted| { + let now = RichView::new(&document).editing(&selection).show(ui); + painted.ticked = now.ticked.or(painted.ticked.take()); + painted.picked = now.picked.or(painted.picked.take()); + painted.leaves = now.leaves; + painted.images = now.images; + painted.wanted = now.wanted; + }, + Painted::default(), + ); + harness.run(); + harness +} + +fn click_at(harness: &mut egui_kittest::Harness<'_, Painted>, at: Pos2) { + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false] { + harness.event(egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }); + } + harness.run(); +} + +/// In the document's order, whatever holds them. +#[test] +fn each_leaf_is_answered_with_its_path() { + let harness = + edited("# t\n\n- a\n - b\n\n> c\n>\n> - d\n\n| e | f |\n| --- | --- |\n| g | h |\n\n```\ni\n```"); + let leaves: Vec<(String, Vec)> = harness + .state() + .leaves + .iter() + .map(|leaf| (leaf.galley.text().to_owned(), leaf.path.clone())) + .collect(); + let expected = [ + ("t", vec![0]), + ("a", vec![1, 0, 0]), + ("b", vec![1, 0, 1, 0, 0]), + ("c", vec![2, 0]), + ("d", vec![2, 1, 0, 0]), + ("e", vec![3, 0, 0]), + ("f", vec![3, 0, 1]), + ("g", vec![3, 1, 0]), + ("h", vec![3, 1, 1]), + ("i", vec![4]), + ]; + + assert_eq!(leaves, expected.map(|(text, path)| (text.to_owned(), path))); +} + +#[test] +fn a_task_s_box_clicked_says_which_one() { + let mut harness = edited("texte\n\n- [ ] a\n- [ ] b"); + let boxes: Vec = harness + .query_all_by(|node| node.author_id() == Some("rich-task")) + .map(|node| node.rect()) + .collect(); + click_at(&mut harness, boxes[1].center()); + + assert_eq!(harness.state().ticked, Some((vec![1], 1))); +} + +#[test] +fn read_a_task_s_box_does_not_take_the_click() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, ticked: &mut bool| { + let document = richtext::read("- [ ] a"); + *ticked |= RichView::new(&document).show(ui).ticked.is_some(); + }, + false, + ); + harness.run(); + harness.get_by(|node| node.author_id() == Some("rich-task")).click(); + harness.run(); + + assert!(!harness.state()); +} + +#[test] +fn an_image_clicked_is_picked_and_each_is_answered_where_it_is() { + let mut harness = edited("a\n\n![x](devnotes:drawing/one)\n\n![y](devnotes:drawing/two)"); + let paths: Vec> = harness.state().images.iter().map(|image| image.path.clone()).collect(); + assert_eq!(paths, [vec![1], vec![2]]); + + let at = harness.state().images[1].rect.center(); + click_at(&mut harness, at); + assert_eq!(harness.state().picked, Some(vec![2])); +} + +// A drawing embedded + +/// The drawing as its `pictures` say it, in a room 400 px wide. +fn embedding(markdown: &'static str, size: [usize; 2]) -> egui_kittest::Harness<'static, Vec> { + let document = richtext::read(markdown); + let mut harness = crate::testing::harness().with_size(vec2(800.0, 900.0)).build_ui_state( + move |ui, wanted: &mut Vec| { + ui.set_width(400.0); + let pixels = egui::ColorImage::filled(size, Color32::WHITE); + let texture = ui.ctx().load_texture("drawing", pixels, egui::TextureOptions::LINEAR); + let pictures = move |id: &str| match id { + "shown" => Some(Embedded::Shown(texture.clone())), + "waiting" => Some(Embedded::Waiting), + "gone" => Some(Embedded::Missing), + _ => None, + }; + let painted = RichView::new(&document).pictures(&pictures, "Dessin introuvable").show(ui); + *wanted = painted.wanted; + }, + Vec::new(), + ); + harness.step(); + harness +} + +fn embeds(harness: &egui_kittest::Harness<'_, State>) -> Vec { + harness + .query_all_by(|node| node.author_id() == Some("rich-embed")) + .map(|node| node.rect()) + .collect() +} + +#[test] +fn a_picture_never_asked_for_is_wanted_and_one_coming_is_not() { + for (markdown, wanted) in [ + ("![a](devnotes:drawing/new)", vec!["new".to_owned()]), + ("![a](devnotes:drawing/waiting)", Vec::new()), + ("![a](devnotes:drawing/shown)", Vec::new()), + ("![a](https://a.fr/b.png)", Vec::new()), + ] { + assert_eq!(*embedding(markdown, [100, 50]).state(), wanted, "{markdown}"); + } +} + +#[test] +fn a_drawing_gone_is_said() { + let words = crate::testing::painted(&embedding("![a](devnotes:drawing/gone)", [100, 50])); + + assert!(words.contains(&"Dessin introuvable".to_owned()), "{words:?}"); +} + +/// At its own size, never wider than the text; given a width, a part of the text's. +#[test] +fn a_drawing_is_drawn_at_its_width_and_keeps_its_shape() { + for (markdown, natural, drawn) in [ + ("![a](devnotes:drawing/shown)", [100, 50], vec2(100.0, 50.0)), + ("![a](devnotes:drawing/shown)", [800, 400], vec2(400.0, 200.0)), + ("![a](devnotes:drawing/shown?w=50)", [100, 50], vec2(200.0, 100.0)), + ] { + let harness = embedding(markdown, natural); + let rects = embeds(&harness); + assert_eq!(rects.len(), 1, "{markdown}"); + assert!((rects[0].size() - drawn).length() < 1.0, "{markdown}: {:?}", rects[0].size()); + } +} + +// A slide + +fn slide_rects(markdown: &'static str) -> Vec { + let document = richtext::read(markdown); + let selection = Selection::default(); + let mut harness = crate::testing::harness().with_size(vec2(1_000.0, 900.0)).build_ui_state( + move |ui, leaves: &mut Vec| { + *leaves = RichView::new(&document).slide(300.0, 2.0).editing(&selection).show(ui).leaves; + }, + Vec::new(), + ); + harness.run(); + std::mem::take(harness.state_mut()) +} + +#[test] +fn a_slide_s_text_is_no_wider_than_it_reads() { + let leaves = slide_rects("un texte assez long pour faire plus d’une ligne sur la largeur donnée"); + + assert!(leaves[0].galley.size().x <= 300.0); + assert!(leaves[0].galley.rows.len() > 1); +} + +#[test] +fn a_slide_s_title_has_its_own_scale() { + let leaves = slide_rects("# Titre\n\n# Autre"); + let heights: Vec = leaves.iter().map(|leaf| leaf.galley.size().y).collect(); + + assert!(heights[0] > 1.8 * heights[1], "{heights:?}"); +} + +#[test] +fn a_slide_s_code_is_centred_at_its_own_width() { + let leaves = slide_rects("```\ncourt\n```"); + + assert!(leaves[0].origin.x > 300.0, "{:?}", leaves[0].origin); +} + +// The marks under the text + +fn filled(found: &'static [Found], selection: &'static Selection) -> Vec { + let document = richtext::read("un deux\n\ntrois"); + let mut harness = crate::testing::harness().with_size(vec2(700.0, 300.0)).build_ui(move |ui| { + RichView::new(&document).found(found).editing(selection).show(ui); + }); + harness.run(); + harness + .output() + .shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Rect(rect) if rect.fill != Color32::TRANSPARENT && rect.rect.height() < 60.0 => { + Some(rect.rect) + } + _ => None, + }) + .collect() +} + +#[test] +fn a_match_is_lit_where_it_is() { + let none = Box::leak(Box::new(Selection::default())); + let bare = filled(&[], none).len(); + let found: &'static [Found] = Box::leak(Box::new([(vec![0], 3..7), (vec![1], 0..5), (vec![9], 0..1)])); + + assert_eq!(filled(found, none).len() - bare, 2); +} + +/// Over both ends' leaves, and the line end of the first. +#[test] +fn a_selection_across_two_paragraphs_is_lit_in_both() { + let none = Box::leak(Box::new(Selection::default())); + let bare = filled(&[], none).len(); + let position = |leaf: usize, offset| richtext::Position { path: vec![leaf], offset }; + let across = Box::leak(Box::new(Selection { anchor: position(1, 2), head: position(0, 3) })); + let lit = filled(&[], across); + + assert_eq!(lit.len() - bare, 2); +} diff --git a/crates/ui/src/widgets/segmented.rs b/crates/ui/src/widgets/segmented.rs index e0759976b..20561c44d 100644 --- a/crates/ui/src/widgets/segmented.rs +++ b/crates/ui/src/widgets/segmented.rs @@ -3,9 +3,7 @@ //! refuse, and this one is read at 11.5 px. use crate::theme::tokens::{font, radius}; -use egui::{ - Color32, CornerRadius, FontFamily, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo, -}; +use egui::{Color32, CornerRadius, FontFamily, Response, Role, Sense, Stroke, Ui, Vec2, WidgetInfo}; use super::{hovered, interact, text, towards}; use crate::theme::palette; @@ -18,11 +16,7 @@ pub struct Segmented<'a, T> { impl<'a, T: PartialEq + Copy> Segmented<'a, T> { pub fn new(options: &'a [(T, &'a str)], author_id: &'a str) -> Self { - Self { - options, - author_id, - taken: None, - } + Self { options, author_id, taken: None } } /// The segment that cannot be chosen: dimmed, and a click on it does nothing. @@ -38,17 +32,10 @@ impl<'a, T: PartialEq + Copy> Segmented<'a, T> { self.options .iter() .map(|(_, label)| { - text( - ui, - label, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ) - .size() - .x - .max(super::MIN_TARGET - 20.0) + text(ui, label, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2) + .size() + .x + .max(super::MIN_TARGET - 20.0) + 20.0 }) .sum::() @@ -61,8 +48,7 @@ impl<'a, T: PartialEq + Copy> Segmented<'a, T> { let width = self.width(ui); // ⚠️ Its place taken at once: a frame sits at the top of its row and a child centred on // a height of nothing runs below it, so the control landed lower than its neighbours. - let (rect, _) = - ui.allocate_exact_size(Vec2::new(width, super::MIN_TARGET + 2.0), Sense::hover()); + let (rect, _) = ui.allocate_exact_size(Vec2::new(width, super::MIN_TARGET + 2.0), Sense::hover()); ui.painter().rect( rect, CornerRadius::same(radius::CONTROL), @@ -72,9 +58,7 @@ impl<'a, T: PartialEq + Copy> Segmented<'a, T> { ); // In its order at the end of a row too: `horizontal` follows the parent's way. let reading = egui::Layout::left_to_right(egui::Align::Center); - let inside = egui::UiBuilder::new() - .max_rect(rect.shrink(1.0)) - .layout(reading); + let inside = egui::UiBuilder::new().max_rect(rect.shrink(1.0)).layout(reading); let changed = ui.scope_builder(inside, |ui| { ui.spacing_mut().item_spacing.x = 0.0; let mut changed = None; @@ -100,14 +84,7 @@ impl<'a, T: PartialEq + Copy> Segmented<'a, T> { fn segment(ui: &mut Ui, label: &str, author_id: &str, (on, open): (bool, bool)) -> Response { let p = palette(ui.ctx()); - let probe = text( - ui, - label, - font::CONTROL, - 400.0, - FontFamily::Proportional, - p.text_2, - ); + let probe = text(ui, label, font::CONTROL, 400.0, FontFamily::Proportional, p.text_2); let corner = CornerRadius::same(radius::CONTROL); let response = interact( ui, @@ -127,18 +104,8 @@ fn segment(ui: &mut Ui, label: &str, author_id: &str, (on, open): (bool, bool)) if on { ui.painter().rect_filled(response.rect, corner, p.bg_3); } - let galley = text( - ui, - label, - font::CONTROL, - 400.0, - FontFamily::Proportional, - ink, - ); - ui.painter().galley( - response.rect.center() - galley.size() / 2.0, - galley, - Color32::TRANSPARENT, - ); + let galley = text(ui, label, font::CONTROL, 400.0, FontFamily::Proportional, ink); + ui.painter() + .galley(response.rect.center() - galley.size() / 2.0, galley, Color32::TRANSPARENT); response } diff --git a/crates/ui/src/widgets/split.rs b/crates/ui/src/widgets/split.rs index f01816626..4f272092a 100644 --- a/crates/ui/src/widgets/split.rs +++ b/crates/ui/src/widgets/split.rs @@ -2,8 +2,8 @@ //! in two by a hairline. use egui::{ - Align, Color32, CornerRadius, FontFamily, FontId, Layout, Popup, Pos2, Rect, Response, Role, - Sense, Stroke, StrokeKind, Ui, UiBuilder, Vec2, WidgetInfo, + Align, Color32, CornerRadius, FontFamily, FontId, Layout, Popup, Pos2, Rect, Response, Role, Sense, + Stroke, StrokeKind, Ui, UiBuilder, Vec2, WidgetInfo, }; use super::{interact, text}; @@ -58,15 +58,7 @@ const ICON: f32 = 14.0; impl<'a> SplitButton<'a> { /// Each half as its label and its `author_id`. pub fn new(main: (&'a str, &'a str), more: (&'a str, &'a str), kind: SplitKind) -> Self { - Self { - main, - more, - kind, - icon: None, - keys: None, - named: true, - enabled: true, - } + Self { main, more, kind, icon: None, keys: None, named: true, enabled: true } } #[must_use] @@ -109,18 +101,7 @@ impl<'a> SplitButton<'a> { let (whole, _) = ui.allocate_exact_size(size, Sense::hover()); let (left, right) = whole.split_left_right_at_x(whole.right() - measures.arrow); let round = CornerRadius::same(measures.corner); - let corners = [ - CornerRadius { - ne: 0, - se: 0, - ..round - }, - CornerRadius { - nw: 0, - sw: 0, - ..round - }, - ]; + let corners = [CornerRadius { ne: 0, se: 0, ..round }, CornerRadius { nw: 0, sw: 0, ..round }]; let main = half(ui, left, self.main, (self.enabled, corners[0])); let more = half(ui, right, self.more, (true, corners[1])); let opened = Popup::is_id_open(ui.ctx(), Popup::default_response_id(&more)); @@ -170,15 +151,9 @@ impl<'a> SplitButton<'a> { let (size, weight) = self.measures().label; let family = FontFamily::Proportional; let icon = self.icon.map(|_| ICON); - let label = self - .named - .then(|| text(ui, self.main.0, size, weight, family, Color32::WHITE)); + let label = self.named.then(|| text(ui, self.main.0, size, weight, family, Color32::WHITE)); let keys = self.shown_keys().map(|keys| keys_text(ui, keys)); - let parts = [ - icon, - label.map(|galley| galley.size().x), - keys.map(|galley| galley.size().x), - ]; + let parts = [icon, label.map(|galley| galley.size().x), keys.map(|galley| galley.size().x)]; let parts: Vec = parts.into_iter().flatten().collect(); let between = parts.len().saturating_sub(1); #[expect(clippy::cast_precision_loss, reason = "three parts at most")] @@ -195,8 +170,7 @@ impl<'a> SplitButton<'a> { let mut left = rect.center().x - self.content_width(ui) / 2.0; let middle = rect.center().y; if let Some(icon) = self.icon { - let glyph = - Rect::from_min_size(Pos2::new(left, middle - ICON / 2.0), Vec2::splat(ICON)); + let glyph = Rect::from_min_size(Pos2::new(left, middle - ICON / 2.0), Vec2::splat(ICON)); icons::paint(ui, glyph, icon, ink); left += ICON + BETWEEN; } @@ -219,40 +193,29 @@ impl<'a> SplitButton<'a> { let p = palette(ui.ctx()); match self.kind { SplitKind::Primary => Colours { - fill: p - .amber_fill - .gamma_multiply(if hovered { 1.08 } else { 1.0 }), + fill: p.amber_fill.gamma_multiply(if hovered { 1.08 } else { 1.0 }), edge: Color32::TRANSPARENT, ink: p.amber_ink, }, - SplitKind::Neutral => Colours { - fill: p.bg_2, - edge: if hovered { p.amber_dim } else { p.line_soft }, - ink: p.text_1, - }, + SplitKind::Neutral => { + Colours { fill: p.bg_2, edge: if hovered { p.amber_dim } else { p.line_soft }, ink: p.text_1 } + } SplitKind::Tint if hovered || opened => Colours { fill: p.amber_fill.gamma_multiply(0.2), edge: p.amber_edge, ink: if hovered { p.text_0 } else { p.amber_text }, }, - SplitKind::Tint if enabled => Colours { - fill: p.amber_fill.gamma_multiply(0.12), - edge: p.amber_dim, - ink: p.amber_text, - }, - SplitKind::Tint => Colours { - fill: Color32::TRANSPARENT, - edge: p.line_soft, - ink: p.text_2, - }, + SplitKind::Tint if enabled => { + Colours { fill: p.amber_fill.gamma_multiply(0.12), edge: p.amber_dim, ink: p.amber_text } + } + SplitKind::Tint => Colours { fill: Color32::TRANSPARENT, edge: p.line_soft, ink: p.text_2 }, } } } fn keys_text(ui: &Ui, keys: &str) -> std::sync::Arc { let font = FontId::monospace(font::BADGE); - ui.painter() - .layout_no_wrap(keys.to_owned(), font, palette(ui.ctx()).text_2) + ui.painter().layout_no_wrap(keys.to_owned(), font, palette(ui.ctx()).text_2) } fn half( @@ -261,16 +224,8 @@ fn half( (label, author_id): (&str, &str), (enabled, corner): (bool, CornerRadius), ) -> Response { - let sense = if enabled { - Sense::click() - } else { - Sense::hover() - }; - let mut place = ui.new_child( - UiBuilder::new() - .max_rect(rect) - .layout(Layout::left_to_right(Align::Min)), - ); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let mut place = ui.new_child(UiBuilder::new().max_rect(rect).layout(Layout::left_to_right(Align::Min))); let info = || WidgetInfo::labeled(Role::Button, enabled, label); interact(&mut place, rect.size(), sense, author_id, info, corner) } diff --git a/crates/ui/src/widgets/tests.rs b/crates/ui/src/widgets/tests.rs index a884d0b51..ff2c88fec 100644 --- a/crates/ui/src/widgets/tests.rs +++ b/crates/ui/src/widgets/tests.rs @@ -22,11 +22,7 @@ fn bench() -> Harness<'static, Bench> { crate::testing::harness().build_ui_state( |ui, bench: &mut Bench| { crate::theme::motion::set_reduced(ui.ctx(), true); - if Button::new("Enregistrer", "save") - .kind(Kind::Filled) - .show(ui) - .clicked() - { + if Button::new("Enregistrer", "save").kind(Kind::Filled).show(ui).clicked() { bench.clicks += 1; } Button::new("Supprimer", "delete") @@ -34,22 +30,15 @@ fn bench() -> Harness<'static, Bench> { .armed(bench.armed) .show(ui); Button::new("Plus tard", "later").enabled(false).show(ui); - IconButton::new(Icon::Trash, "Corbeille", "trash") - .keys("Suppr") + IconButton::new(Icon::Trash, "Corbeille", "trash").keys("Suppr").show(ui); + SplitButton::new(("Exporter", "export"), ("Autres formats", "export-more"), SplitKind::Neutral) .show(ui); - SplitButton::new( - ("Exporter", "export"), - ("Autres formats", "export-more"), - SplitKind::Neutral, - ) - .show(ui); SquareButton::new(Icon::Sidebar, "Masquer le rail", "rail-toggle") .pressed(true) .show(ui); Chip::new("psql", "tag-chip", true).show(ui); Checkbox::new(&mut bench.checked, "Fait", "item-done").show(ui); - Segmented::new(&[(0, "Confortable"), (1, "Compacte")], "density") - .show(ui, &mut bench.density); + Segmented::new(&[(0, "Confortable"), (1, "Compacte")], "density").show(ui, &mut bench.density); TextField::new(&mut bench.typed, "Nom", "name-field") .hint("Nom de la bibliothèque") .show(ui); @@ -85,11 +74,7 @@ fn every_control_is_named_and_addressed() { ] { let node = harness.get_by(|node| node.author_id() == Some(author_id)); assert_eq!(node.accesskit_node().role(), role, "{author_id}"); - assert_eq!( - node.accesskit_node().label().as_deref(), - Some(name), - "{author_id}" - ); + assert_eq!(node.accesskit_node().label().as_deref(), Some(name), "{author_id}"); } } @@ -115,12 +100,8 @@ fn a_click_acts_and_a_disabled_button_does_not() { let mut harness = bench(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("save")) - .click(); - harness - .get_by(|node| node.author_id() == Some("later")) - .click(); + harness.get_by(|node| node.author_id() == Some("save")).click(); + harness.get_by(|node| node.author_id() == Some("later")).click(); harness.run(); assert_eq!(harness.state().clicks, 1); @@ -133,21 +114,14 @@ fn a_checkbox_and_a_segment_change_their_value() { let mut harness = bench(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("item-done")) - .click(); - harness - .get_by(|node| node.author_id() == Some("density-1")) - .click(); + harness.get_by(|node| node.author_id() == Some("item-done")).click(); + harness.get_by(|node| node.author_id() == Some("density-1")).click(); harness.run(); assert!(harness.state().checked); assert_eq!(harness.state().density, 1); let on = harness.get_by(|node| node.author_id() == Some("density-1")); - assert_eq!( - on.accesskit_node().toggled(), - Some(egui::accesskit::Toggled::True) - ); + assert_eq!(on.accesskit_node().toggled(), Some(egui::accesskit::Toggled::True)); } #[test] @@ -155,9 +129,7 @@ fn a_field_takes_what_is_typed() { let mut harness = bench(); harness.run(); - harness - .get_by(|node| node.author_id() == Some("name-field")) - .click(); + harness.get_by(|node| node.author_id() == Some("name-field")).click(); harness.run(); harness .get_by(|node| node.author_id() == Some("name-field")) @@ -174,10 +146,9 @@ fn look() { let Some(directory) = std::env::var_os("DEVNOTES_LOOK") else { return; }; - for (name, theme) in [ - ("dark", crate::theme::Appearance::Dark), - ("light", crate::theme::Appearance::Light), - ] { + for (name, theme) in + [("dark", crate::theme::Appearance::Dark), ("light", crate::theme::Appearance::Light)] + { let mut harness = bench(); crate::theme::apply(&harness.ctx, theme, crate::theme::Density::Comfortable); harness.set_size(egui::vec2(420.0, 620.0)); @@ -193,36 +164,133 @@ fn look() { fn says(harness: &Harness<'_, Bench>, words: &str) -> bool { harness .query_all_by(|_| true) - .filter_map(|node| { - node.accesskit_node() - .label() - .or(node.accesskit_node().value()) - }) + .filter_map(|node| node.accesskit_node().label().or(node.accesskit_node().value())) .any(|said| said == words) } #[test] fn an_icon_alone_says_its_name_and_its_keys_on_hover() { let mut harness = bench(); - harness - .ctx - .all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); + harness.ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0); harness.run(); assert!(!says(&harness, "Corbeille · Suppr")); - harness - .get_by(|node| node.author_id() == Some("trash")) - .hover(); + harness.get_by(|node| node.author_id() == Some("trash")).hover(); for _ in 0..10 { harness.step(); } assert!(says(&harness, "Corbeille · Suppr")); - harness - .get_by(|node| node.author_id() == Some("rail-toggle")) - .hover(); + harness.get_by(|node| node.author_id() == Some("rail-toggle")).hover(); for _ in 0..10 { harness.step(); } assert!(says(&harness, "Masquer le rail")); } + +// One control at a time + +/// What `draw` paints, as circles and filled rectangles. +fn colours(draw: impl Fn(&mut egui::Ui) + 'static) -> Vec { + let mut harness = crate::testing::harness().build_ui(move |ui| draw(ui)); + harness.run(); + let shapes = &harness.output().shapes; + shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Circle(circle) => Some(circle.fill), + egui::Shape::Rect(rect) => Some(rect.fill), + _ => None, + }) + .collect() +} + +#[test] +fn each_priority_has_its_dot_s_colour() { + use engine::notes::priority::Priority; + let p = crate::theme::palette(&egui::Context::default()); + for (priority, colour) in [ + (Priority::None, p.line_no), + (Priority::Low, p.text_2), + (Priority::Medium, p.blue), + (Priority::High, p.amber_text), + (Priority::Urgent, p.red), + ] { + let drawn = colours(move |ui| { + priority_dot(ui, priority); + }); + assert!(drawn.contains(&colour), "{priority:?}"); + } +} + +#[test] +fn a_segment_taken_elsewhere_cannot_be_chosen() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, chosen: &mut u8| { + Segmented::new(&[(0, "A"), (1, "B"), (2, "C")], "side") + .taken(1) + .show(ui, chosen); + }, + 0, + ); + harness.run(); + harness.get_by_label("B").click(); + harness.run(); + assert_eq!(*harness.state(), 0); + harness.get_by_label("C").click(); + harness.run(); + assert_eq!(*harness.state(), 2); +} + +#[test] +fn a_question_asked_in_place_answers_what_was_pressed() { + let mut harness = crate::testing::harness().build_ui_state( + |ui, (asked, pressed): &mut (bool, Option)| { + let question = asked.then_some("Supprimer 3 notes ?"); + let words = ("Supprimer", "Annuler"); + if let Some(now) = ask_in_place(ui, words, question, true, "delete") { + *pressed = Some(now); + *asked = now == InPlace::Ask; + } + }, + (false, None), + ); + harness.run(); + for (control, pressed) in [ + ("delete", InPlace::Ask), + ("delete-cancel", InPlace::Cancel), + ("delete", InPlace::Ask), + ("delete-confirm", InPlace::Confirm), + ] { + harness.get_by(|node| node.author_id() == Some(control)).click(); + harness.run(); + assert_eq!(harness.state().1, Some(pressed), "{control}"); + } +} + +/// In the middle of its room, or near the top of one that has no end. +#[test] +fn an_empty_place_says_so_and_offers_its_actions() { + for (height, within) in [(400.0, 150.0..250.0), (f32::INFINITY, 20.0..120.0)] { + let mut harness = crate::testing::harness().with_size(egui::vec2(600.0, 500.0)).build_ui_state( + move |ui, clicked: &mut Option| { + let room = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(600.0, height)); + let actions = [ + EmptyAction { label: "Créer", author_id: "create", primary: true }, + EmptyAction { label: "Importer", author_id: "import", primary: false }, + ]; + if let Some(rank) = empty_state(ui, room, ("Rien ici", "empty"), &actions) { + *clicked = Some(rank); + } + }, + None, + ); + harness.run(); + let top = harness.get_by(|node| node.author_id() == Some("empty")).rect().top(); + assert!(within.contains(&top), "{height}: {top}"); + + harness.get_by(|node| node.author_id() == Some("import")).click(); + harness.run(); + assert_eq!(*harness.state(), Some(1)); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index d96205d3e..21d5d1517 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -374,13 +374,13 @@ evidence now, not proof; a unit or a custom property is what makes it a styleshe ### Formatting a snippet with Prettier -"Formater" (Shift+Alt+F) runs Prettier itself — 3.9.10, as `package.json` pins it — on the +"Formater" (Shift+Alt+F) runs Prettier itself — 3.9.10, as `scripts/prettier.mjs` pins it — on the editor's draft, **in QuickJS** (D1): `golden/format` holds its answers, byte for byte. `text::format` holds all of it; the editor asks through `FormattingState`, on `compute`. - **One host, started by the first format and kept** (`text::format::host`): a thread of its own with one QuickJS runtime — a runtime is not shared between threads — in which - `standalone.js` and nine plugins are evaluated once. `npm run prettier` copies them into + `standalone.js` and nine plugins are evaluated once. `node scripts/prettier.mjs` copies them into `crates/text/prettier/` after a bump; they are compiled in (2.4 MB). A host that cannot start answers every format `Failed`. - **Only text crosses**: the draft, the caret and Prettier's options, never code. The answer is @@ -1389,7 +1389,8 @@ and exporting write a Note as the Markdown it is, where a snippet is fenced. a test) and written back byte for byte, as `golden/markdown` and `golden/markdown-escape` hold. What the schema does not hold is read as what it shows: raw HTML as its text, a footnote as its brackets, a reference link inline, a bare `https://` - address as a link to itself. `richtext::escape` is `escapeMarkdownText`, ported rule for rule. + address as a link to itself. A cell and a heading hold one line: their breaks are `
`. + `richtext::escape` is `escapeMarkdownText`, ported rule for rule. Undo keeps the document and the selection before each transaction (`History`): a Note is a few kilobytes. - **Editing is `richtext::edit`'s**, the view `overlays/editor/rich.rs`'s. A caret is a path to a @@ -2104,7 +2105,7 @@ _and_ in what is being edited, the rest of the draft untouched. The other way, a tree again, since the rail shows the name and the method. Renaming a folder or a collection bumps `settingsRevision`: its name is in what its requests inherit « from ». -- **The query and its table are kept in step by Rust** (`sync_http_query`, `http/query.rs`): +- **The query and its table are kept in step by Rust** (`query::sync`, `http/query.rs`): the side that was edited wins, nothing is decoded — `{{page}}` and `%20` read back as typed — a disabled row stays in the table and out of the URL, and a description follows its key. The answer is applied only if nothing was typed meanwhile. @@ -2131,9 +2132,9 @@ bumps `settingsRevision`: its name is in what its requests inherit « from ». The rule is the model's (`http::model::header_fault`): a name is an HTTP token, a value holds no line break nor control character, a `{{variable}}` stands for a letter until it is filled, and a row switched off is not judged. Three places apply it: - - `KeyValueTableComponent` as `headers` asks `check_http_headers` and marks the row, with the + - `KeyValueTableComponent` as `headers` asks `model::header_faults` and marks the row, with the reason under the table; a parameter or a form field takes any character and is asked - nothing. `Nom: valeur` typed in a name is split by `read_http_headers` — what follows the + nothing. `Nom: valeur` typed in a name is split by `model::headers_from_text` — what follows the first colon goes to the value when there is none, and the caret with it — and several lines pasted there fill a row each (the field alone would take them on one line). ⚠️ Every change starts from `latest`, what the table last emitted, not from its `rows` input: the input @@ -2479,7 +2480,7 @@ their kind. Names are compared in Rust, case aside (`duplicateEnvironmentName`); named by the front and sits right after its original, secrets included. - **A variable is a name, a value and a type** — Text, Number, Secret. A table keeps its rows - as typed; `check_http_variables` answers each row's fault (a name a `{{…}}` cannot hold, + as typed; `environments::variable_faults` answers each row's fault (a name a `{{…}}` cannot hold, one set twice in the table, a number that does not read), the table marks it and says why, as the headers' table does. A secret's value is a password field, shown one row at a time. - **The page is the workspace's, as the history is** (`HttpWorkspaceStore.page`: requests, @@ -2808,7 +2809,7 @@ its path from the top of the space on hover (`NoteFolder.path`). the global `{{field}}` defaults — one pass that `query_notes`, `board_view` and every single-note answer run, where there used to be three. `notes::store::decorations` reads the counters and the globals; which chips a card keeps is the view's: none for the folder opened, -whose breadcrumb names it (`NotesQuery::keeps_chip`), none for the zone a card sits in on the +whose breadcrumb names it (`view::keeps_chip`), none for the zone a card sits in on the board (`BoardView::keep_chips_from_below`) — a card from a sub-folder says which. The front end never joins a `folderId` against a list it happens to hold. ⚠️ The chip is a **square swatch on a neutral pill** — never a coloured pill, which is what a tag is. A note with no folder gets no chip at @@ -2885,7 +2886,7 @@ visible ground, or every gesture stops at the content's edge on a large window w dotted ground beyond it looks exactly the same (#320). **Pan only, no zoom** — a zoom is a second thing to persist and to reset, and full-size cards are what makes panning worth having. -⚠️ A card that has never been placed takes `free_slot` — the first seat of that flow nothing +⚠️ A card that has never been placed takes `free_slot_from` — the first seat of that flow nothing is standing on — and never the seat its index in the list would give it. A note created now is the most recently updated, so it arrives first and used to be written on top of whichever card the board's very first read had put there. "Standing on" is a rectangle test against the @@ -3306,8 +3307,8 @@ they do **not** travel inside `Note`, which would reload the whole note on every ### The trash, and undoing a deletion -Deleting is **not** destroying. `delete_note` stamps `deleted_at` and the note leaves the -canvas; `notes::trash::RETENTION` (30 days) then decides when it really goes. Three +Deleting is **not** destroying. `delete_notes` stamps `deleted_at` and the notes leave the +canvas; `notes::trash::RETENTION` (30 days) then decides when they really go. Three consequences: - **Every read filters on `deleted_at IS NULL`** — `fetch`, `find`, the facet queries and @@ -3431,8 +3432,8 @@ at — the placements the notes left, the `(note, tag)` pairs actually inserted. `move_notes_back` and `untag_notes` undo, exactly and nothing wider. It also fixed a count that had always overstated itself: `tag_many` used to report every live note in the selection, including the ones already carrying the tag, which `INSERT OR IGNORE` had quietly skipped. -Those notes no longer have `updated_at` refreshed either, for the same reason — nothing about -them changed. +None of them has `updated_at` refreshed: moving, filing and tagging a selection is not editing +it, and « Undo » after any of them leaves a list sorted by modification as it was. ⚠️ Which notes "already carry the tag" is decided in SQL, before the insert, by the same comparison the insert will make: `note_tags.tag` is `COLLATE NOCASE`, and SQLite's `NOCASE` @@ -3452,7 +3453,7 @@ no date; its undo is the same call the other way over those. The selection bar, the `P` key and the editor all go through it (`NotesStore.setPinned`, a batch of one with its undo); only a draft takes its pin as a field. The bar's one button pins what is ticked, or unpins it once all of it is pinned. **A tag is taken off** by `remove_tag(ids, tag)`, which answers the -pairs as stored and moves `updated_at` like tagging; `restore_tags` puts back exactly those. +pairs as stored and leaves `updated_at` like tagging; `restore_tags` puts back exactly those. The bar offers the tags the ticked notes carry (`NoteSelectionStore.checkedTags`). **On screen, a priority is said three ways**: a pill on the card (`PriorityPillComponent`, in @@ -3479,7 +3480,7 @@ as a field is decided in `notes::placeholder` and nowhere else: the name is rest into a form on every copy. Values arrive parsed on `DisplayNote.placeholders`, and `fill_placeholders` — a pure command, no database — does the substitution. -**The code marks them where they are written**, from Rust too: `field_spans` answers each +**The code marks them where they are written**, from Rust too: `placeholder::spans` answers each token's range and its default's, in UTF-16 units — the editor's offsets — from the same `scan` that `parse` and `fill` walk. `FieldMarksStore` asks 250 ms after the typing pauses and keeps the text an answer was found in; the code field (`code-editor/field-marks.ts`) marks only that @@ -3839,11 +3840,6 @@ render — exactly the second one uses it from another application. They are dec though: `ShortcutBindings::defaults()` crosses as the `DEFAULT_SHORTCUTS` constant, next to `GLOBAL_ACTION_EVENT` and `APP_METADATA`, and the front re-exports it rather than retyping it. -The same treatment closes the other mirror: `notes::placeholder` exports `FIELD_NAME_PATTERN`, -and `isVariableName` builds its `RegExp` from it. ⚠️ Rust checks characters rather than -matching a regex, so the pattern and `is_field_name` are held together by one test — -`the_pattern_and_the_rule_agree` — and by nothing else. - `AutostartService` reads the system **first** and aligns the preference on what it finds: turning the entry off from the task manager has to uncheck the box, not see DevNotes put it back. @@ -4978,19 +4974,19 @@ Detection reads the content and returns one of the languages; without it every n The service functions, grouped by the feature that owns them (`crates/engine/src/.rs`): -| Feature | Functions | -| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `notes` | `count_notes_tagged`, `create_note`, `delete_note`, `delete_notes`, `delete_tags`, `empty_trash`, `fill_placeholders`, `get_note`, `list_global_placeholders`, `list_revisions`, `list_tags`, `list_trash`, `move_notes`, `move_notes_back`, `purge_notes`, `query_notes`, `rename_tags`, `restore_notes`, `restore_revision`, `revision_diff`, `seed_samples`, `set_global_placeholders`, `set_placeholder_values`, `tag_notes`, `untag_notes`, `update_note` | -| `spaces` | `count_space_contents`, `create_space`, `delete_space`, `list_spaces`, `pin_space`, `rename_space` | -| `folders` | `arrange_board`, `board_view`, `count_folder_contents`, `create_folder`, `delete_folder`, `file_notes`, `file_notes_back`, `list_folders`, `recolour_folder`, `rename_folder`, `save_board_layout` | -| `attachments` | `attach_clipboard_image`, `attach_file`, `delete_attachment`, `list_attachments`, `open_attachment`, `read_attachment`, `save_attachment` | -| `transfer` | `count_export`, `export_is_protected`, `export_notes` (over an `ExportScope`: the library, a space or a selection), `import_notes`, `share_notes` | -| `vault` | `change_passphrase`, `create_vault`, `unlock_vault`, `vault_state` | -| `libraries` | `create_library`, `delete_library`, `list_libraries`, `open_library`, `rename_library` | -| `backup` | `list_backups`, `restore_backup` | -| `recovery` | `archive_locked_library`, `set_aside_damaged_library` | -| `changelog` | `app_changelog` | -| `desktop` | `hold_quit`, `set_global_shortcuts`, `release_global_shortcuts`, `set_window_behavior`, `sync_tray` | +| Feature | Functions | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `notes` | `count_notes_tagged`, `create_note`, `delete_notes`, `delete_tags`, `empty_trash`, `fill_placeholders`, `get_note`, `list_global_placeholders`, `list_revisions`, `list_tags`, `list_trash`, `move_notes`, `move_notes_back`, `purge_notes`, `query_notes`, `rename_tags`, `restore_notes`, `restore_revision`, `revision_diff`, `seed_samples`, `set_global_placeholders`, `set_placeholder_values`, `tag_notes`, `untag_notes`, `update_note` | +| `spaces` | `count_space_contents`, `create_space`, `delete_space`, `list_spaces`, `pin_space`, `rename_space` | +| `folders` | `arrange_board`, `board_view`, `count_folder_contents`, `create_folder`, `delete_folder`, `file_notes`, `file_notes_back`, `list_folders`, `recolour_folder`, `rename_folder`, `save_board_layout` | +| `attachments` | `attach_clipboard_image`, `attach_file`, `delete_attachment`, `list_attachments`, `open_attachment`, `read_attachment`, `save_attachment` | +| `transfer` | `count_export`, `export_is_protected`, `export_notes` (over an `ExportScope`: the library, a space or a selection), `import_notes`, `share_notes` | +| `vault` | `change_passphrase`, `create_vault`, `unlock_vault`, `vault_state` | +| `libraries` | `create_library`, `delete_library`, `list_libraries`, `open_library`, `rename_library` | +| `backup` | `list_backups`, `restore_backup` | +| `recovery` | `archive_locked_library`, `set_aside_damaged_library` | +| `changelog` | `app_changelog` | +| `desktop` | `hold_quit`, `set_global_shortcuts`, `release_global_shortcuts`, `set_window_behavior`, `sync_tray` | The guarantees the interface relies on (persisted value returned, `Err` on an unknown id, "absent field means unchanged" for patches) are implemented in each feature, and tested there. @@ -5166,13 +5162,13 @@ open, but all of them. What is done about it: - an index entry wipes its texts when it is dropped (`zeroize`), and so do the folder names and global values the index replaces or drops; - the index is emptied when another library is opened, when a copy is restored, and when the - application exits (`Engine::wipe_index`, from the shell's `RunEvent::Exit`); + application exits (`Engine::wipe_index`, queued by `DevNotesApp::on_exit` behind the last write); - nothing of it is logged, nor sent in an event (`IndexProgress` carries two counts). What is not: the copies a view makes are ordinary `String`s, dropped unwiped, as before the index — the notes `query_notes` matched and the previews it sent, the note open in the editor. Pages of the heap can reach swap, a hibernation image or a crash dump, wiped or not, and a -process killed outside `RunEvent::Exit` frees its memory without wiping it. The key is in the +process killed before its exit frees its memory without wiping it. The key is in the process's memory for the length of the session. **There is no « lock » action, and the migration adds none**: the vault has `vault_state`, `create_vault`, `unlock_vault` and `change_passphrase`, nothing that closes a library short of opening another or quitting. @@ -5321,7 +5317,7 @@ note. | exports | **out** | revisions in the bundle would inflate it by a factor of the cap; a note restored elsewhere arriving without its history is the accepted cost | ⚠️ Both omissions are held by a test rather than left to be noticed — -`a_checklist_keeps_nothing_yet` and `a_bundle_carries_no_history_of_the_bodies_it_holds`. +`a_checklist_or_a_drawing_keeps_nothing` and `a_bundle_carries_no_history_of_the_bodies_it_holds`. Half the note kinds get nothing from this first version, and that is said out loud rather than shipped silently. @@ -5559,9 +5555,7 @@ Afterwards every command answers `Locked`, and the page reloads to the gate, as another library does: a `VaultStore.load()` over the same stores, all `providedIn: 'root'`, carried the replaced library's notes, undo record and open Preferences past the unlock. The restored copy needs a passphrase, and asking for it is the only proof the right file is in -place. Where the replaced files went is said across the reload: Rust keeps it -(`backup::Restored`, handed once by `take_restored_aside`), since nothing in the page outlives -the reload on WebKitGTK, and the startup says it once the vault's state is known. +place. Where the replaced files went is what `restore_backup` answers: the gate says it. ⚠️ `BackupsState` follows the shape the tag manager and the trash already use: `ask()` only **proposes**, `pending()` names which copy, and the confirmation is what writes. A library @@ -5587,7 +5581,7 @@ and decrypted is time every other command would spend waiting. document reads it from disk, so DevNotes writes a decrypted copy under `app_data_dir()/open/` and opens that — one click, as before. The copy is `/` (`Attachment::opened_copy`): the viewer shows the name the user knows, and two of one name do not meet. Those copies are swept on the way out -(`RunEvent::Exit`) and again at every launch, which is what covers one another application +(`DevNotesApp::on_exit`) and again at every launch, which is what covers one another application still held, and a crash. ⚠️ The profile and **not** the OS temporary directory: that one is shared with every account on the machine, where the copy would be readable by all of them and a directory somebody else created first would be theirs rather than ours. @@ -6205,13 +6199,10 @@ compiled in. The body is 14 px. Licences and sources: `crates/ui/assets/README.m **Icons** are Lucide's paths (`theme::icons::Icon`), rasterised by resvg into a white alpha mask at the size asked × `pixels_per_point`, cached per size in the context's memory, and tinted by the colour they are painted in — `currentColor`. The interface draws no emoji of its own any -more: 📎 🖼 ⏳ are `Paperclip`, `Image`, `Hourglass`. +more: 📎 ⏳ are `Paperclip`, `Hourglass`. **Motion** is `theme::motion`: `FAST` (120 ms, what follows the pointer, also egui's own -`animation_time`), `ENTER` (160 ms, what enters), `TURN` (a spinner's 800 ms), `MARK` (2 s, a -mark fading). The three entrances (`Rise`, `Lift`, `Fade`) are an opacity and a 4 px offset -from the first frame an element is drawn after a frame it was not, as a CSS animation runs on an -element that did not exist a frame ago. **One switch**, `motion::set_reduced`, cuts all of it — +`animation_time`), `TURN` (a spinner's 800 ms), `MARK` (2 s, a mark fading). **One switch**, `motion::set_reduced`, cuts all of it — the system's wish read by `platform::motion` (the registry under Windows, `gsettings` under GNOME), as the reference's `prefers-reduced-motion` was: there is no setting of its own. A test sweeps `crates/ui/src` for a duration typed anywhere else, as `motion.test.mjs` did. @@ -6338,8 +6329,8 @@ Two facts shape that, and neither is negotiable: out of `ci.yml` — not a taste for tidiness. The same property has a price worth stating: **the changelog commit is never seen by the CI**. -`prepare` is therefore its own gate — it runs `npm run test:scripts` and `prettier --check` on -the file it just wrote, and `scripts/release-notes.mjs` mirrors, in `assertRenderable`, the +`prepare` is therefore its own gate — it runs the tests of the release +scripts, and `scripts/release-notes.mjs` mirrors, in `assertRenderable`, the three invariants `changelog::tests::the_shipped_file_parses_into_something_to_show` asserts. **The packages** are built by `.github/workflows/package.yml`, a job a system: @@ -6701,8 +6692,11 @@ stress budget holds only if it stops keeping the bodies. `cargo test --workspace --exclude e2e` runs everything but the scenarios. `cargo clippy --workspace --all-targets --all-features -- -D warnings` (`--all-features` is what -compiles the `e2e` flavour) and `cargo fmt --all --check` gate the code; the workspace -`Cargo.toml` sets `unsafe_code = "forbid"` (D7) and denies `clippy::all` and `clippy::pedantic`. +compiles the `e2e` flavour) and `cargo fmt --all --check` gate the code; `rustfmt.toml` sets lines +of 110 columns, filled before they are cut, a chain of calls past 80 cut at each call. A commit that +only reformats is named in `.git-blame-ignore-revs`, which GitHub's blame leaves out, and a local one +after `git config blame.ignoreRevsFile .git-blame-ignore-revs`. The workspace `Cargo.toml` sets +`unsafe_code = "forbid"` (D7) and denies `clippy::all` and `clippy::pedantic`. Unit tests are inline `#[cfg(test)] mod tests` blocks at the bottom of the file they cover — the idiomatic Rust form, and the one that keeps a test next to what it asserts. Shared @@ -6842,8 +6836,8 @@ scenario fixed), the tray menu, a global accelerator pressed on the machine (a s ## The website The showcase site, devnotes.fr, lives in `website/`: an Angular project of its own, outside the -Cargo workspace, with its own `package.json` and lockfile (`npm ci` from `website/`). The root -`package.json` stays the repository's build tool and carries none of it. From `website/`: +Cargo workspace, with its own `package.json` and lockfile (`npm ci` from `website/`). There is +none at the root. From `website/`: `npm start` serves it on port 4300, `npm run build` writes `website/dist/`, `npm test` runs the specs, `npm run lint` ESLint, `npm run test:scripts` the Node tests of the tokens. diff --git a/docs/releasing.md b/docs/releasing.md index 5a5ea5161..5bcfd1624 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -11,7 +11,7 @@ checked, so a release that stops before that leaves nothing to clean up. 1. **Bump the version.** One place holds it (D27): `version` under `[workspace.package]` in the root `Cargo.toml`, which every crate inherits. Edit it, then `cargo update --workspace` - writes it into `Cargo.lock`; nothing else carries a version (`package.json` has none). The + writes it into `Cargo.lock`; nothing else carries a version. The bump touches those two files alone. Merge to `main` and wait for CI to go green — the release refuses to start on a commit CI has not passed. diff --git a/e2e/examples/footprint.rs b/e2e/examples/footprint.rs index c34ee5666..88bd8d77b 100644 --- a/e2e/examples/footprint.rs +++ b/e2e/examples/footprint.rs @@ -41,10 +41,7 @@ fn read(id: u32) -> Reading { .output() .expect("powershell answers"); let text = String::from_utf8_lossy(&output.stdout).replace(',', "."); - let numbers: Vec = text - .split_whitespace() - .map(|word| word.parse().expect("a number")) - .collect(); + let numbers: Vec = text.split_whitespace().map(|word| word.parse().expect("a number")).collect(); Reading { working_set: numbers[0] / 1_048_576.0, private: numbers[1] / 1_048_576.0, @@ -100,10 +97,7 @@ fn video(_id: u32) -> Option { } /// A line of the table, after the rest and the idle average. -#[expect( - clippy::disallowed_methods, - reason = "an average over a duration, not a wait for a condition" -)] +#[expect(clippy::disallowed_methods, reason = "an average over a duration, not a wait for a condition")] fn report(app: &App, stage: &str) { let id = app.id(); std::thread::sleep(REST); @@ -112,10 +106,7 @@ fn report(app: &App, stage: &str) { let after = read(id); let cores = 100.0 * (after.cpu_seconds - before.cpu_seconds) / IDLE.as_secs_f64(); let dedicated = video(id).map_or("n/a".to_owned(), |video| format!("{video:.0}")); - println!( - "| {stage} | {:.0} | {:.0} | {dedicated} | {cores:.2} % |", - after.working_set, after.private - ); + println!("| {stage} | {:.0} | {:.0} | {dedicated} | {cores:.2} % |", after.working_set, after.private); } fn browse(app: &mut App) { diff --git a/e2e/src/lib.rs b/e2e/src/lib.rs index cf61defbf..aee35e7d1 100644 --- a/e2e/src/lib.rs +++ b/e2e/src/lib.rs @@ -35,10 +35,7 @@ fn binary() -> PathBuf { return PathBuf::from(path); } let workspace = Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); - let binary = workspace.join(format!( - "target/e2e/debug/devnotes{}", - std::env::consts::EXE_SUFFIX - )); + let binary = workspace.join(format!("target/e2e/debug/devnotes{}", std::env::consts::EXE_SUFFIX)); assert!( binary.exists(), "no e2e flavour at {}: cargo build -p app --features e2e --target-dir target/e2e", @@ -50,10 +47,8 @@ fn binary() -> PathBuf { /// Captures and what a failed scenario leaves behind, unless `DEVNOTES_E2E_OUTPUT` says /// otherwise. fn output() -> PathBuf { - std::env::var_os("DEVNOTES_E2E_OUTPUT").map_or_else( - || Path::new(env!("CARGO_MANIFEST_DIR")).join("../target/e2e/scenarios"), - PathBuf::from, - ) + std::env::var_os("DEVNOTES_E2E_OUTPUT") + .map_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../target/e2e/scenarios"), PathBuf::from) } /// One step of a scenario, named in the output so that a failure says where it stopped. @@ -78,11 +73,7 @@ impl Tree { /// The control that has the focus, as a failure names it. pub fn focused(&self) -> String { - let node = self - .nodes - .iter() - .find(|(id, _)| Some(*id) == self.focus) - .map(|(_, node)| node); + let node = self.nodes.iter().find(|(id, _)| Some(*id) == self.focus).map(|(_, node)| node); match node { Some(node) => format!( "{} ({:?} {:?})", @@ -187,28 +178,17 @@ impl App { } fn start(scenario: &'static str, profile: &Path, mut command: Command) -> Self { - let alone = ONE_WINDOW - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); + let alone = ONE_WINDOW.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let port = free_port(); let mut child = command .arg("--profile") .arg(profile) - .env( - egui_inspection::INSPECTION_ENV_VAR, - format!("127.0.0.1:{port}"), - ) + .env(egui_inspection::INSPECTION_ENV_VAR, format!("127.0.0.1:{port}")) .stdout(Stdio::null()) .spawn() .expect("the e2e flavour starts"); let stream = connect(port, &mut child); - App { - scenario, - profile: profile.to_path_buf(), - child, - stream, - _alone: alone, - } + App { scenario, profile: profile.to_path_buf(), child, stream, _alone: alone } } /// The process, for what is read from outside it. @@ -263,14 +243,8 @@ impl App { if let Some(action) = action { command.arg("--action").arg(action); } - let status = command - .stdout(Stdio::null()) - .status() - .expect("the second launch runs"); - assert!( - status.success(), - "the second launch could not hand over {action:?}" - ); + let status = command.stdout(Stdio::null()).status().expect("the second launch runs"); + assert!(status.success(), "the second launch could not hand over {action:?}"); } /// Closes the window as `Quit` does, waits for the process to end, and launches it again on @@ -322,14 +296,8 @@ impl App { pub fn tree(&mut self) -> Tree { match self.ask(&Request::GetTree) { Response::Tree { accesskit, .. } => match accesskit { - Some(TreeUpdate { nodes, focus, .. }) => Tree { - nodes, - focus: Some(focus), - }, - None => Tree { - nodes: Vec::new(), - focus: None, - }, + Some(TreeUpdate { nodes, focus, .. }) => Tree { nodes, focus: Some(focus) }, + None => Tree { nodes: Vec::new(), focus: None }, }, other => panic!("a tree was asked, {other:?} came back"), } @@ -377,12 +345,7 @@ impl App { } /// As `click_where`, with another button: the middle one closes a tab. - pub fn click_with( - &mut self, - author_id: &str, - button: PointerButton, - which: impl Fn(&Node) -> bool, - ) { + pub fn click_with(&mut self, author_id: &str, button: PointerButton, which: impl Fn(&Node) -> bool) { let until = Instant::now() + PATIENCE; let mut last = None; let bounds = loop { @@ -404,16 +367,9 @@ impl App { ); }; #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new( - f64::midpoint(bounds.x0, bounds.x1) as f32, - f64::midpoint(bounds.y0, bounds.y1) as f32, - ); - let press = |pressed| Event::PointerButton { - pos, - button, - pressed, - modifiers: Modifiers::NONE, - }; + let pos = + Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); + let press = |pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; self.apply(vec![Event::PointerMoved(pos)]); self.apply(vec![press(true)]); self.apply(vec![press(false)]); @@ -480,12 +436,7 @@ impl App { /// A press at `from` and a release at `to`, in points on the window, the pointer moved /// half way between: what a gesture needs to tell a drag from a click. pub fn drag(&mut self, from: Pos2, to: Pos2, button: PointerButton) { - let press = |pos, pressed| Event::PointerButton { - pos, - button, - pressed, - modifiers: Modifiers::NONE, - }; + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers: Modifiers::NONE }; self.apply(vec![Event::PointerMoved(from)]); self.apply(vec![press(from, true)]); self.apply(vec![Event::PointerMoved(from + (to - from) / 2.0)]); @@ -501,9 +452,7 @@ impl App { /// The pointer over the `n`th `author_id` in reading order, counting from 0. pub fn hover_nth(&mut self, author_id: &str, n: usize) { - self.eventually(&format!("{author_id} #{n} is shown"), |tree| { - tree.count(author_id) > n - }); + self.eventually(&format!("{author_id} #{n} is shown"), |tree| tree.count(author_id) > n); let tree = self.tree(); let bounds = tree .all(author_id) @@ -511,19 +460,15 @@ impl App { .and_then(|node| node.bounds()) .unwrap_or_else(|| panic!("{author_id} has no place on screen")); #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new( - f64::midpoint(bounds.x0, bounds.x1) as f32, - f64::midpoint(bounds.y0, bounds.y1) as f32, - ); + let pos = + Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); self.apply(vec![Event::PointerMoved(pos)]); } /// Clicks the `n`th `author_id` from the top, counting from 0: a choice among several whose /// words are the system's language. pub fn click_nth(&mut self, author_id: &str, n: usize) { - self.eventually(&format!("{author_id} #{n} is shown"), |tree| { - tree.count(author_id) > n - }); + self.eventually(&format!("{author_id} #{n} is shown"), |tree| tree.count(author_id) > n); let tree = self.tree(); let target = tree.all(author_id)[n]; let label = target.label().map(str::to_owned); @@ -561,10 +506,8 @@ impl App { return false; }; #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new( - f64::midpoint(bounds.x0, bounds.x1) as f32, - f64::midpoint(bounds.y0, bounds.y1) as f32, - ); + let pos = + Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); self.apply(vec![ Event::PointerMoved(pos), Event::MouseWheel { @@ -619,9 +562,7 @@ impl App { pub fn at_rest(&mut self, author_id: &str) { let place = |app: &mut Self| { let tree = app.tree(); - tree.find(author_id) - .and_then(Node::bounds) - .map(|bounds| (bounds.x0, bounds.y0)) + tree.find(author_id).and_then(Node::bounds).map(|bounds| (bounds.x0, bounds.y0)) }; let until = Instant::now() + PATIENCE; let mut last = place(self); @@ -643,10 +584,8 @@ impl App { return; }; #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - let pos = Pos2::new( - f64::midpoint(bounds.x0, bounds.x1) as f32, - f64::midpoint(bounds.y0, bounds.y1) as f32, - ); + let pos = + Pos2::new(f64::midpoint(bounds.x0, bounds.x1) as f32, f64::midpoint(bounds.y0, bounds.y1) as f32); self.apply(vec![ Event::PointerMoved(pos), Event::MouseWheel { @@ -707,13 +646,8 @@ impl App { /// A key of another layout than QWERTY: `typed` printed on it, standing where `at` does on /// QWERTY (AZERTY's Q is at A). pub fn press_laid_out(&mut self, typed: Key, at: Key, modifiers: Modifiers) { - let event = |pressed| Event::Key { - key: typed, - physical_key: Some(at), - pressed, - repeat: false, - modifiers, - }; + let event = + |pressed| Event::Key { key: typed, physical_key: Some(at), pressed, repeat: false, modifiers }; self.apply(vec![event(true)]); self.apply(vec![event(false)]); } @@ -726,9 +660,7 @@ impl App { /// The window as it stands, as `//.png`. pub fn capture(&mut self, name: &str) -> PathBuf { - let png = match self.ask(&Request::GetScreenshot { - pixels_per_point: Some(1.0), - }) { + let png = match self.ask(&Request::GetScreenshot { pixels_per_point: Some(1.0) }) { Response::Screenshot(png) => png, other => panic!("a capture was asked, {other:?} came back"), }; @@ -760,9 +692,7 @@ impl Drop for App { if std::thread::panicking() { let directory = output().join(self.scenario); let _ = std::fs::create_dir_all(&directory); - let screen = Request::GetScreenshot { - pixels_per_point: Some(1.0), - }; + let screen = Request::GetScreenshot { pixels_per_point: Some(1.0) }; if let Ok(Response::Screenshot(png)) = exchange(&mut self.stream, &screen) { let _ = std::fs::write(directory.join("failure.png"), png.bytes); } @@ -807,10 +737,7 @@ fn connect(port: u16, child: &mut Child) -> TcpStream { assert_eq!(version, protocol::PROTOCOL_VERSION, "another protocol"); return stream; } - assert!( - Instant::now() < until, - "the application never opened its port" - ); + assert!(Instant::now() < until, "the application never opened its port"); std::thread::yield_now(); } } diff --git a/e2e/src/server.rs b/e2e/src/server.rs index a6558bebc..33bef7d18 100644 --- a/e2e/src/server.rs +++ b/e2e/src/server.rs @@ -51,10 +51,7 @@ fn answer(mut stream: TcpStream) { let head = String::from_utf8_lossy(&head).into_owned(); let path = head.split_whitespace().nth(1).unwrap_or("/").to_owned(); if path.starts_with("/slow") { - #[expect( - clippy::disallowed_methods, - reason = "the server's own latency, not a scenario waiting" - )] + #[expect(clippy::disallowed_methods, reason = "the server's own latency, not a scenario waiting")] std::thread::sleep(Duration::from_secs(2)); } let sent = body_of(&mut stream, &head); @@ -94,23 +91,11 @@ fn body_of(stream: &mut TcpStream, head: &str) -> Vec { } fn reply(path: &str, head: &str, sent: &[u8]) -> Reply { - let plain = |status, kind, body: &[u8]| Reply { - status, - kind, - more: String::new(), - body: body.to_vec(), - }; + let plain = |status, kind, body: &[u8]| Reply { status, kind, more: String::new(), body: body.to_vec() }; if let Some(left) = path.strip_prefix("/redirect/") { let left: u32 = left.parse().unwrap_or(0); - let to = if left > 1 { - format!("/redirect/{}", left - 1) - } else { - "/json".to_owned() - }; - return Reply { - more: format!("Location: {to}\r\n"), - ..plain("302 Found", "text/plain", b"") - }; + let to = if left > 1 { format!("/redirect/{}", left - 1) } else { "/json".to_owned() }; + return Reply { more: format!("Location: {to}\r\n"), ..plain("302 Found", "text/plain", b"") }; } if path.starts_with("/json") || path.starts_with("/slow") { let body = br#"{"name":"Ada","languages":["fr","en"],"admin":true}"#; @@ -131,9 +116,9 @@ fn reply(path: &str, head: &str, sent: &[u8]) -> Reply { /// One white pixel. const PIXEL: &[u8] = &[ - 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, - 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xff, 0xff, 0xff, - 0x7f, 0x00, 0x09, 0xfb, 0x03, 0xfd, 0x2a, 0x86, 0xe3, 0x8a, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, - 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, + 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, + 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xff, 0xff, 0xff, 0x7f, 0x00, 0x09, + 0xfb, 0x03, 0xfd, 0x2a, 0x86, 0xe3, 0x8a, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, + 0x60, 0x82, ]; diff --git a/e2e/tests/01_first_launch.rs b/e2e/tests/01_first_launch.rs index 2ebbc1cb3..43600bcdc 100644 --- a/e2e/tests/01_first_launch.rs +++ b/e2e/tests/01_first_launch.rs @@ -10,14 +10,11 @@ fn first_launch() { // Typed in two goes: the start alone is under the floor of twelve characters. let (start, rest) = PASSPHRASE.split_at(7); - step( - "a blank profile opens on the gate, asking the phrase twice", - || { - app.wait_for("vault-confirmation"); - assert!(!app.has("area-switch")); - app.capture("gate-create"); - }, - ); + step("a blank profile opens on the gate, asking the phrase twice", || { + app.wait_for("vault-confirmation"); + assert!(!app.has("area-switch")); + app.capture("gate-create"); + }); // Only Linux is launched from a terminal often enough for its lines to be read as faults. // Mesa's pair about DRI3 is Xvfb's, which has none: no desktop's X server lacks it. @@ -36,34 +33,25 @@ fn first_launch() { app.fill("vault-passphrase", start); app.fill("vault-confirmation", start); app.eventually("the submit is disabled", |tree| { - tree.find("vault-submit") - .is_some_and(egui::accesskit::Node::is_disabled) + tree.find("vault-submit").is_some_and(egui::accesskit::Node::is_disabled) }); }); - step( - "a long enough phrase, twice, creates the library and opens it", - || { - app.fill("vault-passphrase", rest); - app.fill("vault-confirmation", rest); - app.click("vault-submit"); - app.wait_for("area-notes"); - assert!(app.has("area-switch")); - }, - ); + step("a long enough phrase, twice, creates the library and opens it", || { + app.fill("vault-passphrase", rest); + app.fill("vault-confirmation", rest); + app.click("vault-submit"); + app.wait_for("area-notes"); + assert!(app.has("area-switch")); + }); // Nothing compares a seeded word: the samples are in the system's language. - step( - "a new library opens on its six samples, one left out of the folders", - || { - app.eventually("the six cards are drawn", |tree| { - tree.count("note-card") == 6 - }); - assert_eq!(app.tree().count("note-card-folder"), 5); - assert!(!app.has("error-banner")); - app.capture("first-launch-samples"); - }, - ); + step("a new library opens on its six samples, one left out of the folders", || { + app.eventually("the six cards are drawn", |tree| tree.count("note-card") == 6); + assert_eq!(app.tree().count("note-card-folder"), 5); + assert!(!app.has("error-banner")); + app.capture("first-launch-samples"); + }); let mut app = app.relaunch(); @@ -76,24 +64,18 @@ fn first_launch() { app.fill("vault-passphrase", "not the phrase"); app.click("vault-submit"); app.eventually("the problem line speaks", |tree| { - tree.text("vault-problem") - .is_some_and(|said| !said.is_empty()) + tree.text("vault-problem").is_some_and(|said| !said.is_empty()) }); assert!(!app.has("area-notes")); app.capture("gate-wrong"); }); - step( - "the phrase chosen opens the library, its samples seeded once", - || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("the six cards are drawn", |tree| { - tree.count("note-card") == 6 - }); - }, - ); + step("the phrase chosen opens the library, its samples seeded once", || { + app.fill("vault-passphrase", PASSPHRASE); + app.click("vault-submit"); + app.wait_for("area-notes"); + app.eventually("the six cards are drawn", |tree| tree.count("note-card") == 6); + }); app.quit(); } diff --git a/e2e/tests/02_note_lifecycle.rs b/e2e/tests/02_note_lifecycle.rs index a5efdb4c2..d95083469 100644 --- a/e2e/tests/02_note_lifecycle.rs +++ b/e2e/tests/02_note_lifecycle.rs @@ -19,20 +19,17 @@ fn note_lifecycle() { app.create_library(); cards(&mut app, CARDS, "the samples are drawn"); - step( - "a card names its kind by an icon, and only a snippet its format", - || { - let tree = app.tree(); - assert_eq!(tree.count("kind-icon"), CARDS); - let formats = tree.count("note-format"); - assert!(formats > 0 && formats < CARDS, "{formats} formats"); - // Title bar over status line, on every card. - for (icon, when) in tree.all("kind-icon").iter().zip(tree.all("note-card-when")) { - let (icon, when) = (icon.bounds().unwrap(), when.bounds().unwrap()); - assert!(icon.y1 <= when.y0, "{icon:?} over {when:?}"); - } - }, - ); + step("a card names its kind by an icon, and only a snippet its format", || { + let tree = app.tree(); + assert_eq!(tree.count("kind-icon"), CARDS); + let formats = tree.count("note-format"); + assert!(formats > 0 && formats < CARDS, "{formats} formats"); + // Title bar over status line, on every card. + for (icon, when) in tree.all("kind-icon").iter().zip(tree.all("note-card-when")) { + let (icon, when) = (icon.bounds().unwrap(), when.bounds().unwrap()); + assert!(icon.y1 <= when.y0, "{icon:?} over {when:?}"); + } + }); step("a new note opens as a draft that is not yet a note", || { app.click("new-note"); @@ -42,35 +39,29 @@ fn note_lifecycle() { assert!(drawn <= CARDS, "{drawn} cards drawn"); }); - step( - "it is written once it carries something worth keeping", - || { - app.fill("editor-title", TITLE); - app.fill("editor-body", BODY); - app.capture("editor-draft"); - app.click("editor-close"); - app.eventually("the editor is closed and the note is a card", |tree| { - !tree.has("editor-title") && tree.texts("note-card").contains(&TITLE.to_owned()) - }); - cards(&mut app, CARDS + 1, "one card more, and only one"); - }, - ); + step("it is written once it carries something worth keeping", || { + app.fill("editor-title", TITLE); + app.fill("editor-body", BODY); + app.capture("editor-draft"); + app.click("editor-close"); + app.eventually("the editor is closed and the note is a card", |tree| { + !tree.has("editor-title") && tree.texts("note-card").contains(&TITLE.to_owned()) + }); + cards(&mut app, CARDS + 1, "one card more, and only one"); + }); - step( - "the ghost opens a draft, and closed untouched it writes nothing", - || { - app.scroll_to("canvas", "create-ghost"); - app.scroll_above("canvas", "create-ghost", "canvas-keyboard-hint"); - app.at_rest("create-ghost"); - app.click("create-ghost"); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - // Under a header of two rows the top ones went out of view, and were not counted. - app.scroll_top("canvas"); - cards(&mut app, CARDS + 1, "no card more"); - }, - ); + step("the ghost opens a draft, and closed untouched it writes nothing", || { + app.scroll_to("canvas", "create-ghost"); + app.scroll_above("canvas", "create-ghost", "canvas-keyboard-hint"); + app.at_rest("create-ghost"); + app.click("create-ghost"); + app.wait_for("editor-title"); + app.click("editor-close"); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + // Under a header of two rows the top ones went out of view, and were not counted. + app.scroll_top("canvas"); + cards(&mut app, CARDS + 1, "no card more"); + }); step("the kind menu opens the same draft as the button", || { app.click("new-note-kind"); @@ -81,48 +72,34 @@ fn note_lifecycle() { cards(&mut app, CARDS + 1, "no card more"); }); - step( - "each kind opens from its own key, and writes nothing untouched", - || { - for (key, shift) in [(Key::N, false), (Key::N, true), (Key::L, true)] { - let modifiers = if shift { - Modifiers::COMMAND | Modifiers::SHIFT - } else { - Modifiers::COMMAND - }; - app.press(key, modifiers); - app.wait_for("editor-title"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - } - cards(&mut app, CARDS + 1, "no card more"); - assert!(app.has("canvas-keyboard-hint")); - }, - ); + step("each kind opens from its own key, and writes nothing untouched", || { + for (key, shift) in [(Key::N, false), (Key::N, true), (Key::L, true)] { + let modifiers = if shift { Modifiers::COMMAND | Modifiers::SHIFT } else { Modifiers::COMMAND }; + app.press(key, modifiers); + app.wait_for("editor-title"); + app.click("editor-close"); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + } + cards(&mut app, CARDS + 1, "no card more"); + assert!(app.has("canvas-keyboard-hint")); + }); step("a note opened from its card shows what was written", || { app.click_where("note-card-open", |node| node.label() == Some(TITLE)); app.eventually("the note is read back whole", |tree| { - tree.find("editor-body") - .and_then(egui::accesskit::Node::value) - == Some(BODY) + tree.find("editor-body").and_then(egui::accesskit::Node::value) == Some(BODY) }); app.click("editor-close"); }); let mut app = app.relaunch(); - step( - "the note is read back from the library on a relaunch", - || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.wait_for("area-notes"); - app.eventually("its card is there", |tree| { - tree.texts("note-card").contains(&TITLE.to_owned()) - }); - }, - ); + step("the note is read back from the library on a relaunch", || { + app.fill("vault-passphrase", e2e::PASSPHRASE); + app.click("vault-submit"); + app.wait_for("area-notes"); + app.eventually("its card is there", |tree| tree.texts("note-card").contains(&TITLE.to_owned())); + }); app.quit(); } diff --git a/e2e/tests/03_editing_a_note.rs b/e2e/tests/03_editing_a_note.rs index c777ba47f..1def5f9eb 100644 --- a/e2e/tests/03_editing_a_note.rs +++ b/e2e/tests/03_editing_a_note.rs @@ -76,79 +76,58 @@ fn drawings(app: &mut App, exported: &std::path::Path) { app.wait_for("note-card-drawing"); }); - step( - "a drawing is written as a PNG where the dialog says", - || { - open_sketch(app); - app.eventually("the scene read back", |tree| shapes(tree) == "1"); - app.click("drawing-export-png"); - app.eventually("the file written", |_| { - std::fs::read(exported).is_ok_and(|bytes| bytes.starts_with(b"\x89PNG")) - }); - }, - ); - - step( - "the eraser takes shape after shape and stays in hand", - || { - app.click("drawing-tool-ellipse"); - app.drag_in("drawing-stage", (200.0, 40.0), (280.0, 110.0)); - app.eventually("two shapes", |tree| shapes(tree) == "2"); - app.click("drawing-tool-eraser"); - app.drag_in("drawing-stage", (20.0, 75.0), (300.0, 75.0)); - app.eventually("both gone in one drag", |tree| shapes(tree) == "0"); - assert!(pressed(&app.tree(), "drawing-tool-eraser")); - app.click("drawing-undo"); - app.eventually("one step back", |tree| shapes(tree) == "2"); - app.drag_in("drawing-stage", (240.0, 75.0), (240.0, 75.0)); - app.eventually("one by a click", |tree| shapes(tree) == "1"); - }, - ); + step("a drawing is written as a PNG where the dialog says", || { + open_sketch(app); + app.eventually("the scene read back", |tree| shapes(tree) == "1"); + app.click("drawing-export-png"); + app.eventually("the file written", |_| { + std::fs::read(exported).is_ok_and(|bytes| bytes.starts_with(b"\x89PNG")) + }); + }); + + step("the eraser takes shape after shape and stays in hand", || { + app.click("drawing-tool-ellipse"); + app.drag_in("drawing-stage", (200.0, 40.0), (280.0, 110.0)); + app.eventually("two shapes", |tree| shapes(tree) == "2"); + app.click("drawing-tool-eraser"); + app.drag_in("drawing-stage", (20.0, 75.0), (300.0, 75.0)); + app.eventually("both gone in one drag", |tree| shapes(tree) == "0"); + assert!(pressed(&app.tree(), "drawing-tool-eraser")); + app.click("drawing-undo"); + app.eventually("one step back", |tree| shapes(tree) == "2"); + app.drag_in("drawing-stage", (240.0, 75.0), (240.0, 75.0)); + app.eventually("one by a click", |tree| shapes(tree) == "1"); + }); arrow_and_look(app); - step( - "Escape drops the tool, the selection, then the editor", - || { - app.drag_in("drawing-stage", (100.0, 75.0), (100.0, 75.0)); - app.eventually("the stage has the keys", |tree| { - tree.focused().starts_with("drawing-stage") - }); - app.press(Key::O, Modifiers::NONE); - app.eventually("the ellipse taken", |tree| { - pressed(tree, "drawing-tool-ellipse") - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("back to the selection", |tree| { - pressed(tree, "drawing-tool-select") - }); - app.press(Key::Escape, Modifiers::NONE); - assert!( - app.has("editor-title"), - "the selection went, not the editor" - ); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }, - ); + step("Escape drops the tool, the selection, then the editor", || { + app.drag_in("drawing-stage", (100.0, 75.0), (100.0, 75.0)); + app.eventually("the stage has the keys", |tree| tree.focused().starts_with("drawing-stage")); + app.press(Key::O, Modifiers::NONE); + app.eventually("the ellipse taken", |tree| pressed(tree, "drawing-tool-ellipse")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("back to the selection", |tree| pressed(tree, "drawing-tool-select")); + app.press(Key::Escape, Modifiers::NONE); + assert!(app.has("editor-title"), "the selection went, not the editor"); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + }); } /// The sketch open, a rectangle on it: an arrow bound and let go, then the look moved. fn arrow_and_look(app: &mut App) { - step( - "an arrow drawn from a shape, its end let go elsewhere", - || { - app.click("drawing-tool-arrow"); - app.drag_in("drawing-stage", (100.0, 75.0), (320.0, 75.0)); - app.eventually("the arrow", |tree| shapes(tree) == "2"); - app.drag_in("drawing-stage", (320.0, 75.0), (320.0, 150.0)); - app.capture("drawing-arrow-end"); - assert_eq!(shapes(&app.tree()), "2", "moved, not drawn"); - app.click("drawing-undo"); - app.click("drawing-undo"); - app.eventually("the rectangle alone", |tree| shapes(tree) == "1"); - }, - ); + step("an arrow drawn from a shape, its end let go elsewhere", || { + app.click("drawing-tool-arrow"); + app.drag_in("drawing-stage", (100.0, 75.0), (320.0, 75.0)); + app.eventually("the arrow", |tree| shapes(tree) == "2"); + app.drag_in("drawing-stage", (320.0, 75.0), (320.0, 150.0)); + app.capture("drawing-arrow-end"); + assert_eq!(shapes(&app.tree()), "2", "moved, not drawn"); + app.click("drawing-undo"); + app.click("drawing-undo"); + app.eventually("the rectangle alone", |tree| shapes(tree) == "1"); + }); step("the drawing is zoomed, moved and shown whole again", || { let shown = |tree: &Tree| tree.text("drawing-zoom").unwrap_or_default(); @@ -156,11 +135,7 @@ fn arrow_and_look(app: &mut App) { app.click("drawing-zoom-in"); app.click("drawing-zoom-in"); app.eventually("closer", |tree| shown(tree).starts_with("156")); - app.drag( - egui::pos2(700.0, 400.0), - egui::pos2(640.0, 380.0), - egui::PointerButton::Middle, - ); + app.drag(egui::pos2(700.0, 400.0), egui::pos2(640.0, 380.0), egui::PointerButton::Middle); app.capture("drawing-zoomed"); app.click("drawing-fit"); app.eventually("whole again", |tree| shown(tree).starts_with("100")); @@ -185,48 +160,34 @@ fn open_title(tree: &Tree) -> String { /// Beside the cards, J and K step through them; expanded, the cards go; Escape steps back. fn beside_the_cards(app: &mut App) { - step( - "a note opens beside the cards, and J steps to the next one", - || { - app.click("search-input"); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Delete, Modifiers::NONE); - app.eventually("every card back", |tree| tree.count("note-card") > 2); - app.click_nth("note-card-open", 0); - app.wait_for("editor-title"); - let first = open_title(&app.tree()); - app.press(Key::J, Modifiers::NONE); - app.eventually("the next card open", |tree| { - tree.has("editor-title") && open_title(tree) != first - }); - app.press(Key::F2, Modifiers::NONE); - app.eventually("F2 goes to the title", |tree| { - tree.focused().starts_with("editor-title") - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("Escape leaves it, the note still open", |tree| { - tree.has("editor-title") && !tree.focused().starts_with("editor-title") - }); - app.capture("editor-beside-the-cards"); - }, - ); - - step( - "expanded, the note takes the area; Escape steps back", - || { - app.click("editor-fullscreen"); - app.eventually("the cards gone", |tree| { - !tree.has("note-card") && tree.has("editor-position") - }); - app.press(Key::Escape, Modifiers::NONE); - // Beside the cards again, or over them in a window too narrow for both. - app.eventually("out of full screen", |tree| { - !tree.has("editor-position") && tree.has("editor-title") - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }, - ); + step("a note opens beside the cards, and J steps to the next one", || { + app.click("search-input"); + app.press(Key::A, Modifiers::COMMAND); + app.press(Key::Delete, Modifiers::NONE); + app.eventually("every card back", |tree| tree.count("note-card") > 2); + app.click_nth("note-card-open", 0); + app.wait_for("editor-title"); + let first = open_title(&app.tree()); + app.press(Key::J, Modifiers::NONE); + app.eventually("the next card open", |tree| tree.has("editor-title") && open_title(tree) != first); + app.press(Key::F2, Modifiers::NONE); + app.eventually("F2 goes to the title", |tree| tree.focused().starts_with("editor-title")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("Escape leaves it, the note still open", |tree| { + tree.has("editor-title") && !tree.focused().starts_with("editor-title") + }); + app.capture("editor-beside-the-cards"); + }); + + step("expanded, the note takes the area; Escape steps back", || { + app.click("editor-fullscreen"); + app.eventually("the cards gone", |tree| !tree.has("note-card") && tree.has("editor-position")); + app.press(Key::Escape, Modifiers::NONE); + // Beside the cards again, or over them in a window too narrow for both. + app.eventually("out of full screen", |tree| !tree.has("editor-position") && tree.has("editor-title")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + }); } /// The rich text a Note's surface holds. @@ -239,9 +200,7 @@ fn rich(tree: &Tree) -> String { /// The first task's box: ticked or not. fn first_box(tree: &Tree) -> Option { - tree.all("rich-task") - .first() - .and_then(|task| task.toggled()) + tree.all("rich-task").first().and_then(|task| task.toggled()) } /// The one card `words` finds. ⚠️ The previous search showed one card too: the count is @@ -257,48 +216,40 @@ fn search_alone(app: &mut App, words: &str) { } fn notes(app: &mut App) { - step( - "the sample Note opens formatted, and a box ticked or unticked is kept", - || { - search_alone(app, "timeout=120s"); - app.click("note-card-open"); - app.eventually("its tasks drawn", |tree| tree.count("rich-task") == 3); - assert!(!app.tree().has("editor-body"), "no code field for a Note"); - // The sample's first task is done in one language and not in the other. - let before = first_box(&app.tree()); - app.click_nth("rich-task", 0); - app.eventually("the box changed", |tree| first_box(tree) != before); - let after = first_box(&app.tree()); - app.capture("note"); - close(app); - app.click("note-card-open"); - app.eventually("kept once opened again", |tree| first_box(tree) == after); - close(app); - }, - ); - - step( - "a Note typed with the toolbar keeps its stars as typed", - || { - app.click("new-note-kind"); - app.click("new-note-note"); - app.click("editor-rich"); - for glyph in ["2", " ", "*", " ", "3", " ", "*", " ", "4"] { - app.type_text(glyph); - } - app.press(Key::Enter, Modifiers::NONE); - app.click("rich-bold"); - app.type_text("fort"); - app.eventually("both lines typed", |tree| rich(tree) == "2 * 3 * 4\nfort"); - close(app); - search_alone(app, "fort"); - app.click("note-card-open"); - app.eventually("written back as typed", |tree| { - rich(tree) == "2 * 3 * 4\nfort" - }); - close(app); - }, - ); + step("the sample Note opens formatted, and a box ticked or unticked is kept", || { + search_alone(app, "timeout=120s"); + app.click("note-card-open"); + app.eventually("its tasks drawn", |tree| tree.count("rich-task") == 3); + assert!(!app.tree().has("editor-body"), "no code field for a Note"); + // The sample's first task is done in one language and not in the other. + let before = first_box(&app.tree()); + app.click_nth("rich-task", 0); + app.eventually("the box changed", |tree| first_box(tree) != before); + let after = first_box(&app.tree()); + app.capture("note"); + close(app); + app.click("note-card-open"); + app.eventually("kept once opened again", |tree| first_box(tree) == after); + close(app); + }); + + step("a Note typed with the toolbar keeps its stars as typed", || { + app.click("new-note-kind"); + app.click("new-note-note"); + app.click("editor-rich"); + for glyph in ["2", " ", "*", " ", "3", " ", "*", " ", "4"] { + app.type_text(glyph); + } + app.press(Key::Enter, Modifiers::NONE); + app.click("rich-bold"); + app.type_text("fort"); + app.eventually("both lines typed", |tree| rich(tree) == "2 * 3 * 4\nfort"); + close(app); + search_alone(app, "fort"); + app.click("note-card-open"); + app.eventually("written back as typed", |tree| rich(tree) == "2 * 3 * 4\nfort"); + close(app); + }); step("a double click in a Note takes the word under it", || { // A click less than 0.3 s before a double click makes it a triple, for egui: the last @@ -311,17 +262,13 @@ fn notes(app: &mut App) { app.type_text("fort"); app.eventually("the Note alone", |tree| tree.count("note-card") == 1); app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| { - tree.focused().starts_with("note-card-open") - }); + app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); app.press(Key::Enter, Modifiers::NONE); app.wait_for("editor-rich"); // The first word: the page's margin is 28 points, 20 above the first line. app.double_click_in("editor-rich", (31.0, 31.0)); app.type_text("deux"); - app.eventually("the word typed over", |tree| { - rich(tree) == "deux * 3 * 4\nfort" - }); + app.eventually("the word typed over", |tree| rich(tree) == "deux * 3 * 4\nfort"); close(app); }); @@ -370,9 +317,7 @@ fn editing_a_note() { app.fill("editor-source", "runbooks/api.md"); close(&mut app); open(&mut app); - app.eventually("the code as typed", |tree| { - code(tree) == "kubectl rollout restart deployment/api" - }); + app.eventually("the code as typed", |tree| code(tree) == "kubectl rollout restart deployment/api"); app.eventually("the context as typed", |tree| { tree.find("editor-source").and_then(|field| field.value()) == Some("runbooks/api.md") }); @@ -386,25 +331,18 @@ fn editing_a_note() { app.capture("snippet-editor"); }); - step( - "Tab stays in the code, and the find bar finds in it", - || { - app.click("editor-body"); - app.press(Key::Home, Modifiers::COMMAND); - app.press(Key::Tab, Modifiers::NONE); - app.eventually("a level before the code", |tree| { - code(tree).starts_with(" kubectl") - }); - app.press(Key::F, Modifiers::COMMAND); - app.wait_for("search-field"); - app.type_text("rollout"); - app.eventually("one match, selected", |tree| { - tree.text("search-count").as_deref() == Some("1 / 1") - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the bar is closed", |tree| !tree.has("search-field")); - }, - ); + step("Tab stays in the code, and the find bar finds in it", || { + app.click("editor-body"); + app.press(Key::Home, Modifiers::COMMAND); + app.press(Key::Tab, Modifiers::NONE); + app.eventually("a level before the code", |tree| code(tree).starts_with(" kubectl")); + app.press(Key::F, Modifiers::COMMAND); + app.wait_for("search-field"); + app.type_text("rollout"); + app.eventually("one match, selected", |tree| tree.text("search-count").as_deref() == Some("1 / 1")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the bar is closed", |tree| !tree.has("search-field")); + }); step("full screen and back keep the draft", || { app.click("editor-body"); @@ -417,20 +355,17 @@ fn editing_a_note() { app.eventually("the draft written", |tree| code(tree).ends_with("--watch")); }); - step( - "the header folds, and stays folded from note to note", - || { - app.click("editor-fold-header"); - app.wait_for("editor-header-summary"); - close(&mut app); - open(&mut app); - app.wait_for("editor-header-summary"); - assert!(!app.has("editor-source")); - app.click("editor-header-summary"); - app.wait_for("editor-source"); - close(&mut app); - }, - ); + step("the header folds, and stays folded from note to note", || { + app.click("editor-fold-header"); + app.wait_for("editor-header-summary"); + close(&mut app); + open(&mut app); + app.wait_for("editor-header-summary"); + assert!(!app.has("editor-source")); + app.click("editor-header-summary"); + app.wait_for("editor-source"); + close(&mut app); + }); beside_the_cards(&mut app); drawings(&mut app, &exported); diff --git a/e2e/tests/04_trash_and_undo.rs b/e2e/tests/04_trash_and_undo.rs index 69b0c61be..bd0782f6c 100644 --- a/e2e/tests/04_trash_and_undo.rs +++ b/e2e/tests/04_trash_and_undo.rs @@ -44,36 +44,28 @@ fn trash_and_undo() { app.create_library(); cards(&mut app, CARDS, "the samples are drawn"); - step( - "the card's menu needs the second click to delete anything", - || { - app.hover("note-card-open"); - app.click("note-card-menu"); - app.click("note-card-delete"); - assert_eq!(app.tree().count("note-card"), CARDS); - app.press(Key::Escape, Modifiers::NONE); - }, - ); - - step( - "the priorities of the menu come and go with the pointer, and one is picked", - || { - let levels = "note-card-priority-level"; - app.hover("note-card-open"); - app.click("note-card-menu"); - app.hover("note-card-priority"); - app.eventually("the five levels", |tree| tree.count(levels) == 5); - app.hover("note-card-duplicate"); - app.eventually("closed with the pointer gone", |tree| !tree.has(levels)); - app.hover("note-card-priority"); - app.hover_nth(levels, 3); - app.eventually("open under the pointer", |tree| tree.count(levels) == 5); - app.click_nth(levels, 0); - app.eventually("a pick closes the menu", |tree| { - !tree.has("note-card-priority") - }); - }, - ); + step("the card's menu needs the second click to delete anything", || { + app.hover("note-card-open"); + app.click("note-card-menu"); + app.click("note-card-delete"); + assert_eq!(app.tree().count("note-card"), CARDS); + app.press(Key::Escape, Modifiers::NONE); + }); + + step("the priorities of the menu come and go with the pointer, and one is picked", || { + let levels = "note-card-priority-level"; + app.hover("note-card-open"); + app.click("note-card-menu"); + app.hover("note-card-priority"); + app.eventually("the five levels", |tree| tree.count(levels) == 5); + app.hover("note-card-duplicate"); + app.eventually("closed with the pointer gone", |tree| !tree.has(levels)); + app.hover("note-card-priority"); + app.hover_nth(levels, 3); + app.eventually("open under the pointer", |tree| tree.count(levels) == 5); + app.click_nth(levels, 0); + app.eventually("a pick closes the menu", |tree| !tree.has("note-card-priority")); + }); step("Delete arms the card, and Escape calls it off", || { app.press(Key::ArrowDown, Modifiers::NONE); @@ -103,16 +95,13 @@ fn trash_and_undo() { assert!(!app.has("undo-bar")); }); - step( - "Ctrl+Z still takes it back once the banner has gone", - || { - delete_first(&mut app); - app.wait_for("undo-bar"); - app.eventually("the banner's timer runs out", |tree| !tree.has("undo-bar")); - app.press(Key::Z, Modifiers::COMMAND); - cards(&mut app, CARDS, "the note is back"); - }, - ); + step("Ctrl+Z still takes it back once the banner has gone", || { + delete_first(&mut app); + app.wait_for("undo-bar"); + app.eventually("the banner's timer runs out", |tree| !tree.has("undo-bar")); + app.press(Key::Z, Modifiers::COMMAND); + cards(&mut app, CARDS, "the note is back"); + }); step("a dismissed offer is given up for good", || { trash_first(&mut app); @@ -150,27 +139,24 @@ fn trash_panel(app: &mut App) { assert_eq!(app.tree().count("note-card"), CARDS - 1); }); - step( - "a search narrows the trash, and restoring reaches what it found", - || { - for _ in 0..3 { - trash_first(app); - } - app.click("trash-open"); - rows(app, 3, "the three deleted notes are listed"); - app.fill("trash-search", "zz-nothing-zz"); - app.eventually("the search finds nothing", |tree| { - tree.has("trash-empty-state") && !tree.has("trash-empty") - }); - app.press(Key::A, Modifiers::COMMAND); - app.press(Key::Backspace, Modifiers::NONE); - rows(app, 3, "the whole trash is back"); - app.click("trash-restore-all"); - emptied(app); - app.click("trash-close"); - cards(app, CARDS - 1, "the three notes are back"); - }, - ); + step("a search narrows the trash, and restoring reaches what it found", || { + for _ in 0..3 { + trash_first(app); + } + app.click("trash-open"); + rows(app, 3, "the three deleted notes are listed"); + app.fill("trash-search", "zz-nothing-zz"); + app.eventually("the search finds nothing", |tree| { + tree.has("trash-empty-state") && !tree.has("trash-empty") + }); + app.press(Key::A, Modifiers::COMMAND); + app.press(Key::Backspace, Modifiers::NONE); + rows(app, 3, "the whole trash is back"); + app.click("trash-restore-all"); + emptied(app); + app.click("trash-close"); + cards(app, CARDS - 1, "the three notes are back"); + }); step("emptying says what it erases, then erases it", || { trash_first(app); diff --git a/e2e/tests/05_spaces.rs b/e2e/tests/05_spaces.rs index e7338f4f7..b8d72ce4f 100644 --- a/e2e/tests/05_spaces.rs +++ b/e2e/tests/05_spaces.rs @@ -28,35 +28,32 @@ fn is_shown(tree: &e2e::Tree, name: &str) -> bool { } fn deleted_with_its_notes(app: &mut App) { - step( - "a space deleted with its notes puts them in the trash", - || { - app.click("space-create-open"); - app.fill("space-create-input", "Brouillons"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - is_shown(tree, "Brouillons") && tree.count("note-card") == 0 - }); - app.click("new-note"); - app.fill("editor-title", DOOMED); - app.fill("editor-body", "à jeter"); - app.click("editor-close"); - app.eventually("its note is a card", |tree| tree.count("note-card") == 1); - app.click_where("space-edit", options_of("Brouillons")); - app.click("space-delete-held"); - app.click("space-delete-held-1"); - app.click("space-delete"); - app.click("space-delete"); - app.eventually("the space is gone, its note not in the refuge", |tree| { - tree.count("space-option") == 1 && tree.count("note-card") == CARDS - }); - app.click("trash-open"); - app.eventually("the note waits in the trash", |tree| { - tree.texts("trash-row-title").contains(&DOOMED.to_owned()) - }); - app.press(Key::Escape, Modifiers::NONE); - }, - ); + step("a space deleted with its notes puts them in the trash", || { + app.click("space-create-open"); + app.fill("space-create-input", "Brouillons"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown", |tree| { + is_shown(tree, "Brouillons") && tree.count("note-card") == 0 + }); + app.click("new-note"); + app.fill("editor-title", DOOMED); + app.fill("editor-body", "à jeter"); + app.click("editor-close"); + app.eventually("its note is a card", |tree| tree.count("note-card") == 1); + app.click_where("space-edit", options_of("Brouillons")); + app.click("space-delete-held"); + app.click("space-delete-held-1"); + app.click("space-delete"); + app.click("space-delete"); + app.eventually("the space is gone, its note not in the refuge", |tree| { + tree.count("space-option") == 1 && tree.count("note-card") == CARDS + }); + app.click("trash-open"); + app.eventually("the note waits in the trash", |tree| { + tree.texts("trash-row-title").contains(&DOOMED.to_owned()) + }); + app.press(Key::Escape, Modifiers::NONE); + }); } #[test] @@ -65,22 +62,15 @@ fn spaces() { let mut app = App::launch("05_spaces", profile.path()); app.create_library(); - step( - "a new library has one space, and it cannot be deleted", - || { - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); - assert_eq!(app.tree().count("space-option"), 1); - app.click("space-edit"); - app.wait_for("space-delete-blocked"); - assert!(!app.has("space-delete")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the panel is closed", |tree| { - !tree.has("space-delete-blocked") - }); - }, - ); + step("a new library has one space, and it cannot be deleted", || { + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); + assert_eq!(app.tree().count("space-option"), 1); + app.click("space-edit"); + app.wait_for("space-delete-blocked"); + assert!(!app.has("space-delete")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the panel is closed", |tree| !tree.has("space-delete-blocked")); + }); step("a space made from the rail is the one shown", || { app.click("space-create-open"); @@ -104,33 +94,26 @@ fn spaces() { }); }); - step( - "pinned, it heads the list whatever its name, and falls back", - || { - app.click_where("space-edit", options_of("Lectures")); - app.click("space-pin"); - app.eventually("the pinned space is first", |tree| { - tree.texts("space-option").first().map(String::as_str) == Some("Lectures") - }); - app.click("space-pin"); - app.eventually("the unpinned space is back in its name's order", |tree| { - let names = tree.texts("space-option"); - names.len() == 2 && names.contains(&"Lectures".to_owned()) - }); - app.click_where("space-edit", options_of("Lectures")); - app.eventually("the panel is closed", |tree| !tree.has("space-pin")); - }, - ); + step("pinned, it heads the list whatever its name, and falls back", || { + app.click_where("space-edit", options_of("Lectures")); + app.click("space-pin"); + app.eventually("the pinned space is first", |tree| { + tree.texts("space-option").first().map(String::as_str) == Some("Lectures") + }); + app.click("space-pin"); + app.eventually("the unpinned space is back in its name's order", |tree| { + let names = tree.texts("space-option"); + names.len() == 2 && names.contains(&"Lectures".to_owned()) + }); + app.click_where("space-edit", options_of("Lectures")); + app.eventually("the panel is closed", |tree| !tree.has("space-pin")); + }); step("« all spaces » shows every note, a space its own", || { app.click("space-option-all"); - app.eventually("every card is back", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); app.click_where("space-option", named("Lectures")); - app.eventually("the canvas narrowed to the space", |tree| { - tree.count("note-card") == 0 - }); + app.eventually("the canvas narrowed to the space", |tree| tree.count("note-card") == 0); }); let mut app = app.relaunch(); @@ -144,19 +127,16 @@ fn spaces() { }); }); - step( - "deleting a space says where its notes go, then moves them", - || { - app.click_where("space-edit", options_of("Lectures")); - app.wait_for("space-delete-consequence"); - app.capture("rail-space-panel"); - app.click("space-delete"); - app.click("space-delete"); - app.eventually("the space is gone, its refuge shown", |tree| { - tree.count("space-option") == 1 && tree.count("note-card") == CARDS - }); - }, - ); + step("deleting a space says where its notes go, then moves them", || { + app.click_where("space-edit", options_of("Lectures")); + app.wait_for("space-delete-consequence"); + app.capture("rail-space-panel"); + app.click("space-delete"); + app.click("space-delete"); + app.eventually("the space is gone, its refuge shown", |tree| { + tree.count("space-option") == 1 && tree.count("note-card") == CARDS + }); + }); deleted_with_its_notes(&mut app); diff --git a/e2e/tests/06_search_and_filters.rs b/e2e/tests/06_search_and_filters.rs index 9b93e278d..dbc9c5373 100644 --- a/e2e/tests/06_search_and_filters.rs +++ b/e2e/tests/06_search_and_filters.rs @@ -41,17 +41,12 @@ struct Layout { } fn layout(tree: &e2e::Tree) -> Layout { - let area = tree - .find("area-notes") - .and_then(egui::accesskit::Node::bounds); + let area = tree.find("area-notes").and_then(egui::accesskit::Node::bounds); let boxes: Vec<(&'static str, egui::accesskit::Rect)> = HEADER[..HEADER.len() - 1] .iter() .filter_map(|id| Some((*id, tree.find(id)?.bounds()?))) .collect(); - let mut middles: Vec = boxes - .iter() - .map(|(_, b)| f64::midpoint(b.y0, b.y1)) - .collect(); + let mut middles: Vec = boxes.iter().map(|(_, b)| f64::midpoint(b.y0, b.y1)).collect(); middles.sort_by(f64::total_cmp); let starts: Vec = middles .iter() @@ -63,33 +58,16 @@ fn layout(tree: &e2e::Tree) -> Layout { .iter() .map(|(id, b)| { let middle = f64::midpoint(b.y0, b.y1); - ( - *id, - starts - .iter() - .filter(|start| **start <= middle + 12.0) - .count(), - ) + (*id, starts.iter().filter(|start| **start <= middle + 12.0).count()) }) .collect(); - let overflowing = area.is_none_or(|area| { - boxes - .iter() - .any(|(_, b)| b.x0 < area.x0 - 1.0 || b.x1 > area.x1 + 1.0) - }); - Layout { - rows: starts.len(), - row_of, - overflowing, - } + let overflowing = + area.is_none_or(|area| boxes.iter().any(|(_, b)| b.x0 < area.x0 - 1.0 || b.x1 > area.x1 + 1.0)); + Layout { rows: starts.len(), row_of, overflowing } } fn row(layout: &Layout, id: &str) -> usize { - layout - .row_of - .iter() - .find(|(each, _)| *each == id) - .map_or(0, |(_, row)| *row) + layout.row_of.iter().find(|(each, _)| *each == id).map_or(0, |(_, row)| *row) } fn search(app: &mut App, words: &str) { @@ -103,25 +81,18 @@ fn search_and_filters() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch("06_search_and_filters", profile.path()); app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); - step( - "a search finds a note by its body, past the debounce", - || { - search(&mut app, "withRetry"); - app.eventually("one card, and its count", |tree| { - tree.count("note-card") == 1 && tree.has("search-matched") - }); - }, - ); + step("a search finds a note by its body, past the debounce", || { + search(&mut app, "withRetry"); + app.eventually("one card, and its count", |tree| { + tree.count("note-card") == 1 && tree.has("search-matched") + }); + }); step("down from the field to the card it found", || { app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| { - tree.focused().starts_with("note-card-open") - }); + app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); }); step("it folds case the way Rust does", || { @@ -132,10 +103,7 @@ fn search_and_filters() { step("nothing found says so, and still counts", || { search(&mut app, "nothing matches this"); app.eventually("the canvas says nothing matches", |tree| { - tree.has("canvas-no-results") - && tree - .text("search-matched") - .is_some_and(|said| !said.is_empty()) + tree.has("canvas-no-results") && tree.text("search-matched").is_some_and(|said| !said.is_empty()) }); app.capture("search-nothing"); }); @@ -147,27 +115,18 @@ fn search_and_filters() { }); }); - step( - "the quick filter keeps one pinned note, then one with a deadline", - || { - app.click(PINNED); - app.eventually("the pinned welcome", |tree| tree.count("note-card") == 1); - app.click(UNTRIAGED); - app.eventually("the list with a deadline", |tree| { - tree.count("note-card") == 1 - }); - app.click(ALL); - app.eventually("every card is back", |tree| { - tree.count("note-card") == CARDS - }); - }, - ); + step("the quick filter keeps one pinned note, then one with a deadline", || { + app.click(PINNED); + app.eventually("the pinned welcome", |tree| tree.count("note-card") == 1); + app.click(UNTRIAGED); + app.eventually("the list with a deadline", |tree| tree.count("note-card") == 1); + app.click(ALL); + app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); + }); step("Ctrl+K puts the caret in the search", || { app.press(Key::K, Modifiers::COMMAND); - app.eventually("the search has the focus", |tree| { - tree.focused().starts_with("search-input") - }); + app.eventually("the search has the focus", |tree| tree.focused().starts_with("search-input")); }); step("no grouping lays the cards out as one list", || { @@ -194,11 +153,7 @@ fn search_and_filters() { }); step("the board waits for its own phase", || { - assert!( - app.tree() - .find("view-board") - .is_some_and(egui::accesskit::Node::is_disabled) - ); + assert!(app.tree().find("view-board").is_some_and(egui::accesskit::Node::is_disabled)); }); read_text(&mut app); @@ -206,25 +161,20 @@ fn search_and_filters() { } fn read_text(app: &mut App) { - step( - "a Note is found by the words it shows, across its bold", - || { - app.click("new-note-kind"); - app.click("new-note-note"); - app.click("editor-rich"); - app.type_text("ask about the "); - app.click("rich-bold"); - app.type_text("rollout"); - app.click("rich-bold"); - app.type_text(" window"); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - search(app, "rollout window"); - app.eventually("the Note alone", |tree| { - tree.count("note-card") == 1 && tree.has("search-matched") - }); - }, - ); + step("a Note is found by the words it shows, across its bold", || { + app.click("new-note-kind"); + app.click("new-note-note"); + app.click("editor-rich"); + app.type_text("ask about the "); + app.click("rich-bold"); + app.type_text("rollout"); + app.click("rich-bold"); + app.type_text(" window"); + app.click("editor-close"); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + search(app, "rollout window"); + app.eventually("the Note alone", |tree| tree.count("note-card") == 1 && tree.has("search-matched")); + }); } /// The filters' menus and their way out, side by side. @@ -234,62 +184,45 @@ fn band_on_one_line(tree: &e2e::Tree) -> bool { .filter_map(|id| tree.find(id)?.bounds()) .map(|b| f64::midpoint(b.y0, b.y1)) .collect(); - middles.len() == 3 - && middles - .windows(2) - .all(|pair| (pair[0] - pair[1]).abs() < 2.0) + middles.len() == 3 && middles.windows(2).all(|pair| (pair[0] - pair[1]).abs() < 2.0) } /// The filters' menus over the samples, then the header at three widths. fn rails_and_header(app: &mut App) { - step( - "a kind from its menu narrows the cards, and « All » gives them back", - || { - app.click("facets-toggle"); - app.click("facet-menu-kind"); - app.click("kind-chip-note"); - app.eventually("the Notes alone, and the toggle counts one value", |tree| { - let cards = tree.count("note-card"); - cards > 0 && cards < CARDS && tree.text("facets-count").as_deref() == Some("1") - }); - assert!( - app.tree() - .find("facets-toggle") - .is_some_and(egui::accesskit::Node::is_disabled), - "it refuses to fold while a value is ticked" - ); - assert!(app.tree().has("kind-chip-all"), "the menu stays open"); - app.capture("facets-kind"); - app.click("kind-chip-all"); - app.eventually("every card is back", |tree| { - tree.count("note-card") == CARDS - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu closed", |tree| !tree.has("kind-chip-all")); - }, - ); + step("a kind from its menu narrows the cards, and « All » gives them back", || { + app.click("facets-toggle"); + app.click("facet-menu-kind"); + app.click("kind-chip-note"); + app.eventually("the Notes alone, and the toggle counts one value", |tree| { + let cards = tree.count("note-card"); + cards > 0 && cards < CARDS && tree.text("facets-count").as_deref() == Some("1") + }); + assert!( + app.tree().find("facets-toggle").is_some_and(egui::accesskit::Node::is_disabled), + "it refuses to fold while a value is ticked" + ); + assert!(app.tree().has("kind-chip-all"), "the menu stays open"); + app.capture("facets-kind"); + app.click("kind-chip-all"); + app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the menu closed", |tree| !tree.has("kind-chip-all")); + }); - step( - "a tag and a format narrow too, and one click clears them", - || { - app.click("facet-menu-tag"); - app.click("tag-pill"); - app.eventually("fewer cards", |tree| tree.count("note-card") < CARDS); - app.click("facet-menu-language"); - app.click_nth("language-chip", 0); - app.eventually("two values ticked", |tree| { - tree.text("facets-count").as_deref() == Some("2") - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the band on one line", band_on_one_line); - app.click("clear-filters"); - app.eventually("every card is back, and the way out goes", |tree| { - tree.count("note-card") == CARDS - && !tree.has("clear-filters") - && !tree.has("facets-count") - }); - }, - ); + step("a tag and a format narrow too, and one click clears them", || { + app.click("facet-menu-tag"); + app.click("tag-pill"); + app.eventually("fewer cards", |tree| tree.count("note-card") < CARDS); + app.click("facet-menu-language"); + app.click_nth("language-chip", 0); + app.eventually("two values ticked", |tree| tree.text("facets-count").as_deref() == Some("2")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the band on one line", band_on_one_line); + app.click("clear-filters"); + app.eventually("every card is back, and the way out goes", |tree| { + tree.count("note-card") == CARDS && !tree.has("clear-filters") && !tree.has("facets-count") + }); + }); step("Escape closes the menu, then lets the value go", || { app.click("facet-menu-kind"); @@ -300,22 +233,17 @@ fn rails_and_header(app: &mut App) { !tree.has("kind-chip-all") && tree.count("note-card") < CARDS }); app.press(Key::Escape, Modifiers::NONE); - app.eventually("every card is back", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("every card is back", |tree| tree.count("note-card") == CARDS); app.click("facets-toggle"); app.eventually("the band folds", |tree| !tree.has("facet-menu-kind")); }); - step( - "the header holds one row at 1,100 with the rail open", - || { - app.resize(1_100, 720); - let shown = layout(&app.tree()); - assert!(!shown.overflowing); - assert_eq!(shown.rows, 1); - }, - ); + step("the header holds one row at 1,100 with the rail open", || { + app.resize(1_100, 720); + let shown = layout(&app.tree()); + assert!(!shown.overflowing); + assert_eq!(shown.rows, 1); + }); step("the rail put away, one row at 1,330, two at 640", || { app.click("library-rail-toggle"); diff --git a/e2e/tests/07_checklists.rs b/e2e/tests/07_checklists.rs index 188309f06..8bd42d043 100644 --- a/e2e/tests/07_checklists.rs +++ b/e2e/tests/07_checklists.rs @@ -29,9 +29,7 @@ fn open(app: &mut App) { app.type_text(TITLE); app.eventually("the list alone", |tree| tree.count("note-card") == 1); app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| { - tree.focused().starts_with("note-card-open") - }); + app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); app.press(Key::Enter, Modifiers::NONE); app.wait_for("checklist-add"); } @@ -68,58 +66,38 @@ fn checklists() { close(&mut app); open(&mut app); app.eventually("the rows in the order added", |tree| { - rows(tree) - == [ - "Tag the release", - "Write the changelog", - "Publish the binaries", - ] + rows(tree) == ["Tag the release", "Write the changelog", "Publish the binaries"] }); app.capture("checklist-editor"); }); - step( - "Enter cuts a row at the caret, Backspace joins it back", - || { - app.click_nth("checklist-text", 2); - app.press(Key::End, Modifiers::NONE); - for _ in 0.."binaries".len() { - app.press(Key::ArrowLeft, Modifiers::NONE); - } - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the row cut in two", |tree| { - rows(tree).get(2..) == Some(&["Publish the ".to_owned(), "binaries".to_owned()][..]) - }); - app.press(Key::Backspace, Modifiers::NONE); - app.eventually("joined back", |tree| rows(tree).len() == 3); - }, - ); + step("Enter cuts a row at the caret, Backspace joins it back", || { + app.click_nth("checklist-text", 2); + app.press(Key::End, Modifiers::NONE); + for _ in 0.."binaries".len() { + app.press(Key::ArrowLeft, Modifiers::NONE); + } + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the row cut in two", |tree| { + rows(tree).get(2..) == Some(&["Publish the ".to_owned(), "binaries".to_owned()][..]) + }); + app.press(Key::Backspace, Modifiers::NONE); + app.eventually("joined back", |tree| rows(tree).len() == 3); + }); - step( - "lines pasted into a row are as many items, their boxes read", - || { - add(&mut app, ""); - app.paste("- Freeze the merges\n- [x] Back the database up"); - app.eventually("two rows from the paste", |tree| { - rows(tree).get(3..) - == Some( - &[ - "Freeze the merges".to_owned(), - "Back the database up".to_owned(), - ][..], - ) - }); - app.eventually("the box pasted ticked", |tree| { - ticks(tree) == [false, false, false, false, true] - }); - }, - ); + step("lines pasted into a row are as many items, their boxes read", || { + add(&mut app, ""); + app.paste("- Freeze the merges\n- [x] Back the database up"); + app.eventually("two rows from the paste", |tree| { + rows(tree).get(3..) + == Some(&["Freeze the merges".to_owned(), "Back the database up".to_owned()][..]) + }); + app.eventually("the box pasted ticked", |tree| ticks(tree) == [false, false, false, false, true]); + }); step("a row is ticked, moved up by Alt+↑ and removed", || { app.click_nth("checklist-check", 0); - app.eventually("the first row ticked", |tree| { - ticks(tree).first() == Some(&true) - }); + app.eventually("the first row ticked", |tree| ticks(tree).first() == Some(&true)); app.click_nth("checklist-text", 1); app.press(Key::ArrowUp, Modifiers::ALT); app.eventually("the second row first", |tree| { @@ -134,12 +112,7 @@ fn checklists() { open(&mut app); app.eventually("as left", |tree| { rows(tree) - == [ - "Write the changelog", - "Tag the release", - "Publish the binaries", - "Freeze the merges", - ] + == ["Write the changelog", "Tag the release", "Publish the binaries", "Freeze the merges"] && ticks(tree) == [false, true, false, false] }); close(&mut app); @@ -152,9 +125,7 @@ fn checklists() { tree.text("note-card-progress").as_deref() == Some("2/4") }); open(&mut app); - app.eventually("the first open row ticked", |tree| { - ticks(tree).first() == Some(&true) - }); + app.eventually("the first open row ticked", |tree| ticks(tree).first() == Some(&true)); close(&mut app); }); diff --git a/e2e/tests/08_placeholder_fields.rs b/e2e/tests/08_placeholder_fields.rs index cd559d0d2..b2302e070 100644 --- a/e2e/tests/08_placeholder_fields.rs +++ b/e2e/tests/08_placeholder_fields.rs @@ -42,9 +42,7 @@ fn counted(tree: &e2e::Tree) -> String { } fn closed(app: &mut App) { - app.eventually("the form is closed", |tree| { - !tree.has("placeholder-form-hint") - }); + app.eventually("the form is closed", |tree| !tree.has("placeholder-form-hint")); } #[test] @@ -54,27 +52,20 @@ fn placeholder_fields() { app.create_library(); app.wait_for("note-card"); app.fill("search-input", "5432"); - app.eventually("the snippet with fields, alone", |tree| { - tree.count("note-card") == 1 + app.eventually("the snippet with fields, alone", |tree| tree.count("note-card") == 1); + + step("the keyboard asks for the fields too, in the first one", || { + app.press(Key::ArrowDown, Modifiers::NONE); + app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); + app.press(Key::C, Modifiers::NONE); + app.eventually("the form, typing in its first field", |tree| { + tree.focused().starts_with("placeholder-input") + }); + app.capture("placeholder-form"); + app.press(Key::Escape, Modifiers::NONE); + closed(&mut app); }); - step( - "the keyboard asks for the fields too, in the first one", - || { - app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| { - tree.focused().starts_with("note-card-open") - }); - app.press(Key::C, Modifiers::NONE); - app.eventually("the form, typing in its first field", |tree| { - tree.focused().starts_with("placeholder-input") - }); - app.capture("placeholder-form"); - app.press(Key::Escape, Modifiers::NONE); - closed(&mut app); - }, - ); - step("the card offers the fields instead of a plain copy", || { app.hover("note-card-open"); app.wait_for("note-card-fill"); @@ -88,9 +79,7 @@ fn placeholder_fields() { closed(&mut app); app.wait_for("status-toast"); open_from_card(&mut app); - app.eventually("the value typed comes back", |tree| { - first_value(tree) == "db.internal" - }); + app.eventually("the value typed comes back", |tree| first_value(tree) == "db.internal"); }); step("cancelled, the form writes nothing", || { @@ -100,9 +89,7 @@ fn placeholder_fields() { app.click("placeholder-cancel"); closed(&mut app); open_from_card(&mut app); - app.eventually("the value kept is still there", |tree| { - first_value(tree) == "db.internal" - }); + app.eventually("the value kept is still there", |tree| first_value(tree) == "db.internal"); }); step("« copy as is » copies and closes", || { @@ -111,14 +98,11 @@ fn placeholder_fields() { app.wait_for("status-toast"); }); - step( - "the editor's panel counts what is kept, default aside", - || { - open_editor(&mut app); - app.eventually("one field filled of four", |tree| counted(tree) == "1/4"); - app.capture("fields-panel"); - }, - ); + step("the editor's panel counts what is kept, default aside", || { + open_editor(&mut app); + app.eventually("one field filled of four", |tree| counted(tree) == "1/4"); + app.capture("fields-panel"); + }); step("the body is shown filled, and given back", || { app.click("placeholder-panel-preview"); @@ -128,20 +112,17 @@ fn placeholder_fields() { app.wait_for("editor-body"); }); - step( - "folded, the panel stays so for the next note opened", - || { - app.click("placeholder-panel-toggle"); - app.eventually("the fields gone", |tree| !tree.has("placeholder-input")); - close_editor(&mut app); - open_editor(&mut app); - app.wait_for("placeholder-panel-toggle"); - assert!(!app.has("placeholder-input")); - app.click("placeholder-panel-toggle"); - app.wait_for("placeholder-input"); - close_editor(&mut app); - }, - ); + step("folded, the panel stays so for the next note opened", || { + app.click("placeholder-panel-toggle"); + app.eventually("the fields gone", |tree| !tree.has("placeholder-input")); + close_editor(&mut app); + open_editor(&mut app); + app.wait_for("placeholder-panel-toggle"); + assert!(!app.has("placeholder-input")); + app.click("placeholder-panel-toggle"); + app.wait_for("placeholder-input"); + close_editor(&mut app); + }); app.quit(); } diff --git a/e2e/tests/09_quick_palette.rs b/e2e/tests/09_quick_palette.rs index dcd84c24e..ced1d665b 100644 --- a/e2e/tests/09_quick_palette.rs +++ b/e2e/tests/09_quick_palette.rs @@ -22,9 +22,7 @@ fn search(app: &mut App, words: &str) { } fn editor_title(tree: &e2e::Tree) -> Option { - tree.find("editor-title") - .and_then(|field| field.value()) - .map(str::to_owned) + tree.find("editor-title").and_then(|field| field.value()).map(str::to_owned) } #[test] @@ -32,9 +30,7 @@ fn quick_palette() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch("09_quick_palette", profile.path()); app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); step("a second launch opens it, on the recent notes", || { app.act("palette"); @@ -45,50 +41,37 @@ fn quick_palette() { app.capture("palette-recent"); }); - step( - "it narrows to what is typed, and Enter opens the note", - || { - search(&mut app, "withRetry"); - app.eventually("one note answers", |tree| tree.count("palette-option") == 1); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the editor is open on it, the palette gone", |tree| { - tree.has("editor-title") && !tree.has("palette-input") - }); - app.click("editor-close"); - app.eventually("the editor is closed", |tree| !tree.has("editor-title")); - }, - ); + step("it narrows to what is typed, and Enter opens the note", || { + search(&mut app, "withRetry"); + app.eventually("one note answers", |tree| tree.count("palette-option") == 1); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the editor is open on it, the palette gone", |tree| { + tree.has("editor-title") && !tree.has("palette-input") + }); + app.click("editor-close"); + app.eventually("the editor is closed", |tree| !tree.has("editor-title")); + }); - step( - "a query that finds nothing offers a note named after it", - || { - app.press(Key::P, Modifiers::COMMAND | Modifiers::ALT); - opened(&mut app); - search(&mut app, NOTHING); - app.eventually( - "the offer replaces the list, and says nothing matched", - |tree| { - tree.has("palette-create") - && tree.has("palette-empty") - && tree.count("palette-option") == 0 - }, - ); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the note opens titled, already written", |tree| { - editor_title(tree).as_deref() == Some(NOTHING) - }); - app.click("editor-close"); - app.eventually("one card more", |tree| tree.count("note-card") == CARDS + 1); - }, - ); + step("a query that finds nothing offers a note named after it", || { + app.press(Key::P, Modifiers::COMMAND | Modifiers::ALT); + opened(&mut app); + search(&mut app, NOTHING); + app.eventually("the offer replaces the list, and says nothing matched", |tree| { + tree.has("palette-create") && tree.has("palette-empty") && tree.count("palette-option") == 0 + }); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the note opens titled, already written", |tree| { + editor_title(tree).as_deref() == Some(NOTHING) + }); + app.click("editor-close"); + app.eventually("one card more", |tree| tree.count("note-card") == CARDS + 1); + }); step("`>` lists the commands, and Escape closes", || { app.press(Key::P, Modifiers::COMMAND | Modifiers::ALT); opened(&mut app); app.type_text(">"); - app.eventually("the commands", |tree| { - tree.count("palette-option") >= 5 && tree.has("palette-group") - }); + app.eventually("the commands", |tree| tree.count("palette-option") >= 5 && tree.has("palette-group")); app.press(Key::Escape, Modifiers::NONE); app.eventually("the palette is closed", |tree| !tree.has("palette-input")); }); diff --git a/e2e/tests/10_library_transfer.rs b/e2e/tests/10_library_transfer.rs index 71ff0231c..16915ee8c 100644 --- a/e2e/tests/10_library_transfer.rs +++ b/e2e/tests/10_library_transfer.rs @@ -113,12 +113,10 @@ fn sealed_file(app: &mut App, file: &Path) { app.fill("passphrase-prompt-field", "not the phrase"); app.click("passphrase-prompt-submit"); app.eventually("the prompt says the phrase is wrong", |tree| { - tree.text("passphrase-prompt-problem") - .is_some_and(|said| !said.is_empty()) + tree.text("passphrase-prompt-problem").is_some_and(|said| !said.is_empty()) }); app.eventually("the prompt is open again", |tree| { - tree.find("passphrase-prompt-field") - .is_some_and(|field| !field.is_disabled()) + tree.find("passphrase-prompt-field").is_some_and(|field| !field.is_disabled()) }); app.fill("passphrase-prompt-field", PHRASE); app.click("passphrase-prompt-submit"); @@ -142,32 +140,23 @@ fn library_transfer() { app.click("file-menu"); app.wait_for("file-option-exportSelection"); let tree = app.tree(); - assert!( - tree.find("file-option-exportSelection") - .unwrap() - .is_disabled() - ); + assert!(tree.find("file-option-exportSelection").unwrap().is_disabled()); assert!(tree.find("file-option-copyMarkdown").unwrap().is_disabled()); assert!(!tree.find("file-option-exportAll").unwrap().is_disabled()); app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu is closed", |tree| { - !tree.has("file-option-exportAll") - }); + app.eventually("the menu is closed", |tree| !tree.has("file-option-exportAll")); }); - step( - "an export in the clear writes an archive and names it", - || { - menu(&mut app, "exportAll"); - app.wait_for("passphrase-prompt"); - app.capture("protect-prompt"); - app.click("passphrase-prompt-plain"); - let said = report(&mut app); - assert!(said.contains(FILE), "{said}"); - assert!(said.contains(&(CARDS + 1).to_string()), "{said}"); - assert!(is_archive(&file)); - }, - ); + step("an export in the clear writes an archive and names it", || { + menu(&mut app, "exportAll"); + app.wait_for("passphrase-prompt"); + app.capture("protect-prompt"); + app.click("passphrase-prompt-plain"); + let said = report(&mut app); + assert!(said.contains(FILE), "{said}"); + assert!(said.contains(&(CARDS + 1).to_string()), "{said}"); + assert!(is_archive(&file)); + }); step("importing what is there adds nothing, and says so", || { menu(&mut app, "import"); @@ -185,24 +174,20 @@ fn library_transfer() { sealed_file(&mut app, &file); - step( - "a file from a newer version comes in rather than failing", - || { - std::fs::write(&file, NEWER).unwrap(); - menu(&mut app, "import"); - report(&mut app); - // In its own space: a list draws only what is in view, and the window's size is the - // machine's. - app.click_where("space-option", |node| node.label() == Some("Ailleurs")); - app.eventually("the note from the future is drawn", |tree| { - tree.texts("note-card-title") - .contains(&"Ahead of this build".to_owned()) - }); - app.eventually("the drawing imported shows its picture", |tree| { - tree.has("note-card-drawing") && !tree.has("note-card-drawing-empty") - }); - }, - ); + step("a file from a newer version comes in rather than failing", || { + std::fs::write(&file, NEWER).unwrap(); + menu(&mut app, "import"); + report(&mut app); + // In its own space: a list draws only what is in view, and the window's size is the + // machine's. + app.click_where("space-option", |node| node.label() == Some("Ailleurs")); + app.eventually("the note from the future is drawn", |tree| { + tree.texts("note-card-title").contains(&"Ahead of this build".to_owned()) + }); + app.eventually("the drawing imported shows its picture", |tree| { + tree.has("note-card-drawing") && !tree.has("note-card-drawing-empty") + }); + }); step("Escape gives a prompt up, and nothing is written", || { std::fs::remove_file(&file).unwrap(); diff --git a/e2e/tests/12_preferences.rs b/e2e/tests/12_preferences.rs index b417f9398..767ca1499 100644 --- a/e2e/tests/12_preferences.rs +++ b/e2e/tests/12_preferences.rs @@ -77,26 +77,23 @@ fn preferences() { let mut app = App::launch("12_preferences", profile.path()); app.create_library(); - step( - "the theme shows as it is chosen, and Cancel takes it back", - || { - open(&mut app); - app.capture("preferences"); - app.click(THEME_DARK); - app.click("settings-apply"); - let dark = theme_word(&mut app); - - app.click(THEME_LIGHT); - app.eventually("the window previews the light theme", |tree| { - tree.text("theme-toggle").is_some_and(|word| word != dark) - }); - app.click("settings-cancel"); - closed(&mut app); - app.eventually("the theme is back", |tree| { - tree.text("theme-toggle").as_deref() == Some(dark.as_str()) - }); - }, - ); + step("the theme shows as it is chosen, and Cancel takes it back", || { + open(&mut app); + app.capture("preferences"); + app.click(THEME_DARK); + app.click("settings-apply"); + let dark = theme_word(&mut app); + + app.click(THEME_LIGHT); + app.eventually("the window previews the light theme", |tree| { + tree.text("theme-toggle").is_some_and(|word| word != dark) + }); + app.click("settings-cancel"); + closed(&mut app); + app.eventually("the theme is back", |tree| { + tree.text("theme-toggle").as_deref() == Some(dark.as_str()) + }); + }); step("the language waits for the button", || { open(&mut app); @@ -109,9 +106,7 @@ fn preferences() { locale(&mut app, ENGLISH); assert_eq!(file_word(&mut app), "Fichier", "nothing before the button"); app.click("settings-apply"); - app.eventually("the window speaks English", |tree| { - tree.text("file-menu").as_deref() == Some("File") - }); + app.eventually("the window speaks English", |tree| tree.text("file-menu").as_deref() == Some("File")); app.click("settings-close"); closed(&mut app); }); @@ -160,10 +155,7 @@ fn preferences() { }); let four = card_height(&mut app); - step( - "five preview lines make every card 160 px rather than 140", - || five_lines(&mut app, four), - ); + step("five preview lines make every card 160 px rather than 140", || five_lines(&mut app, four)); let theme = theme_word(&mut app); let mut app = app.relaunch(); @@ -171,18 +163,15 @@ fn preferences() { app.click("vault-submit"); app.wait_for("area-notes"); - step( - "what was applied is what the next launch opens with", - || { - assert_eq!(file_word(&mut app), "File"); - assert_eq!(theme_word(&mut app), theme); - still_five_lines(&mut app, four); - open(&mut app); - app.click(COMFORTABLE); - app.click("settings-cancel"); - closed(&mut app); - }, - ); + step("what was applied is what the next launch opens with", || { + assert_eq!(file_word(&mut app), "File"); + assert_eq!(theme_word(&mut app), theme); + still_five_lines(&mut app, four); + open(&mut app); + app.click(COMFORTABLE); + app.click("settings-cancel"); + closed(&mut app); + }); app.quit(); } diff --git a/e2e/tests/13_multiple_selection.rs b/e2e/tests/13_multiple_selection.rs index fba07eea6..9aefc9dbb 100644 --- a/e2e/tests/13_multiple_selection.rs +++ b/e2e/tests/13_multiple_selection.rs @@ -11,8 +11,7 @@ fn tick_two(app: &mut App) { app.press(key, Modifiers::NONE); } app.eventually("two cards are ticked", |tree| { - tree.text("selection-count") - .is_some_and(|said| said.contains('2')) + tree.text("selection-count").is_some_and(|said| said.contains('2')) }); } @@ -41,9 +40,7 @@ fn multiple_selection() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch("13_multiple_selection", profile.path()); app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); step("a card is ticked by its box, which stays put", || { ticked_by_its_box(&mut app); @@ -62,14 +59,10 @@ fn multiple_selection() { // While the bar offers the tagging back, Escape would take it back. app.click("undo-dismiss"); app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); app.click("search-input"); app.type_text("batchtag"); - app.eventually("the two tagged notes are found", |tree| { - tree.count("note-card") == 2 - }); + app.eventually("the two tagged notes are found", |tree| tree.count("note-card") == 2); }); step("deleting the selection takes two clicks", || { @@ -82,9 +75,7 @@ fn multiple_selection() { tree.has("canvas-no-results") && !tree.has("selection-count") }); app.click("search-clear"); - app.eventually("the others are untouched", |tree| { - tree.count("note-card") == CARDS - 2 - }); + app.eventually("the others are untouched", |tree| tree.count("note-card") == CARDS - 2); }); app.quit(); diff --git a/e2e/tests/14_tag_manager.rs b/e2e/tests/14_tag_manager.rs index 2c4272a30..ed11b8b3d 100644 --- a/e2e/tests/14_tag_manager.rs +++ b/e2e/tests/14_tag_manager.rs @@ -20,9 +20,7 @@ fn tag(app: &mut App, positions: &[usize], tag: &str) { app.press(Key::Enter, Modifiers::NONE); app.click("undo-dismiss"); app.click("selection-clear"); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); } fn listed(tree: &e2e::Tree, tag: &str) -> bool { @@ -37,10 +35,7 @@ fn tick(app: &mut App, tag: &str) { fn target(tree: &e2e::Tree) -> String { let field = tree.find("tag-target"); - field - .and_then(|node| node.value()) - .unwrap_or_default() - .to_owned() + field.and_then(|node| node.value()).unwrap_or_default().to_owned() } /// The ticked tags under `into`, typed over what the field holds, proposed then confirmed. @@ -57,60 +52,45 @@ fn tag_manager() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch("14_tag_manager", profile.path()); app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); tag(&mut app, &[0, 1], "staging"); tag(&mut app, &[0], "urgent"); tag(&mut app, &[2], "preprod"); - step( - "the tags' menu opens the manager, which lists every tag", - || { - app.click("facets-toggle"); - app.click("facet-menu-tag"); - app.click("tag-manage"); - app.eventually("the scenario's tags are listed", |tree| { - ["staging", "urgent", "preprod"] - .iter() - .all(|tag| listed(tree, tag)) - }); - assert!( - app.tree() - .find("tag-apply") - .is_some_and(egui::accesskit::Node::is_disabled), - "nothing ticked, nothing to apply" - ); - }, - ); + step("the tags' menu opens the manager, which lists every tag", || { + app.click("facets-toggle"); + app.click("facet-menu-tag"); + app.click("tag-manage"); + app.eventually("the scenario's tags are listed", |tree| { + ["staging", "urgent", "preprod"].iter().all(|tag| listed(tree, tag)) + }); + assert!( + app.tree().find("tag-apply").is_some_and(egui::accesskit::Node::is_disabled), + "nothing ticked, nothing to apply" + ); + }); - step( - "a rename says what it touches, and cancelling writes nothing", - || { - tick(&mut app, "staging"); - app.eventually("its name fills the field, which has the focus", |tree| { - target(tree) == "staging" && tree.focused().starts_with("tag-target") - }); - assert!( - app.tree() - .find("tag-apply") - .is_some_and(egui::accesskit::Node::is_disabled), - "its own name changes nothing" - ); - assert!(app.tree().has("tag-target-reason")); - // Selected: what is typed replaces it. - app.type_text("recette"); - app.eventually("edited in place", |tree| target(tree) == "recette"); - app.click("tag-apply"); - app.eventually("two notes carry it, and the sentence says so", |tree| { - tree.text("tag-confirm-text") - .is_some_and(|said| said.contains('2')) - }); - app.capture("tag-confirm"); - app.click("tag-confirm-cancel"); - assert!(listed(&app.tree(), "staging")); - }, - ); + step("a rename says what it touches, and cancelling writes nothing", || { + tick(&mut app, "staging"); + app.eventually("its name fills the field, which has the focus", |tree| { + target(tree) == "staging" && tree.focused().starts_with("tag-target") + }); + assert!( + app.tree().find("tag-apply").is_some_and(egui::accesskit::Node::is_disabled), + "its own name changes nothing" + ); + assert!(app.tree().has("tag-target-reason")); + // Selected: what is typed replaces it. + app.type_text("recette"); + app.eventually("edited in place", |tree| target(tree) == "recette"); + app.click("tag-apply"); + app.eventually("two notes carry it, and the sentence says so", |tree| { + tree.text("tag-confirm-text").is_some_and(|said| said.contains('2')) + }); + app.capture("tag-confirm"); + app.click("tag-confirm-cancel"); + assert!(listed(&app.tree(), "staging")); + }); step("confirmed, the rename reaches every note", || { app.click("tag-apply"); @@ -140,9 +120,7 @@ fn tag_manager() { app.click("tag-confirm-apply"); app.eventually("urgent is gone", |tree| !listed(tree, "urgent")); app.click("tag-manager-close"); - app.eventually("the manager is closed", |tree| { - !tree.has("tag-manager-close") - }); + app.eventually("the manager is closed", |tree| !tree.has("tag-manager-close")); // The band takes room from the cards: how many are drawn under it depends on the window. app.click("facets-toggle"); app.eventually("every note stays", |tree| tree.count("note-card") == CARDS); diff --git a/e2e/tests/15_preferences_on_disk.rs b/e2e/tests/15_preferences_on_disk.rs index acf67596a..5de9343a5 100644 --- a/e2e/tests/15_preferences_on_disk.rs +++ b/e2e/tests/15_preferences_on_disk.rs @@ -17,17 +17,12 @@ fn stored(profile: &Path) -> serde_json::Map { } fn says(profile: &Path, key: &str) -> Option { - stored(profile) - .get(key) - .and_then(Value::as_str) - .map(str::to_owned) + stored(profile).get(key).and_then(Value::as_str).map(str::to_owned) } /// Read again through the window: a write answers frames later, on the core's queue. fn settled(app: &mut App, profile: &Path, key: &str, want: &str) { - app.eventually(&format!("{key} reaches the file"), |_| { - says(profile, key).as_deref() == Some(want) - }); + app.eventually(&format!("{key} reaches the file"), |_| says(profile, key).as_deref() == Some(want)); } fn open(app: &mut App) { @@ -55,11 +50,7 @@ fn preferences_on_disk() { app.click(THEME_LIGHT); // The window has drawn the choice, and with it any write it would have asked for. app.wait_for("settings-apply"); - assert_eq!( - says(profile, "devnotes.theme").as_deref(), - Some("dark"), - "a preview is not a write" - ); + assert_eq!(says(profile, "devnotes.theme").as_deref(), Some("dark"), "a preview is not a write"); app.click("settings-close"); settled(&mut app, profile, "devnotes.theme", "light"); }); diff --git a/e2e/tests/16_passphrase_change.rs b/e2e/tests/16_passphrase_change.rs index dc4a70fd7..52e1adf78 100644 --- a/e2e/tests/16_passphrase_change.rs +++ b/e2e/tests/16_passphrase_change.rs @@ -50,55 +50,43 @@ fn passphrase_change() { let file = key_file(profile).expect("the library has its key file"); let first = std::fs::read(&file).unwrap(); - step( - "a change that cannot name the phrase rewrites nothing", - || { - security(&mut app); - fill_change(&mut app, "not the current one"); - app.eventually("the phrase is refused", |tree| { - tree.text("change-passphrase-problem") - .is_some_and(|said| !said.is_empty()) - }); - assert_eq!(std::fs::read(&file).unwrap(), first); - assert!(app.has("change-passphrase"), "the dialog stays"); - }, - ); + step("a change that cannot name the phrase rewrites nothing", || { + security(&mut app); + fill_change(&mut app, "not the current one"); + app.eventually("the phrase is refused", |tree| { + tree.text("change-passphrase-problem").is_some_and(|said| !said.is_empty()) + }); + assert_eq!(std::fs::read(&file).unwrap(), first); + assert!(app.has("change-passphrase"), "the dialog stays"); + }); - step( - "the right phrase rewraps the key and leaves the notes", - || { - app.eventually("the fields are free again", |tree| { - tree.find("change-passphrase-current") - .is_some_and(|field| !field.is_disabled()) - }); - fill_change(&mut app, PASSPHRASE); - app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); - // It stands over the dialog's buttons in a small window. - app.wait_for("status-toast"); - app.click("status-dismiss"); - app.eventually("the report is dismissed", |tree| !tree.has("status-toast")); - assert_ne!(std::fs::read(&file).unwrap(), first); - app.click("settings-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - assert!(app.has("note-card"), "the session carries on"); - }, - ); + step("the right phrase rewraps the key and leaves the notes", || { + app.eventually("the fields are free again", |tree| { + tree.find("change-passphrase-current").is_some_and(|field| !field.is_disabled()) + }); + fill_change(&mut app, PASSPHRASE); + app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); + // It stands over the dialog's buttons in a small window. + app.wait_for("status-toast"); + app.click("status-dismiss"); + app.eventually("the report is dismissed", |tree| !tree.has("status-toast")); + assert_ne!(std::fs::read(&file).unwrap(), first); + app.click("settings-close"); + app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); + assert!(app.has("note-card"), "the session carries on"); + }); let mut app = app.relaunch(); - step( - "the new phrase opens the library, and the old one no longer", - || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.eventually("the old phrase is refused", |tree| { - tree.text("vault-problem") - .is_some_and(|said| !said.is_empty()) - }); - app.fill("vault-passphrase", NEXT); - app.click("vault-submit"); - app.wait_for("area-notes"); - }, - ); + step("the new phrase opens the library, and the old one no longer", || { + app.fill("vault-passphrase", PASSPHRASE); + app.click("vault-submit"); + app.eventually("the old phrase is refused", |tree| { + tree.text("vault-problem").is_some_and(|said| !said.is_empty()) + }); + app.fill("vault-passphrase", NEXT); + app.click("vault-submit"); + app.wait_for("area-notes"); + }); app.quit(); } diff --git a/e2e/tests/17_folders.rs b/e2e/tests/17_folders.rs index 5f39df7bd..ed5461b6c 100644 --- a/e2e/tests/17_folders.rs +++ b/e2e/tests/17_folders.rs @@ -30,10 +30,7 @@ fn titles(tree: &Tree) -> Vec { /// How many rows of the rail are named `name`: the samples' folders are listed too. fn rows_named(tree: &Tree, name: &str) -> usize { - tree.texts("folder-option") - .iter() - .filter(|row| *row == name) - .count() + tree.texts("folder-option").iter().filter(|row| *row == name).count() } fn crumb(tree: &Tree) -> Option { @@ -43,10 +40,7 @@ fn crumb(tree: &Tree) -> Option { fn centre(node: &Node) -> Pos2 { let rect = node.bounds().expect("a place on screen"); #[expect(clippy::cast_possible_truncation, reason = "points on a screen")] - Pos2::new( - f64::midpoint(rect.x0, rect.x1) as f32, - f64::midpoint(rect.y0, rect.y1) as f32, - ) + Pos2::new(f64::midpoint(rect.x0, rect.x1) as f32, f64::midpoint(rect.y0, rect.y1) as f32) } fn write(app: &mut App, title: &str) { @@ -90,27 +84,23 @@ fn tick_all(app: &mut App) { app.press(key, Modifiers::NONE); } app.eventually("two cards are ticked", |tree| { - tree.text("selection-count") - .is_some_and(|said| said.contains('2')) + tree.text("selection-count").is_some_and(|said| said.contains('2')) }); } fn space_of_its_own(app: &mut App) { - step( - "a space of its own, two notes, a folder made from the rail", - || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - write(app, FIRST); - write(app, SECOND); - make_folder(app, "Perf"); - app.eventually("the folder is listed", |tree| rows_named(tree, "Perf") == 1); - }, - ); + step("a space of its own, two notes, a folder made from the rail", || { + app.click("space-create-open"); + app.fill("space-create-input", SPACE); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown", |tree| { + tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + }); + write(app, FIRST); + write(app, SECOND); + make_folder(app, "Perf"); + app.eventually("the folder is listed", |tree| rows_named(tree, "Perf") == 1); + }); step("a second folder of the same name is refused", || { make_folder(app, "Perf"); @@ -122,36 +112,24 @@ fn space_of_its_own(app: &mut App) { } fn filing(app: &mut App) { - step( - "a whole selection is filed in one gesture, and says where", - || { - tick_all(app); - file_into(app, "Perf"); - app.eventually("both cards wear the folder's chip", |tree| { - tree.count("note-card-folder") == 2 - }); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); - }, - ); + step("a whole selection is filed in one gesture, and says where", || { + tick_all(app); + file_into(app, "Perf"); + app.eventually("both cards wear the folder's chip", |tree| tree.count("note-card-folder") == 2); + // While the bar offers the filing back, Escape would take it back. + app.click("undo-dismiss"); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); + }); - step( - "the folder narrows the canvas, and the space opens it back", - || { - app.click_where("folder-option", named("Perf")); - app.eventually("its notes alone, no chip naming it", |tree| { - crumb(tree).as_deref() == Some("Perf") - && titles(tree).len() == 2 - && !tree.has("note-card-folder") - }); - app.click_where("space-option", named(SPACE)); - app.eventually("the whole space", |tree| crumb(tree).is_none()); - }, - ); + step("the folder narrows the canvas, and the space opens it back", || { + app.click_where("folder-option", named("Perf")); + app.eventually("its notes alone, no chip naming it", |tree| { + crumb(tree).as_deref() == Some("Perf") && titles(tree).len() == 2 && !tree.has("note-card-folder") + }); + app.click_where("space-option", named(SPACE)); + app.eventually("the whole space", |tree| crumb(tree).is_none()); + }); step("a selection taken back out wears no chip at all", || { tick_all(app); @@ -168,114 +146,87 @@ fn filing(app: &mut App) { app.click("note-card-move"); app.fill("note-card-move-filter", "perf"); app.press(Key::Enter, Modifiers::NONE); - app.eventually("one card wears the chip", |tree| { - tree.count("note-card-folder") == 1 - }); + app.eventually("one card wears the chip", |tree| tree.count("note-card-folder") == 1); }); step("deleting the folder leaves every note standing", || { - app.click_where("folder-edit", |node| { - node.label().is_some_and(|label| label.contains("Perf")) - }); + app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Perf"))); app.click("folder-delete"); app.click("folder-delete"); app.eventually("the folder is gone, both notes kept", |tree| { - rows_named(tree, "Perf") == 0 - && titles(tree).len() == 2 - && !tree.has("note-card-folder") + rows_named(tree, "Perf") == 0 && titles(tree).len() == 2 && !tree.has("note-card-folder") }); }); } fn nested(app: &mut App) { - step( - "a folder dragged onto another goes inside it, offered back", - || { - make_folder(app, "Bases"); - app.eventually("listed", |tree| rows_named(tree, "Bases") == 1); - make_folder(app, "Index"); - app.eventually("listed", |tree| rows_named(tree, "Index") == 1); - app.click_where("folder-option", named("Index")); - app.wait_for("folder-breadcrumb-name"); - write(app, NESTED); - app.click_where("space-option", named(SPACE)); - app.eventually("the space", |tree| crumb(tree).is_none()); - let tree = app.tree(); - let index = tree - .all("folder-option") - .into_iter() - .find(|node| node.label() == Some("Index")) - .map(centre) - .unwrap(); - let bases = tree - .all("folder-option") - .into_iter() - .find(|node| node.label() == Some("Bases")) - .map(centre) - .unwrap(); - app.drag(index, bases, PointerButton::Primary); - app.eventually( - "« Index » is drawn inside « Bases », and offered back", - |tree| { - let rows = tree.all("folder-option"); - let left = |name: &str| { - rows.iter() - .find(|node| node.label() == Some(name)) - .and_then(|node| node.bounds()) - .map(|bounds| bounds.x0) - }; - left("Index") > left("Bases") && tree.has("undo-restore") - }, - ); - app.capture("rail-nested"); - app.click("undo-dismiss"); - app.eventually("the bar is gone", |tree| !tree.has("undo-bar")); - }, - ); + step("a folder dragged onto another goes inside it, offered back", || { + make_folder(app, "Bases"); + app.eventually("listed", |tree| rows_named(tree, "Bases") == 1); + make_folder(app, "Index"); + app.eventually("listed", |tree| rows_named(tree, "Index") == 1); + app.click_where("folder-option", named("Index")); + app.wait_for("folder-breadcrumb-name"); + write(app, NESTED); + app.click_where("space-option", named(SPACE)); + app.eventually("the space", |tree| crumb(tree).is_none()); + let tree = app.tree(); + let index = tree + .all("folder-option") + .into_iter() + .find(|node| node.label() == Some("Index")) + .map(centre) + .unwrap(); + let bases = tree + .all("folder-option") + .into_iter() + .find(|node| node.label() == Some("Bases")) + .map(centre) + .unwrap(); + app.drag(index, bases, PointerButton::Primary); + app.eventually("« Index » is drawn inside « Bases », and offered back", |tree| { + let rows = tree.all("folder-option"); + let left = |name: &str| { + rows.iter() + .find(|node| node.label() == Some(name)) + .and_then(|node| node.bounds()) + .map(|bounds| bounds.x0) + }; + left("Index") > left("Bases") && tree.has("undo-restore") + }); + app.capture("rail-nested"); + app.click("undo-dismiss"); + app.eventually("the bar is gone", |tree| !tree.has("undo-bar")); + }); - step( - "an opened folder lists its whole sub-tree, each card naming its own", - || { - app.click_where("folder-option", named("Bases")); - app.eventually("the note of « Index » is listed", |tree| { - crumb(tree).as_deref() == Some("Bases") && titles(tree).contains(&NESTED.to_owned()) - }); - // The chip shows the deepest folder and says its path from the top. - assert_eq!( - app.tree().text("note-card-folder").as_deref(), - Some("Bases › Index") - ); - }, - ); + step("an opened folder lists its whole sub-tree, each card naming its own", || { + app.click_where("folder-option", named("Bases")); + app.eventually("the note of « Index » is listed", |tree| { + crumb(tree).as_deref() == Some("Bases") && titles(tree).contains(&NESTED.to_owned()) + }); + // The chip shows the deepest folder and says its path from the top. + assert_eq!(app.tree().text("note-card-folder").as_deref(), Some("Bases › Index")); + }); - step( - "on the board, a folder that holds folders is a board one level down", - || { - app.click("folder-breadcrumb-back"); - app.eventually("the space", |tree| crumb(tree).is_none()); - app.click("view-board"); - app.click_where("board-zone-open", named("Bases")); - app.eventually("« Index » is its one zone, holding its note", |tree| { - crumb(tree).as_deref() == Some("Bases") - && tree.texts("board-zone-open") == ["Index"] - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually( - "the space's board, « Index » inside « Bases »'s zone", - |tree| { - crumb(tree).is_none() - && tree.texts("board-zone-open").contains(&"Bases".to_owned()) - && tree.texts("board-zone-child").contains(&"Index".to_owned()) - }, - ); - app.click("view-list"); - }, - ); + step("on the board, a folder that holds folders is a board one level down", || { + app.click("folder-breadcrumb-back"); + app.eventually("the space", |tree| crumb(tree).is_none()); + app.click("view-board"); + app.click_where("board-zone-open", named("Bases")); + app.eventually("« Index » is its one zone, holding its note", |tree| { + crumb(tree).as_deref() == Some("Bases") && tree.texts("board-zone-open") == ["Index"] + }); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the space's board, « Index » inside « Bases »'s zone", |tree| { + crumb(tree).is_none() + && tree.texts("board-zone-open").contains(&"Bases".to_owned()) + && tree.texts("board-zone-child").contains(&"Index".to_owned()) + }); + app.click("view-list"); + }); step("a folder made inside another from its panel", || { - app.click_where("folder-edit", |node| { - node.label().is_some_and(|label| label.contains("Index")) - }); + app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Index"))); app.click("folder-subfolder-open"); app.fill("folder-subfolder-input", "Partiels"); app.press(Key::Enter, Modifiers::NONE); @@ -289,65 +240,53 @@ fn nested(app: &mut App) { /// « Bases », holding « Index » and its note, dropped onto the samples' space: the note is found /// there, and the undo bar brings everything back. fn to_another_space(app: &mut App) { - step( - "a folder dragged onto another space goes there with its notes, offered back", - || { - let tree = app.tree(); - let samples = tree - .texts("space-option") + step("a folder dragged onto another space goes there with its notes, offered back", || { + let tree = app.tree(); + let samples = tree + .texts("space-option") + .into_iter() + .find(|name| name != SPACE) + .expect("the samples' space"); + let at = |author_id: &str, name: &str| { + tree.all(author_id) .into_iter() - .find(|name| name != SPACE) - .expect("the samples' space"); - let at = |author_id: &str, name: &str| { - tree.all(author_id) - .into_iter() - .find(|node| node.label() == Some(name)) - .map_or_else(|| panic!("no row {name}"), centre) - }; - let (bases, other) = (at("folder-option", "Bases"), at("space-option", &samples)); - app.drag(bases, other, PointerButton::Primary); - app.wait_for("undo-restore"); - app.click_where("space-option", named(&samples)); - app.eventually("the note of « Index » is in the samples' space", |tree| { - titles(tree).contains(&NESTED.to_owned()) - }); - app.click("undo-restore"); - app.click_where("space-option", named(SPACE)); - app.eventually("back in its space, with its note", |tree| { - titles(tree).contains(&NESTED.to_owned()) - }); - }, - ); + .find(|node| node.label() == Some(name)) + .map_or_else(|| panic!("no row {name}"), centre) + }; + let (bases, other) = (at("folder-option", "Bases"), at("space-option", &samples)); + app.drag(bases, other, PointerButton::Primary); + app.wait_for("undo-restore"); + app.click_where("space-option", named(&samples)); + app.eventually("the note of « Index » is in the samples' space", |tree| { + titles(tree).contains(&NESTED.to_owned()) + }); + app.click("undo-restore"); + app.click_where("space-option", named(SPACE)); + app.eventually("back in its space, with its note", |tree| titles(tree).contains(&NESTED.to_owned())); + }); } fn deleted_with_its_notes(app: &mut App) { - step( - "a folder deleted with its notes puts them in the trash", - || { - make_folder(app, "Jetable"); - app.eventually("the folder is listed", |tree| { - rows_named(tree, "Jetable") == 1 - }); - app.click_where("folder-option", named("Jetable")); - app.wait_for("folder-breadcrumb-name"); - write(app, DOOMED); - app.click_where("folder-edit", |node| { - node.label().is_some_and(|label| label.contains("Jetable")) - }); - app.click("folder-delete-held"); - app.click("folder-delete-held-1"); - app.click("folder-delete"); - app.click("folder-delete"); - app.eventually("the folder is gone, its note with it", |tree| { - rows_named(tree, "Jetable") == 0 && !titles(tree).contains(&DOOMED.to_owned()) - }); - app.click("trash-open"); - app.eventually("the note waits in the trash", |tree| { - tree.texts("trash-row-title").contains(&DOOMED.to_owned()) - }); - app.press(Key::Escape, Modifiers::NONE); - }, - ); + step("a folder deleted with its notes puts them in the trash", || { + make_folder(app, "Jetable"); + app.eventually("the folder is listed", |tree| rows_named(tree, "Jetable") == 1); + app.click_where("folder-option", named("Jetable")); + app.wait_for("folder-breadcrumb-name"); + write(app, DOOMED); + app.click_where("folder-edit", |node| node.label().is_some_and(|label| label.contains("Jetable"))); + app.click("folder-delete-held"); + app.click("folder-delete-held-1"); + app.click("folder-delete"); + app.click("folder-delete"); + app.eventually("the folder is gone, its note with it", |tree| { + rows_named(tree, "Jetable") == 0 && !titles(tree).contains(&DOOMED.to_owned()) + }); + app.click("trash-open"); + app.eventually("the note waits in the trash", |tree| { + tree.texts("trash-row-title").contains(&DOOMED.to_owned()) + }); + app.press(Key::Escape, Modifiers::NONE); + }); } #[test] diff --git a/e2e/tests/18_board.rs b/e2e/tests/18_board.rs index 0923c04b9..434bbda01 100644 --- a/e2e/tests/18_board.rs +++ b/e2e/tests/18_board.rs @@ -18,8 +18,7 @@ fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { } fn is_on(tree: &Tree, author_id: &str) -> bool { - tree.find(author_id) - .is_some_and(|node| node.toggled() == Some(Toggled::True)) + tree.find(author_id).is_some_and(|node| node.toggled() == Some(Toggled::True)) } fn frame_of(tree: &Tree, zone: &str) -> Option { @@ -38,10 +37,7 @@ fn titles_in(tree: &Tree, zone: &str) -> Vec { .into_iter() .filter(|node| { node.bounds().is_some_and(|card| { - card.x0 >= frame.x0 - && card.x1 <= frame.x1 - && card.y0 >= frame.y0 - && card.y1 <= frame.y1 + card.x0 >= frame.x0 && card.x1 <= frame.x1 && card.y0 >= frame.y0 && card.y1 <= frame.y1 }) }) .map(|node| node.label().or(node.value()).unwrap_or_default().to_owned()) @@ -49,10 +45,7 @@ fn titles_in(tree: &Tree, zone: &str) -> Vec { } fn frames(tree: &Tree) -> Vec { - tree.all("board-zone") - .into_iter() - .filter_map(Node::bounds) - .collect() + tree.all("board-zone").into_iter().filter_map(Node::bounds).collect() } /// A note written from the editor in whatever space or folder is shown. @@ -77,56 +70,48 @@ fn choose_space(app: &mut App, name: &str) { /// A space of its own: two folders, a note filed in the first, one loose. fn seed(app: &mut App) { - step( - "a space of its own: two folders, a note filed, one loose", - || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); + step("a space of its own: two folders, a note filed, one loose", || { + app.click("space-create-open"); + app.fill("space-create-input", SPACE); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown, empty", |tree| { + tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + }); + for name in ["Perf", "Migrations"] { + app.click("folder-create-open"); + app.fill("folder-create-input", name); app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown, empty", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + app.eventually("the folder is listed", |tree| { + tree.texts("folder-option").contains(&name.to_owned()) }); - for name in ["Perf", "Migrations"] { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| { - tree.texts("folder-option").contains(&name.to_owned()) - }); - } - app.click_where("folder-option", named("Perf")); - app.wait_for("folder-breadcrumb-name"); - write(app, FILED); - choose_space(app, SPACE); - write(app, LOOSE); - }, - ); + } + app.click_where("folder-option", named("Perf")); + app.wait_for("folder-breadcrumb-name"); + write(app, FILED); + choose_space(app, SPACE); + write(app, LOOSE); + }); } /// What a card on the board still does: tick its items, take the selection, take the arrows. fn on_the_board(app: &mut App) { - step( - "a todo list is ticked on the board, and shown ticked", - || { - app.click("new-note-kind"); - app.click("new-note-checklist"); - app.fill("editor-title", LIST); - app.click("checklist-add"); - app.eventually("the new row has the focus", |tree| { - tree.focused().starts_with("checklist-text") - }); - app.type_text("Tag"); - app.click("editor-close"); - app.eventually("the list is a loose card", |tree| { - tree.texts("board-loose-card").contains(&LIST.to_owned()) - }); - app.click_nth("note-card-item", 0); - app.eventually("the item is ticked", |tree| { - tree.find("note-card-item") - .is_some_and(|node| node.toggled() == Some(Toggled::True)) - }); - }, - ); + step("a todo list is ticked on the board, and shown ticked", || { + app.click("new-note-kind"); + app.click("new-note-checklist"); + app.fill("editor-title", LIST); + app.click("checklist-add"); + app.eventually("the new row has the focus", |tree| tree.focused().starts_with("checklist-text")); + app.type_text("Tag"); + app.click("editor-close"); + app.eventually("the list is a loose card", |tree| { + tree.texts("board-loose-card").contains(&LIST.to_owned()) + }); + app.click_nth("note-card-item", 0); + app.eventually("the item is ticked", |tree| { + tree.find("note-card-item") + .is_some_and(|node| node.toggled() == Some(Toggled::True)) + }); + }); step("the corner is the selection tick's", || { let title = app.tree().texts("board-loose-card")[0].clone(); @@ -142,22 +127,17 @@ fn on_the_board(app: &mut App) { panel_kept(app); }); - step( - "the arrows walk the cards as the board lays them out", - || { - app.click("search-input"); - app.press(Key::ArrowDown, Modifiers::NONE); - for _ in 0..3 { - app.press(Key::ArrowLeft, Modifiers::NONE); - } - app.eventually("the first card of the board has the focus", |tree| { - tree.focused().contains(FILED) - }); - app.press(Key::ArrowRight, Modifiers::NONE); - app.eventually("then the next", |tree| !tree.focused().contains(FILED)); - app.press(Key::Escape, Modifiers::NONE); - }, - ); + step("the arrows walk the cards as the board lays them out", || { + app.click("search-input"); + app.press(Key::ArrowDown, Modifiers::NONE); + for _ in 0..3 { + app.press(Key::ArrowLeft, Modifiers::NONE); + } + app.eventually("the first card of the board has the focus", |tree| tree.focused().contains(FILED)); + app.press(Key::ArrowRight, Modifiers::NONE); + app.eventually("then the next", |tree| !tree.focused().contains(FILED)); + app.press(Key::Escape, Modifiers::NONE); + }); } fn open_title(tree: &Tree) -> Option<&str> { @@ -192,39 +172,27 @@ fn lit(tree: &Tree, title: &str) -> Option { /// A search dims on the board, and the tidy names what it would touch. fn dimmed(app: &mut App) { - step( - "a search dims what it does not match, and drops nothing", - || { - app.click("search-input"); - app.type_text("EXPLAIN"); - app.eventually("the loose card is dimmed", |tree| { - lit(tree, LOOSE) == Some(false) - }); - let tree = app.tree(); - assert_eq!(lit(&tree, FILED), Some(true)); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - app.capture("board-dimmed"); - app.click("search-clear"); - app.eventually("the card is lit again", |tree| { - lit(tree, LOOSE) == Some(true) - }); - }, - ); + step("a search dims what it does not match, and drops nothing", || { + app.click("search-input"); + app.type_text("EXPLAIN"); + app.eventually("the loose card is dimmed", |tree| lit(tree, LOOSE) == Some(false)); + let tree = app.tree(); + assert_eq!(lit(&tree, FILED), Some(true)); + assert_eq!(titles_in(&tree, "Perf"), [FILED]); + app.capture("board-dimmed"); + app.click("search-clear"); + app.eventually("the card is lit again", |tree| lit(tree, LOOSE) == Some(true)); + }); - step( - "reorganising says how many folders and cards it moves", - || { - app.click("board-tidy-more"); - app.eventually("the entry counts two of each", |tree| { - tree.text("board-tidy-everything") - .is_some_and(|said| said.matches('2').count() == 2) - }); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the menu is closed", |tree| { - !tree.has("board-tidy-everything") - }); - }, - ); + step("reorganising says how many folders and cards it moves", || { + app.click("board-tidy-more"); + app.eventually("the entry counts two of each", |tree| { + tree.text("board-tidy-everything") + .is_some_and(|said| said.matches('2').count() == 2) + }); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the menu is closed", |tree| !tree.has("board-tidy-everything")); + }); } #[test] @@ -237,43 +205,34 @@ fn board() { seed(&mut app); - step( - "the list is the default, and there is no board across every space", - || { - assert!(is_on(&app.tree(), "view-list")); - assert!(!app.has("board")); - app.click("space-option-all"); - app.eventually("the board is offered disabled", |tree| { - tree.find("view-board").is_some_and(Node::is_disabled) - }); - choose_space(&mut app, SPACE); - }, - ); + step("the list is the default, and there is no board across every space", || { + assert!(is_on(&app.tree(), "view-list")); + assert!(!app.has("board")); + app.click("space-option-all"); + app.eventually("the board is offered disabled", |tree| { + tree.find("view-board").is_some_and(Node::is_disabled) + }); + choose_space(&mut app, SPACE); + }); - step( - "each folder is a zone holding its notes, the loose ones beside", - || { - app.click("view-board"); - app.eventually("the zones are drawn", |tree| tree.count("board-zone") == 2); - let tree = app.tree(); - let mut zones = tree.texts("board-zone-open"); - zones.sort(); - assert_eq!(zones, ["Migrations", "Perf"]); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - assert!(titles_in(&tree, "Migrations").is_empty()); - assert_eq!(tree.texts("board-loose-card"), [LOOSE]); - // The same card as the list's: its title, and the layer that opens it. - assert_eq!(tree.count("note-card-open"), 2); - let [first, second] = frames(&tree)[..] else { - panic!("two zones"); - }; - assert!( - first.x1 <= second.x0 || second.x1 <= first.x0, - "side by side" - ); - app.capture("board"); - }, - ); + step("each folder is a zone holding its notes, the loose ones beside", || { + app.click("view-board"); + app.eventually("the zones are drawn", |tree| tree.count("board-zone") == 2); + let tree = app.tree(); + let mut zones = tree.texts("board-zone-open"); + zones.sort(); + assert_eq!(zones, ["Migrations", "Perf"]); + assert_eq!(titles_in(&tree, "Perf"), [FILED]); + assert!(titles_in(&tree, "Migrations").is_empty()); + assert_eq!(tree.texts("board-loose-card"), [LOOSE]); + // The same card as the list's: its title, and the layer that opens it. + assert_eq!(tree.count("note-card-open"), 2); + let [first, second] = frames(&tree)[..] else { + panic!("two zones"); + }; + assert!(first.x1 <= second.x0 || second.x1 <= first.x0, "side by side"); + app.capture("board"); + }); on_the_board(&mut app); dimmed(&mut app); @@ -281,21 +240,16 @@ fn board() { let before = frames(&app.tree()); let mut app = app.relaunch(); - step( - "a relaunch comes back on the board, its layout unchanged", - || { - app.fill("vault-passphrase", e2e::PASSPHRASE); - app.click("vault-submit"); - app.eventually("the board is back", |tree| tree.count("board-zone") == 2); - assert_eq!(frames(&app.tree()), before); - }, - ); + step("a relaunch comes back on the board, its layout unchanged", || { + app.fill("vault-passphrase", e2e::PASSPHRASE); + app.click("vault-submit"); + app.eventually("the board is back", |tree| tree.count("board-zone") == 2); + assert_eq!(frames(&app.tree()), before); + }); step("the view is remembered space by space", || { choose_space(&mut app, &samples); - app.eventually("the samples are listed", |tree| { - !tree.has("board") && tree.has("note-card") - }); + app.eventually("the samples are listed", |tree| !tree.has("board") && tree.has("note-card")); choose_space(&mut app, SPACE); app.eventually("the board is back", |tree| tree.has("board")); }); @@ -309,21 +263,18 @@ fn board() { app.wait_for("board"); }); - step( - "a window larger than the board is pointer ground all over", - || { - app.resize(1600, 1000); - app.eventually("the surface covers the ground", |tree| { - let (Some(ground), Some(surface)) = ( - tree.find("board").and_then(Node::bounds), - tree.find("board-surface").and_then(Node::bounds), - ) else { - return false; - }; - surface.x1 >= ground.x1 && surface.y1 >= ground.y1 - }); - }, - ); + step("a window larger than the board is pointer ground all over", || { + app.resize(1600, 1000); + app.eventually("the surface covers the ground", |tree| { + let (Some(ground), Some(surface)) = ( + tree.find("board").and_then(Node::bounds), + tree.find("board-surface").and_then(Node::bounds), + ) else { + return false; + }; + surface.x1 >= ground.x1 && surface.y1 >= ground.y1 + }); + }); app.quit(); } diff --git a/e2e/tests/19_board_gesture.rs b/e2e/tests/19_board_gesture.rs index febff3b1d..feaaccef4 100644 --- a/e2e/tests/19_board_gesture.rs +++ b/e2e/tests/19_board_gesture.rs @@ -33,10 +33,7 @@ fn point(x: f64, y: f64) -> Pos2 { } fn centre(rect: Rect) -> Pos2 { - point( - f64::midpoint(rect.x0, rect.x1), - f64::midpoint(rect.y0, rect.y1), - ) + point(f64::midpoint(rect.x0, rect.x1), f64::midpoint(rect.y0, rect.y1)) } /// The titles drawn inside `zone`. @@ -47,9 +44,8 @@ fn titles_in(tree: &Tree, zone: &str) -> Vec { tree.all("board-zone-card") .into_iter() .filter(|node| { - node.bounds().is_some_and(|card| { - card.x0 >= frame.x0 && card.x1 <= frame.x1 && card.y0 >= frame.y0 - }) + node.bounds() + .is_some_and(|card| card.x0 >= frame.x0 && card.x1 <= frame.x1 && card.y0 >= frame.y0) }) .map(|node| node.label().unwrap_or_default().to_owned()) .collect() @@ -58,15 +54,12 @@ fn titles_in(tree: &Tree, zone: &str) -> Vec { /// A zone's control, the one in that zone's header. fn control_of(tree: &Tree, author_id: &str, zone: &str) -> Option { let frame = bounds_of(tree, "board-zone", zone)?; - tree.all(author_id) - .into_iter() - .filter_map(Node::bounds) - .find(|control| { - control.x0 >= frame.x0 - 1.0 - && control.x1 <= frame.x1 + 1.0 - && control.y0 >= frame.y0 - 1.0 - && control.y1 <= frame.y1 + 1.0 - }) + tree.all(author_id).into_iter().filter_map(Node::bounds).find(|control| { + control.x0 >= frame.x0 - 1.0 + && control.x1 <= frame.x1 + 1.0 + && control.y0 >= frame.y0 - 1.0 + && control.y1 <= frame.y1 + 1.0 + }) } fn write(app: &mut App, title: &str) { @@ -88,9 +81,7 @@ fn filed(node: &Node) -> bool { fn file_into(app: &mut App, name: &str) { app.click("selection-move"); let end = format!(" › {name}"); - app.click_where("selection-move-place", |node| { - node.label().is_some_and(|label| label.ends_with(&end)) - }); + app.click_where("selection-move-place", |node| node.label().is_some_and(|label| label.ends_with(&end))); } fn reopen(app: App) -> App { @@ -102,54 +93,46 @@ fn reopen(app: App) -> App { } fn seed(app: &mut App) { - step( - "a space of its own: two folders, a note filed, one loose", - || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); + step("a space of its own: two folders, a note filed, one loose", || { + app.click("space-create-open"); + app.fill("space-create-input", SPACE); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown", |tree| { + tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + }); + for name in ["Perf", "Migrations"] { + app.click("folder-create-open"); + app.fill("folder-create-input", name); app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + app.eventually("the folder is listed", |tree| { + tree.texts("folder-option").contains(&name.to_owned()) }); - for name in ["Perf", "Migrations"] { - app.click("folder-create-open"); - app.fill("folder-create-input", name); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| { - tree.texts("folder-option").contains(&name.to_owned()) - }); - } - app.click_where("folder-option", named("Perf")); - app.wait_for("folder-breadcrumb-name"); - write(app, FILED); - app.click_where("space-option", named(SPACE)); - app.eventually("the space is shown", |tree| { - !tree.has("folder-breadcrumb-name") - }); - write(app, LOOSE); - app.click("view-board"); - app.eventually("the board is drawn", |tree| tree.count("board-zone") == 2); - }, - ); + } + app.click_where("folder-option", named("Perf")); + app.wait_for("folder-breadcrumb-name"); + write(app, FILED); + app.click_where("space-option", named(SPACE)); + app.eventually("the space is shown", |tree| !tree.has("folder-breadcrumb-name")); + write(app, LOOSE); + app.click("view-board"); + app.eventually("the board is drawn", |tree| tree.count("board-zone") == 2); + }); } fn cards(app: &mut App) { - step( - "a card dragged into a zone is filed there, and its place forgotten", - || { - let tree = app.tree(); - let card = bounds_of(&tree, "board-loose-card", LOOSE).unwrap(); - let zone = bounds_of(&tree, "board-zone", "Migrations").unwrap(); - // The card lands where its corner does: the grab, at its centre, keeps the offset. - let into = point(zone.x0 + 150.0, zone.y0 + 120.0); - app.drag(centre(card), into, PointerButton::Primary); - app.eventually("the card flows in the zone", |tree| { - titles_in(tree, "Migrations") == [LOOSE] - && !tree.texts("board-loose-card").contains(&LOOSE.to_owned()) - }); - app.capture("board-filed"); - }, - ); + step("a card dragged into a zone is filed there, and its place forgotten", || { + let tree = app.tree(); + let card = bounds_of(&tree, "board-loose-card", LOOSE).unwrap(); + let zone = bounds_of(&tree, "board-zone", "Migrations").unwrap(); + // The card lands where its corner does: the grab, at its centre, keeps the offset. + let into = point(zone.x0 + 150.0, zone.y0 + 120.0); + app.drag(centre(card), into, PointerButton::Primary); + app.eventually("the card flows in the zone", |tree| { + titles_in(tree, "Migrations") == [LOOSE] + && !tree.texts("board-loose-card").contains(&LOOSE.to_owned()) + }); + app.capture("board-filed"); + }); step("dropped on the ground, it comes back out", || { let card = bounds_of(&app.tree(), "board-zone-card", LOOSE).unwrap(); @@ -166,54 +149,38 @@ fn cards(app: &mut App) { let card = bounds_of(&tree, "board-loose-card", LOOSE).unwrap(); let row = bounds_of(&tree, "folder-option", "Migrations").unwrap(); app.drag(centre(card), centre(row), PointerButton::Primary); - app.eventually("the card flows in the zone", |tree| { - titles_in(tree, "Migrations") == [LOOSE] - }); + app.eventually("the card flows in the zone", |tree| titles_in(tree, "Migrations") == [LOOSE]); let card = bounds_of(&app.tree(), "board-zone-card", LOOSE).unwrap(); let ground = Pos2::new(centre(card).x, centre(card).y + 360.0); app.drag(centre(card), ground, PointerButton::Primary); - app.eventually("the card is loose again", |tree| { - titles_in(tree, "Migrations").is_empty() - }); + app.eventually("the card is loose again", |tree| titles_in(tree, "Migrations").is_empty()); }); - step( - "the keyboard files with no pointer, from the selection bar", - || { - app.click_where("note-card-check", filed); - app.wait_for("selection-count"); - file_into(app, "Migrations"); - app.eventually("the note is in the other zone", |tree| { - titles_in(tree, "Migrations") == [FILED] - }); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.click_where("note-card-check", filed); - file_into(app, "Perf"); - app.eventually("and back", |tree| titles_in(tree, "Perf") == [FILED]); - // While the bar offers the filing back, Escape would take it back. - app.click("undo-dismiss"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); - }, - ); + step("the keyboard files with no pointer, from the selection bar", || { + app.click_where("note-card-check", filed); + app.wait_for("selection-count"); + file_into(app, "Migrations"); + app.eventually("the note is in the other zone", |tree| titles_in(tree, "Migrations") == [FILED]); + // While the bar offers the filing back, Escape would take it back. + app.click("undo-dismiss"); + app.press(Key::Escape, Modifiers::NONE); + app.click_where("note-card-check", filed); + file_into(app, "Perf"); + app.eventually("and back", |tree| titles_in(tree, "Perf") == [FILED]); + // While the bar offers the filing back, Escape would take it back. + app.click("undo-dismiss"); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); + }); step("a zone's menu ticks every card it holds", || { - app.click_where("board-zone-menu", |node| { - node.label().is_some_and(|label| label.contains("Perf")) - }); + app.click_where("board-zone-menu", |node| node.label().is_some_and(|label| label.contains("Perf"))); app.click("folder-select-notes"); app.eventually("its card is ticked", |tree| { - tree.text("selection-count") - .is_some_and(|said| said.contains('1')) + tree.text("selection-count").is_some_and(|said| said.contains('1')) }); app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); }); } @@ -223,119 +190,87 @@ fn zones(app: &mut App) { let frame = bounds_of(&tree, "board-zone", "Perf").unwrap(); for control in ["board-zone-grip", "board-zone-open", "board-zone-menu"] { let drawn = control_of(&tree, control, "Perf").unwrap(); - assert!( - drawn.y1 <= frame.y0 + ZONE_HEADER, - "{control} overflows the header" - ); + assert!(drawn.y1 <= frame.y0 + ZONE_HEADER, "{control} overflows the header"); } }); - step( - "a zone moved by its grip lands on the grid and keeps its notes", - || { - let tree = app.tree(); - let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); - let grip = control_of(&tree, "board-zone-grip", "Perf").unwrap(); - let to = centre(grip) + egui::vec2(93.0, 141.0); - app.drag(centre(grip), to, PointerButton::Primary); - app.eventually("the zone moved, its size kept", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|moved| { - (moved.x0 - before.x0).abs() > 0.5 - && (moved.width() - before.width()).abs() < 0.5 - }) - }); - assert_eq!(titles_in(&app.tree(), "Perf"), [FILED]); - }, - ); + step("a zone moved by its grip lands on the grid and keeps its notes", || { + let tree = app.tree(); + let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); + let grip = control_of(&tree, "board-zone-grip", "Perf").unwrap(); + let to = centre(grip) + egui::vec2(93.0, 141.0); + app.drag(centre(grip), to, PointerButton::Primary); + app.eventually("the zone moved, its size kept", |tree| { + bounds_of(tree, "board-zone", "Perf").is_some_and(|moved| { + (moved.x0 - before.x0).abs() > 0.5 && (moved.width() - before.width()).abs() < 0.5 + }) + }); + assert_eq!(titles_in(&app.tree(), "Perf"), [FILED]); + }); - step( - "resized by its corner, it captures and releases nothing", - || { - let tree = app.tree(); - let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); - let corner = control_of(&tree, "board-zone-resize", "Perf").unwrap(); - let to = centre(corner) + egui::vec2(260.0, 120.0); - app.drag(centre(corner), to, PointerButton::Primary); - app.eventually("the zone is wider, where it was", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|resized| { - resized.width() > before.width() + 100.0 && (resized.x0 - before.x0).abs() < 0.5 - }) - }); - let tree = app.tree(); - assert_eq!(titles_in(&tree, "Perf"), [FILED]); - assert!(tree.texts("board-loose-card").contains(&LOOSE.to_owned())); - }, - ); + step("resized by its corner, it captures and releases nothing", || { + let tree = app.tree(); + let before = bounds_of(&tree, "board-zone", "Perf").unwrap(); + let corner = control_of(&tree, "board-zone-resize", "Perf").unwrap(); + let to = centre(corner) + egui::vec2(260.0, 120.0); + app.drag(centre(corner), to, PointerButton::Primary); + app.eventually("the zone is wider, where it was", |tree| { + bounds_of(tree, "board-zone", "Perf").is_some_and(|resized| { + resized.width() > before.width() + 100.0 && (resized.x0 - before.x0).abs() < 0.5 + }) + }); + let tree = app.tree(); + assert_eq!(titles_in(&tree, "Perf"), [FILED]); + assert!(tree.texts("board-loose-card").contains(&LOOSE.to_owned())); + }); - step( - "a band drawn on the ground becomes the folder named there", - || { - let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); - let from = point(ground.x0 + 40.0, ground.y1 - 260.0); - app.drag( - from, - from + egui::vec2(300.0, 220.0), - PointerButton::Primary, - ); - app.fill("folder-name-input", "Reporting"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the zone is drawn where it was drawn", |tree| { - tree.texts("board-zone-open") - .contains(&"Reporting".to_owned()) - }); - app.capture("board-drawn-zone"); - }, - ); + step("a band drawn on the ground becomes the folder named there", || { + let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); + let from = point(ground.x0 + 40.0, ground.y1 - 260.0); + app.drag(from, from + egui::vec2(300.0, 220.0), PointerButton::Primary); + app.fill("folder-name-input", "Reporting"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the zone is drawn where it was drawn", |tree| { + tree.texts("board-zone-open").contains(&"Reporting".to_owned()) + }); + app.capture("board-drawn-zone"); + }); } fn selecting(app: &mut App) { - step( - "a right-button sweep ticks the cards it crosses, zones included", - || { - let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); - let from = point(ground.x0 + 4.0, ground.y0 + 4.0); - let to = point(ground.x1 - 40.0, ground.y1 - 60.0); - app.drag(from, to, PointerButton::Secondary); - app.eventually("both cards are ticked", |tree| { - tree.text("selection-count") - .is_some_and(|said| said.contains('2')) - }); - assert!( - !app.has("folder-name-input"), - "the right button draws no folder" - ); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the selection is let go", |tree| { - !tree.has("selection-count") - }); - }, - ); + step("a right-button sweep ticks the cards it crosses, zones included", || { + let ground = app.tree().find("board").and_then(Node::bounds).unwrap(); + let from = point(ground.x0 + 4.0, ground.y0 + 4.0); + let to = point(ground.x1 - 40.0, ground.y1 - 60.0); + app.drag(from, to, PointerButton::Secondary); + app.eventually("both cards are ticked", |tree| { + tree.text("selection-count").is_some_and(|said| said.contains('2')) + }); + assert!(!app.has("folder-name-input"), "the right button draws no folder"); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the selection is let go", |tree| !tree.has("selection-count")); + }); } /// One step: the core writes in order, so the undo of the reorganisation puts back the layout /// aligning left — the hand's, if aligning moved no zone. fn tidying(app: &mut App) { - step( - "aligning leaves the zones; reorganising moves them, and its undo puts the hand's back", - || { - let by_hand = bounds_of(&app.tree(), "board-zone", "Perf").unwrap(); - app.click("board-tidy"); - app.click("board-tidy-more"); - app.click("board-tidy-everything"); - app.eventually("the zone is back at its seat", |tree| { - bounds_of(tree, "board-zone", "Perf") - .is_some_and(|seat| (seat.x0 - by_hand.x0).abs() > 0.5) - && tree.has("undo-restore") - }); - app.capture("board-reorganised"); - app.click("undo-restore"); - app.eventually("the hand's layout is back", |tree| { - bounds_of(tree, "board-zone", "Perf").is_some_and(|back| { - (back.x0 - by_hand.x0).abs() < 0.5 && (back.y0 - by_hand.y0).abs() < 0.5 - }) - }); - }, - ); + step("aligning leaves the zones; reorganising moves them, and its undo puts the hand's back", || { + let by_hand = bounds_of(&app.tree(), "board-zone", "Perf").unwrap(); + app.click("board-tidy"); + app.click("board-tidy-more"); + app.click("board-tidy-everything"); + app.eventually("the zone is back at its seat", |tree| { + bounds_of(tree, "board-zone", "Perf").is_some_and(|seat| (seat.x0 - by_hand.x0).abs() > 0.5) + && tree.has("undo-restore") + }); + app.capture("board-reorganised"); + app.click("undo-restore"); + app.eventually("the hand's layout is back", |tree| { + bounds_of(tree, "board-zone", "Perf") + .is_some_and(|back| (back.x0 - by_hand.x0).abs() < 0.5 && (back.y0 - by_hand.y0).abs() < 0.5) + }); + }); } #[test] diff --git a/e2e/tests/20_folder_descent.rs b/e2e/tests/20_folder_descent.rs index d256c785f..44ce87427 100644 --- a/e2e/tests/20_folder_descent.rs +++ b/e2e/tests/20_folder_descent.rs @@ -57,80 +57,61 @@ fn clear(app: &mut App) { } fn seed(app: &mut App) { - step( - "a space of its own, a folder holding one note, one loose", - || { - app.click("space-create-open"); - app.fill("space-create-input", SPACE); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown", |tree| { - tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") - }); - app.click("folder-create-open"); - app.fill("folder-create-input", "Perf"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| tree.has("folder-option")); - app.click_where("folder-option", named("Perf")); - app.eventually( - "empty, it offers the card to create from, not a search", - |tree| { - tree.has("create-ghost") - && !tree.has("canvas-no-results") - && heading(tree).to_uppercase().starts_with("PERF") - }, - ); - write(app, "create-ghost", INSIDE); - app.click_where("space-option", named(SPACE)); - app.eventually("the space is shown", |tree| crumb(tree).is_none()); - write(app, "new-note", LOOSE); - app.click("view-board"); - app.wait_for("board-zone"); - }, - ); + step("a space of its own, a folder holding one note, one loose", || { + app.click("space-create-open"); + app.fill("space-create-input", SPACE); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown", |tree| { + tree.texts("space-option").contains(&SPACE.to_owned()) && !tree.has("note-card") + }); + app.click("folder-create-open"); + app.fill("folder-create-input", "Perf"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the folder is listed", |tree| tree.has("folder-option")); + app.click_where("folder-option", named("Perf")); + app.eventually("empty, it offers the card to create from, not a search", |tree| { + tree.has("create-ghost") + && !tree.has("canvas-no-results") + && heading(tree).to_uppercase().starts_with("PERF") + }); + write(app, "create-ghost", INSIDE); + app.click_where("space-option", named(SPACE)); + app.eventually("the space is shown", |tree| crumb(tree).is_none()); + write(app, "new-note", LOOSE); + app.click("view-board"); + app.wait_for("board-zone"); + }); } fn inside(app: &mut App) { - step( - "a zone's title opens its folder, a flat grid of its notes", - || { - app.click_where("board-zone-open", named("Perf")); - app.eventually("the breadcrumb names it, the grid shows its note", |tree| { - crumb(tree).as_deref() == Some("Perf") - && !tree.has("board") - && titles(tree) == [INSIDE] - }); - let tree = app.tree(); - assert!( - heading(&tree).to_uppercase().starts_with("PERF"), - "{}", - heading(&tree) - ); - for gone in ["space-switcher", "view-board", "folder-switcher"] { - assert!(!tree.has(gone), "{gone} is put away"); - } - assert!(tree.has("create-ghost"), "a note is made from here"); - app.capture("folder-open"); - }, - ); - - step( - "a search stays inside the folder, and drops the ghost", - || { - search(app, "EXPLAIN"); - // The heading follows the field at once, the ghost the view once the search rests. - app.eventually("found inside, the list no longer named after it", |tree| { - titles(tree) == [INSIDE] - && !heading(tree).to_uppercase().starts_with("PERF") - && !tree.has("create-ghost") - }); - search(app, "Dump"); - app.eventually( - "a note of the space outside it stays out of reach", - |tree| tree.has("canvas-no-results") && crumb(tree).is_some(), - ); - clear(app); - }, - ); + step("a zone's title opens its folder, a flat grid of its notes", || { + app.click_where("board-zone-open", named("Perf")); + app.eventually("the breadcrumb names it, the grid shows its note", |tree| { + crumb(tree).as_deref() == Some("Perf") && !tree.has("board") && titles(tree) == [INSIDE] + }); + let tree = app.tree(); + assert!(heading(&tree).to_uppercase().starts_with("PERF"), "{}", heading(&tree)); + for gone in ["space-switcher", "view-board", "folder-switcher"] { + assert!(!tree.has(gone), "{gone} is put away"); + } + assert!(tree.has("create-ghost"), "a note is made from here"); + app.capture("folder-open"); + }); + + step("a search stays inside the folder, and drops the ghost", || { + search(app, "EXPLAIN"); + // The heading follows the field at once, the ghost the view once the search rests. + app.eventually("found inside, the list no longer named after it", |tree| { + titles(tree) == [INSIDE] + && !heading(tree).to_uppercase().starts_with("PERF") + && !tree.has("create-ghost") + }); + search(app, "Dump"); + app.eventually("a note of the space outside it stays out of reach", |tree| { + tree.has("canvas-no-results") && crumb(tree).is_some() + }); + clear(app); + }); step("a note made here arrives filed", || { write(app, "new-note", MADE); @@ -168,9 +149,7 @@ fn leaving(app: &mut App) { app.click_where("board-zone-open", named("Performance")); app.wait_for("folder-breadcrumb-name"); app.click("folder-breadcrumb-back"); - app.eventually("back on the board", |tree| { - crumb(tree).is_none() && tree.has("board") - }); + app.eventually("back on the board", |tree| crumb(tree).is_none() && tree.has("board")); assert!( app.tree() .all("space-option") @@ -179,21 +158,16 @@ fn leaving(app: &mut App) { ); }); - step( - "deleted from inside it, its notes stay on the board", - || { - app.click_where("board-zone-open", named("Performance")); - app.wait_for("folder-breadcrumb-name"); - app.click("folder-breadcrumb-menu"); - app.click("folder-delete"); - app.click("folder-delete"); - app.eventually("the folder is gone, its notes loose", |tree| { - crumb(tree).is_none() - && !tree.has("board-zone") - && tree.count("board-loose-card") == 3 - }); - }, - ); + step("deleted from inside it, its notes stay on the board", || { + app.click_where("board-zone-open", named("Performance")); + app.wait_for("folder-breadcrumb-name"); + app.click("folder-breadcrumb-menu"); + app.click("folder-delete"); + app.click("folder-delete"); + app.eventually("the folder is gone, its notes loose", |tree| { + crumb(tree).is_none() && !tree.has("board-zone") && tree.count("board-loose-card") == 3 + }); + }); } #[test] diff --git a/e2e/tests/21_folders_travel.rs b/e2e/tests/21_folders_travel.rs index 191e4287e..778150af2 100644 --- a/e2e/tests/21_folders_travel.rs +++ b/e2e/tests/21_folders_travel.rs @@ -18,10 +18,7 @@ fn named(name: &str) -> impl Fn(&Node) -> bool + '_ { } fn folders_named(tree: &Tree, name: &str) -> usize { - tree.texts("folder-option") - .iter() - .filter(|row| *row == name) - .count() + tree.texts("folder-option").iter().filter(|row| *row == name).count() } fn write(app: &mut App, title: &str) { @@ -36,9 +33,7 @@ fn make_folder(app: &mut App, name: &str) { app.click("folder-create-open"); app.fill("folder-create-input", name); app.press(Key::Enter, Modifiers::NONE); - app.eventually("the folder is listed", |tree| { - folders_named(tree, name) == 1 - }); + app.eventually("the folder is listed", |tree| folders_named(tree, name) == 1); } fn menu(app: &mut App, entry: &str) { @@ -89,16 +84,13 @@ fn folders_travel() { menu(&mut app, "import"); report(&mut app); app.click_where("space-option", named(SPACE)); - app.eventually("the two notes are drawn", |tree| { - tree.count("note-card") == 2 - }); + app.eventually("the two notes are drawn", |tree| tree.count("note-card") == 2); let tree = app.tree(); assert_eq!(folders_named(&tree, CITED), 1); assert_eq!(folders_named(&tree, UNCITED), 0, "cited by nobody"); app.click_where("folder-option", named(CITED)); app.eventually("the folder holds its note", |tree| { - tree.count("note-card") == 1 - && tree.texts("note-card-title").contains(&FILED.to_owned()) + tree.count("note-card") == 1 && tree.texts("note-card-title").contains(&FILED.to_owned()) }); }); diff --git a/e2e/tests/22_note_history.rs b/e2e/tests/22_note_history.rs index dbff7840b..29d1e970c 100644 --- a/e2e/tests/22_note_history.rs +++ b/e2e/tests/22_note_history.rs @@ -26,9 +26,7 @@ fn open(app: &mut App, title: &str) { tree.count("note-card") == 1 && tree.texts("note-card").contains(&title.to_owned()) }); app.press(Key::ArrowDown, Modifiers::NONE); - app.eventually("the card has the focus", |tree| { - tree.focused().starts_with("note-card-open") - }); + app.eventually("the card has the focus", |tree| tree.focused().starts_with("note-card-open")); app.press(Key::Enter, Modifiers::NONE); app.wait_for("editor-title"); } @@ -109,18 +107,15 @@ fn note_history() { app.capture("revision-preview"); }); - step( - "going back puts the body in the editor, nothing newer kept", - || { - app.click("revision-restore"); - app.eventually("the oldest body back", |tree| code(tree) == "select 1"); - app.eventually("nothing newer kept", |tree| !tree.has("revisions-toggle")); - close(&mut app); - open(&mut app, TITLE); - app.eventually("still the oldest body", |tree| code(tree) == "select 1"); - close(&mut app); - }, - ); + step("going back puts the body in the editor, nothing newer kept", || { + app.click("revision-restore"); + app.eventually("the oldest body back", |tree| code(tree) == "select 1"); + app.eventually("nothing newer kept", |tree| !tree.has("revisions-toggle")); + close(&mut app); + open(&mut app, TITLE); + app.eventually("still the oldest body", |tree| code(tree) == "select 1"); + close(&mut app); + }); step("a todo list keeps no history", || { todo_list_keeps_none(&mut app); diff --git a/e2e/tests/23_backups.rs b/e2e/tests/23_backups.rs index e692874f9..66cd1a5c2 100644 --- a/e2e/tests/23_backups.rs +++ b/e2e/tests/23_backups.rs @@ -61,20 +61,17 @@ fn backups() { close(&mut app); }); - step( - "the trigger names what a restore would do, and runs none", - || { - security(&mut app); - app.click("backup-restore"); - app.wait_for("backup-confirm"); - strip_shown(&mut app); - assert!(!app.has("backup-restore"), "the trigger gave way"); - assert!(app.has("settings-dialog")); - app.click("backup-cancel"); - app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); - close(&mut app); - }, - ); + step("the trigger names what a restore would do, and runs none", || { + security(&mut app); + app.click("backup-restore"); + app.wait_for("backup-confirm"); + strip_shown(&mut app); + assert!(!app.has("backup-restore"), "the trigger gave way"); + assert!(app.has("settings-dialog")); + app.click("backup-cancel"); + app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); + close(&mut app); + }); step("it replaces the library and goes back to the gate", || { app.click("new-note"); diff --git a/e2e/tests/24_forgotten_passphrase.rs b/e2e/tests/24_forgotten_passphrase.rs index e9125f93d..983d69d6c 100644 --- a/e2e/tests/24_forgotten_passphrase.rs +++ b/e2e/tests/24_forgotten_passphrase.rs @@ -22,14 +22,11 @@ fn forgotten_passphrase() { assert!(!app.has("vault-passphrase")); }); - step( - "it goes back to the field without touching anything", - || { - app.click("vault-keep-trying"); - app.wait_for("vault-passphrase"); - assert!(!app.has("vault-archive")); - }, - ); + step("it goes back to the field without touching anything", || { + app.click("vault-keep-trying"); + app.wait_for("vault-passphrase"); + assert!(!app.has("vault-archive")); + }); step("it archives and comes back asking for a new phrase", || { app.click("vault-forgotten"); diff --git a/e2e/tests/25_libraries.rs b/e2e/tests/25_libraries.rs index 2418f6030..04b509b92 100644 --- a/e2e/tests/25_libraries.rs +++ b/e2e/tests/25_libraries.rs @@ -80,16 +80,13 @@ fn libraries() { pass_the_gate(&mut app); }); - step( - "it is a library of its own, seeded as a first launch", - || { - app.eventually("its samples are drawn", |tree| tree.has("note-card")); - assert!(!has_space(&app.tree(), HOME)); - panel(&mut app); - assert_eq!(app.tree().count("library-row"), 2); - close_panel(&mut app); - }, - ); + step("it is a library of its own, seeded as a first launch", || { + app.eventually("its samples are drawn", |tree| tree.has("note-card")); + assert!(!has_space(&app.tree(), HOME)); + panel(&mut app); + assert_eq!(app.tree().count("library-row"), 2); + close_panel(&mut app); + }); step("a switch asks before it loses an unsaved request", || { leave_a_request_unsaved(&mut app); @@ -98,9 +95,7 @@ fn libraries() { app.wait_for("http-leave-dialog"); assert_eq!(app.tree().count("http-leave-name"), 1); app.click("http-leave-cancel"); - app.eventually("the question is gone", |tree| { - !tree.has("http-leave-dialog") - }); + app.eventually("the question is gone", |tree| !tree.has("http-leave-dialog")); assert!(!app.has("vault-passphrase"), "nothing changed"); app.click("library-switch"); @@ -109,21 +104,16 @@ fn libraries() { assert!(!app.has("vault-confirmation"), "this one has its phrase"); }); - step( - "the gate goes from one library to the other, and back", - || { - app.click("vault-library-switch"); - app.click("vault-library-switch-1"); - app.eventually("the gate asks for the other", |tree| { - gate_library(tree) == OTHER - }); - app.click("vault-library-switch"); - app.click("vault-library-switch-0"); - app.eventually("the gate asks for the first", |tree| { - tree.has("vault-library-switch") && gate_library(tree) != OTHER - }); - }, - ); + step("the gate goes from one library to the other, and back", || { + app.click("vault-library-switch"); + app.click("vault-library-switch-1"); + app.eventually("the gate asks for the other", |tree| gate_library(tree) == OTHER); + app.click("vault-library-switch"); + app.click("vault-library-switch-0"); + app.eventually("the gate asks for the first", |tree| { + tree.has("vault-library-switch") && gate_library(tree) != OTHER + }); + }); step("what was left there is found", || { pass_the_gate(&mut app); @@ -138,9 +128,7 @@ fn libraries() { assert!(said.contains(OTHER), "{said}"); assert_eq!(app.tree().count("library-row"), 2); app.click("library-confirm-delete"); - app.eventually("the library is erased", |tree| { - tree.count("library-row") == 1 - }); + app.eventually("the library is erased", |tree| tree.count("library-row") == 1); }); step("the one that is left offers no deletion", || { @@ -156,10 +144,7 @@ fn libraries() { step("a registry cut short still opens on the library", || { app.wait_for("vault-passphrase"); - assert!( - !app.has("vault-confirmation"), - "not taken for a first launch" - ); + assert!(!app.has("vault-confirmation"), "not taken for a first launch"); pass_the_gate(&mut app); app.eventually("its own spaces are listed", |tree| has_space(tree, HOME)); }); diff --git a/e2e/tests/26_formatting.rs b/e2e/tests/26_formatting.rs index a615fe5e0..c7d7a62f4 100644 --- a/e2e/tests/26_formatting.rs +++ b/e2e/tests/26_formatting.rs @@ -53,9 +53,7 @@ fn formatting() { step("its notice takes the format back", || { app.click("editor-format-undo"); - app.eventually("the code on one line again", |tree| { - code(tree).lines().count() == 1 - }); + app.eventually("the code on one line again", |tree| code(tree).lines().count() == 1); }); step("Shift+Alt+F formats from the title, and it is kept", || { @@ -85,29 +83,25 @@ fn formatting() { }); }); - step( - "format on save is named beside its switch, and turns", - || { - let on = |tree: &Tree| { - tree.find("prettier-formatOnSave") - .and_then(egui::accesskit::Node::toggled) - == Some(egui::accesskit::Toggled::True) - }; - app.click("editor-format-settings"); - app.wait_for("prettier-formatOnSave"); - let tree = app.tree(); - assert!(!on(&tree)); - let label = tree.text("prettier-formatOnSave").unwrap_or_default(); - assert!(!label.is_empty() && tree.mentions(&label)); - app.capture("format-settings"); - app.click("prettier-formatOnSave"); - app.eventually("on", on); - app.click("prettier-formatOnSave"); - app.eventually("off again", |tree| !on(tree)); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("closed", |tree| !tree.has("prettier-formatOnSave")); - }, - ); + step("format on save is named beside its switch, and turns", || { + let on = |tree: &Tree| { + tree.find("prettier-formatOnSave").and_then(egui::accesskit::Node::toggled) + == Some(egui::accesskit::Toggled::True) + }; + app.click("editor-format-settings"); + app.wait_for("prettier-formatOnSave"); + let tree = app.tree(); + assert!(!on(&tree)); + let label = tree.text("prettier-formatOnSave").unwrap_or_default(); + assert!(!label.is_empty() && tree.mentions(&label)); + app.capture("format-settings"); + app.click("prettier-formatOnSave"); + app.eventually("on", on); + app.click("prettier-formatOnSave"); + app.eventually("off again", |tree| !on(tree)); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("closed", |tree| !tree.has("prettier-formatOnSave")); + }); step("a syntax error is said, and nothing changes", || { app.click("editor-body"); @@ -115,25 +109,16 @@ fn formatting() { app.type_text(")"); let typed = code(&app.tree()); app.click("editor-format"); - app.eventually("the error said", |tree| { - notice(tree).as_deref() == Some("syntax") - }); + app.eventually("the error said", |tree| notice(tree).as_deref() == Some("syntax")); assert_eq!(code(&app.tree()), typed); close(&mut app); }); - step( - "a language Prettier does not read leaves the button disabled", - || { - open(&mut app, "5432"); - assert!( - app.tree() - .find("editor-format") - .is_some_and(egui::accesskit::Node::is_disabled) - ); - close(&mut app); - }, - ); + step("a language Prettier does not read leaves the button disabled", || { + open(&mut app, "5432"); + assert!(app.tree().find("editor-format").is_some_and(egui::accesskit::Node::is_disabled)); + close(&mut app); + }); app.quit(); } diff --git a/e2e/tests/27_json_explorer.rs b/e2e/tests/27_json_explorer.rs index d3259bc01..0c1caacd2 100644 --- a/e2e/tests/27_json_explorer.rs +++ b/e2e/tests/27_json_explorer.rs @@ -20,8 +20,7 @@ fn at(path: &'static str) -> impl Fn(&egui::accesskit::Node) -> bool { } fn invalid(tree: &Tree) -> bool { - tree.find("editor-json-validity") - .is_some_and(|node| node.invalid().is_some()) + tree.find("editor-json-validity").is_some_and(|node| node.invalid().is_some()) } #[test] @@ -33,9 +32,7 @@ fn json_explorer() { // The notes header stays above an expanded note: the graph is given its height back. app.resize(1_100, 900); app.fill("search-input", "p95Ms"); - app.eventually("the JSON sample, alone", |tree| { - tree.count("note-card") == 1 - }); + app.eventually("the JSON sample, alone", |tree| tree.count("note-card") == 1); step("the band says the draft parses, over its code", || { app.click("note-card-open"); @@ -68,33 +65,24 @@ fn json_explorer() { app.eventually("the first row", |tree| selected(tree) == "$.service"); }); - step( - "everything folds and opens, the selection falling back and coming back", - || { - app.click("json-open-all"); - app.eventually("every node", |tree| nodes(tree) == 6); - app.click_where("json-row", at("$.owner.team")); - app.click("json-collapse-all"); - app.eventually("the root alone", |tree| nodes(tree) == 1); - app.eventually("the row still drawn", |tree| selected(tree) == "$.owner"); - app.click("json-open-all"); - app.eventually("back where it was", |tree| selected(tree) == "$.owner.team"); - }, - ); + step("everything folds and opens, the selection falling back and coming back", || { + app.click("json-open-all"); + app.eventually("every node", |tree| nodes(tree) == 6); + app.click_where("json-row", at("$.owner.team")); + app.click("json-collapse-all"); + app.eventually("the root alone", |tree| nodes(tree) == 1); + app.eventually("the row still drawn", |tree| selected(tree) == "$.owner"); + app.click("json-open-all"); + app.eventually("back where it was", |tree| selected(tree) == "$.owner.team"); + }); step("a match is stepped to and shown in the code", || { app.fill("json-search", "ONCALL"); - app.eventually("one match", |tree| { - tree.text("json-match-count").as_deref() == Some("1") - }); + app.eventually("one match", |tree| tree.text("json-match-count").as_deref() == Some("1")); app.click("json-match-next"); - app.eventually("the match selected", |tree| { - selected(tree) == "$.owner.onCall" - }); + app.eventually("the match selected", |tree| selected(tree) == "$.owner.onCall"); app.click("json-show-in-code"); - app.eventually("back to the code", |tree| { - tree.has("editor-body") && !tree.has("json-node-head") - }); + app.eventually("back to the code", |tree| tree.has("editor-body") && !tree.has("json-node-head")); }); step("the tree folds a container", || { @@ -115,38 +103,33 @@ fn json_explorer() { /// The code and the graph side by side, selecting in each other; the code hidden; too narrow. fn side_by_side(app: &mut App) { - step( - "side by side the code and the graph select in each other", - || { - app.click("editor-view-graph"); - app.click("editor-side-by-side"); - app.eventually("the graph beside the code", |tree| { - tree.has("side-by-side") && tree.has("side-by-side-code") - }); - app.click("editor-body"); - app.press(Key::Home, Modifiers::COMMAND); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::End, Modifiers::NONE); - app.press(Key::ArrowLeft, Modifiers::NONE); - app.press(Key::ArrowLeft, Modifiers::NONE); - app.eventually("the value under the caret", |tree| { - selected(tree) == "$.service" - }); - app.capture("side-by-side"); - - app.click("editor-hide-code"); - app.eventually("the graph alone", |tree| !tree.has("side-by-side")); - app.click("editor-hide-code"); - app.wait_for("side-by-side"); - app.resize(720, 700); - app.wait_for("editor-side-by-side-narrow"); - assert!(!app.has("side-by-side"), "too narrow, it is not squeezed"); - app.resize(1_100, 900); - app.wait_for("side-by-side"); - app.click("editor-side-by-side"); - app.eventually("one at a time again", |tree| !tree.has("side-by-side")); - }, - ); + step("side by side the code and the graph select in each other", || { + app.click("editor-view-graph"); + app.click("editor-side-by-side"); + app.eventually("the graph beside the code", |tree| { + tree.has("side-by-side") && tree.has("side-by-side-code") + }); + app.click("editor-body"); + app.press(Key::Home, Modifiers::COMMAND); + app.press(Key::ArrowDown, Modifiers::NONE); + app.press(Key::End, Modifiers::NONE); + app.press(Key::ArrowLeft, Modifiers::NONE); + app.press(Key::ArrowLeft, Modifiers::NONE); + app.eventually("the value under the caret", |tree| selected(tree) == "$.service"); + app.capture("side-by-side"); + + app.click("editor-hide-code"); + app.eventually("the graph alone", |tree| !tree.has("side-by-side")); + app.click("editor-hide-code"); + app.wait_for("side-by-side"); + app.resize(720, 700); + app.wait_for("editor-side-by-side-narrow"); + assert!(!app.has("side-by-side"), "too narrow, it is not squeezed"); + app.resize(1_100, 900); + app.wait_for("side-by-side"); + app.click("editor-side-by-side"); + app.eventually("one at a time again", |tree| !tree.has("side-by-side")); + }); } fn broken_draft(app: &mut App) { diff --git a/e2e/tests/28_areas.rs b/e2e/tests/28_areas.rs index 43d7e745d..c7940ca81 100644 --- a/e2e/tests/28_areas.rs +++ b/e2e/tests/28_areas.rs @@ -33,36 +33,25 @@ fn reach(app: &mut App, author_id: &str) { fn value_of(app: &mut App, author_id: &str) -> String { let tree = app.tree(); let node = tree.find(author_id); - node.and_then(egui::accesskit::Node::value) - .unwrap_or_default() - .to_owned() + node.and_then(egui::accesskit::Node::value).unwrap_or_default().to_owned() } fn palette_key_shows(app: &mut App, said: &str) { app.eventually(&format!("the palette's field shows {said}"), |tree| { - tree.find("shortcut-field-palette") - .and_then(egui::accesskit::Node::value) - == Some(said) + tree.find("shortcut-field-palette").and_then(egui::accesskit::Node::value) == Some(said) }); } /// AZERTY's Q, where QWERTY's A stands: macOS hears the place, the others the letter. fn another_layout(app: &mut App) { - step( - "a key of another layout is kept as the system will hear it", - || { - app.click("shortcut-field-palette"); - app.press_laid_out(Key::Q, Key::A, Modifiers::COMMAND | Modifiers::ALT); - let heard = if cfg!(target_os = "macos") { - "Ctrl+Alt+A" - } else { - "Ctrl+Alt+Q" - }; - palette_key_shows(app, heard); - app.click("shortcut-reset-palette"); - palette_key_shows(app, "Ctrl+Alt+P"); - }, - ); + step("a key of another layout is kept as the system will hear it", || { + app.click("shortcut-field-palette"); + app.press_laid_out(Key::Q, Key::A, Modifiers::COMMAND | Modifiers::ALT); + let heard = if cfg!(target_os = "macos") { "Ctrl+Alt+A" } else { "Ctrl+Alt+Q" }; + palette_key_shows(app, heard); + app.click("shortcut-reset-palette"); + palette_key_shows(app, "Ctrl+Alt+P"); + }); } /// The sidebar toggle's box in the area shown, once it holds still. @@ -79,30 +68,19 @@ fn toggle_box(app: &mut App, author_id: &str) -> (f64, f64, f64, f64) { /// The toggle stands at one place in the three areas. fn one_toggle_place(app: &mut App) { let same = |a: (f64, f64, f64, f64), b: (f64, f64, f64, f64)| { - [a.0 - b.0, a.1 - b.1, a.2 - b.2, a.3 - b.3] - .iter() - .all(|gap| gap.abs() < 0.5) + [a.0 - b.0, a.1 - b.1, a.2 - b.2, a.3 - b.3].iter().all(|gap| gap.abs() < 0.5) }; - step( - "the sidebar toggle stands at one place in every area", - || { - let notes = toggle_box(app, "library-rail-toggle"); - app.click("area-option-tools"); - let tools = toggle_box(app, "tools-rail-toggle"); - assert!( - same(tools, notes), - "{tools:?} in the tools, {notes:?} in the notes" - ); - app.click("area-option-http"); - let http = toggle_box(app, "http-rail-toggle"); - assert!( - same(http, notes), - "{http:?} in HTTP, {notes:?} in the notes" - ); - app.click("area-option-notes"); - app.wait_for("area-notes"); - }, - ); + step("the sidebar toggle stands at one place in every area", || { + let notes = toggle_box(app, "library-rail-toggle"); + app.click("area-option-tools"); + let tools = toggle_box(app, "tools-rail-toggle"); + assert!(same(tools, notes), "{tools:?} in the tools, {notes:?} in the notes"); + app.click("area-option-http"); + let http = toggle_box(app, "http-rail-toggle"); + assert!(same(http, notes), "{http:?} in HTTP, {notes:?} in the notes"); + app.click("area-option-notes"); + app.wait_for("area-notes"); + }); } #[test] @@ -122,19 +100,16 @@ fn areas() { one_toggle_place(&mut app); - step( - "the keys go there too, and the notes keep their search", - || { - app.click("search-input"); - app.type_text("zzz-nothing-matches"); - app.eventually("nothing matches", |tree| !tree.has("note-card")); - tools(&mut app); - notes(&mut app); - app.eventually("the search is as it was", |tree| !tree.has("note-card")); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the search is off", |tree| tree.has("note-card")); - }, - ); + step("the keys go there too, and the notes keep their search", || { + app.click("search-input"); + app.type_text("zzz-nothing-matches"); + app.eventually("nothing matches", |tree| !tree.has("note-card")); + tools(&mut app); + notes(&mut app); + app.eventually("the search is as it was", |tree| !tree.has("note-card")); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the search is off", |tree| tree.has("note-card")); + }); step("what the native side asks comes back to the notes", || { tools(&mut app); @@ -180,23 +155,18 @@ fn areas() { assert!(app.has("settings-dialog")); }); - step( - "a canvas key takes a bare letter, and the canvas answers", - || { - reach(&mut app, "shortcut-field-canvas.check"); - app.click("shortcut-field-canvas.check"); - app.press(Key::J, Modifiers::NONE); - app.eventually("the field shows it", |tree| { - tree.find("shortcut-field-canvas.check") - .and_then(egui::accesskit::Node::value) - == Some("J") - }); - close_preferences(&mut app); - app.press(Key::ArrowDown, Modifiers::NONE); - app.press(Key::J, Modifiers::NONE); - app.wait_for("selection-count"); - }, - ); + step("a canvas key takes a bare letter, and the canvas answers", || { + reach(&mut app, "shortcut-field-canvas.check"); + app.click("shortcut-field-canvas.check"); + app.press(Key::J, Modifiers::NONE); + app.eventually("the field shows it", |tree| { + tree.find("shortcut-field-canvas.check").and_then(egui::accesskit::Node::value) == Some("J") + }); + close_preferences(&mut app); + app.press(Key::ArrowDown, Modifiers::NONE); + app.press(Key::J, Modifiers::NONE); + app.wait_for("selection-count"); + }); tools(&mut app); let mut app = app.relaunch(); diff --git a/e2e/tests/29_tools.rs b/e2e/tests/29_tools.rs index 8502a2457..b7e27d96c 100644 --- a/e2e/tests/29_tools.rs +++ b/e2e/tests/29_tools.rs @@ -18,9 +18,7 @@ fn home(app: &mut App) { step("a keyword narrows the catalogue", || { app.fill("tools-search", "crlf"); app.wait_for("tools-entry-line-breaks"); - app.eventually("the others are gone", |tree| { - tree.find("tools-entry-hash").is_none() - }); + app.eventually("the others are gone", |tree| tree.find("tools-entry-hash").is_none()); app.press(Key::Escape, Modifiers::NONE); app.wait_for("tools-entry-hash"); }); @@ -52,9 +50,7 @@ fn text_tools(app: &mut App) { app.wait_for("tool-title"); app.fill("case-input", "parse URL"); app.eventually("the cases are shown", |tree| { - tree.texts("output-value") - .iter() - .any(|it| it == "parse_url") + tree.texts("output-value").iter().any(|it| it == "parse_url") }); }); step("the diff compares two texts", || { @@ -70,9 +66,7 @@ fn text_tools(app: &mut App) { /// By the search: the catalogue is longer than the window. fn open_tool(app: &mut App, tool: &str) { app.fill("tools-search", tool); - app.eventually("the catalogue is narrowed", |tree| { - !tree.has("tools-entry-hash") - }); + app.eventually("the catalogue is narrowed", |tree| !tree.has("tools-entry-hash")); app.click(&format!("tools-entry-{tool}")); app.wait_for("tool-title"); } @@ -86,41 +80,30 @@ fn back_to_the_home(app: &mut App) { } fn data_tools(app: &mut App) { - step( - "a document is converted, and the swap brings it back", - || { - open_tool(app, "convert"); - app.fill("convert-input", r#"{"service":"billing"}"#); - app.eventually("the YAML is shown", |tree| { - tree.text("convert-output") - .is_some_and(|it| it.contains("service: billing")) - }); - app.click("convert-swap"); - app.eventually("the JSON is back", |tree| { - tree.text("convert-output") - .is_some_and(|it| it.contains('{')) - }); - back_to_the_home(app); - }, - ); + step("a document is converted, and the swap brings it back", || { + open_tool(app, "convert"); + app.fill("convert-input", r#"{"service":"billing"}"#); + app.eventually("the YAML is shown", |tree| { + tree.text("convert-output").is_some_and(|it| it.contains("service: billing")) + }); + app.click("convert-swap"); + app.eventually("the JSON is back", |tree| { + tree.text("convert-output").is_some_and(|it| it.contains('{')) + }); + back_to_the_home(app); + }); step("a seed brings the same person back", || { open_tool(app, "identity"); app.wait_for("identity-card"); let drawn = app.tree().text("identity-surname"); app.fill("identity-seed", "devnotes"); app.wait_for("identity-seed-pinned"); - app.eventually("the seed's person is on the card", |tree| { - tree.text("identity-surname") != drawn - }); + app.eventually("the seed's person is on the card", |tree| tree.text("identity-surname") != drawn); let surname = app.tree().text("identity-surname"); retype(app, "identity-seed", "another"); - app.eventually("another person is drawn", |tree| { - tree.text("identity-surname") != surname - }); + app.eventually("another person is drawn", |tree| tree.text("identity-surname") != surname); retype(app, "identity-seed", "devnotes"); - app.eventually("the first person is back", |tree| { - tree.text("identity-surname") == surname - }); + app.eventually("the first person is back", |tree| tree.text("identity-surname") == surname); back_to_the_home(app); }); step("a code is drawn from a URL", || { @@ -167,10 +150,7 @@ fn remembered(mut app: App) -> App { app.wait_for("tools-favourite-cron"); app.wait_for("tools-recent-case"); let tree = app.tree(); - assert!( - tree.text("tools-count") - .is_some_and(|words| words.contains("32")) - ); + assert!(tree.text("tools-count").is_some_and(|words| words.contains("32"))); }); app } diff --git a/e2e/tests/30_http.rs b/e2e/tests/30_http.rs index 46333700d..57ec05072 100644 --- a/e2e/tests/30_http.rs +++ b/e2e/tests/30_http.rs @@ -48,49 +48,35 @@ fn organise(app: &mut App) { create(app, API); app.eventually("the collection is listed", |tree| rows(tree) == [API]); }); - step( - "a folder and two requests made from the rows' menus", - || { - choose(app, API, &["http-node-new-folder"]); - create(app, "Auth"); - app.eventually("the folder is listed", |tree| rows(tree) == [API, "Auth"]); - choose(app, "Auth", &["http-node-new", "http-node-new-http"]); - create(app, "Login"); - app.eventually("the request is listed", |tree| { - rows(tree) == [API, "Auth", "GET Login"] - }); - choose(app, "Auth", &["http-node-new", "http-node-new-websocket"]); - create(app, "Flux"); - app.eventually("the socket is listed", |tree| { - rows(tree) == [API, "Auth", "GET Login", "WS Flux"] - }); - }, - ); - step( - "a request moved with the keys, then out of its folder", - || { - app.click_where("http-node-name", named("WS Flux")); - app.press(Key::ArrowUp, Modifiers::ALT); - app.eventually("the socket is first", |tree| { - rows(tree) == [API, "Auth", "WS Flux", "GET Login"] - }); - app.eventually("the move is said", |tree| { - tree.text("http-rail-moved") - .is_some_and(|said| said.contains("Login")) - }); - app.press(Key::ArrowLeft, Modifiers::ALT); - app.eventually("the socket is at the collection's root", |tree| { - rows(tree) == [API, "Auth", "GET Login", "WS Flux"] - }); - // Nothing is above a folder's first request but its folder: refused, and said. - app.click_where("http-node-name", named("GET Login")); - app.press(Key::ArrowRight, Modifiers::ALT); - app.eventually("the refusal is said", |tree| { - tree.text("http-rail-moved") - .is_some_and(|said| said.contains("Login")) - }); - }, - ); + step("a folder and two requests made from the rows' menus", || { + choose(app, API, &["http-node-new-folder"]); + create(app, "Auth"); + app.eventually("the folder is listed", |tree| rows(tree) == [API, "Auth"]); + choose(app, "Auth", &["http-node-new", "http-node-new-http"]); + create(app, "Login"); + app.eventually("the request is listed", |tree| rows(tree) == [API, "Auth", "GET Login"]); + choose(app, "Auth", &["http-node-new", "http-node-new-websocket"]); + create(app, "Flux"); + app.eventually("the socket is listed", |tree| rows(tree) == [API, "Auth", "GET Login", "WS Flux"]); + }); + step("a request moved with the keys, then out of its folder", || { + app.click_where("http-node-name", named("WS Flux")); + app.press(Key::ArrowUp, Modifiers::ALT); + app.eventually("the socket is first", |tree| rows(tree) == [API, "Auth", "WS Flux", "GET Login"]); + app.eventually("the move is said", |tree| { + tree.text("http-rail-moved").is_some_and(|said| said.contains("Login")) + }); + app.press(Key::ArrowLeft, Modifiers::ALT); + app.eventually("the socket is at the collection's root", |tree| { + rows(tree) == [API, "Auth", "GET Login", "WS Flux"] + }); + // Nothing is above a folder's first request but its folder: refused, and said. + app.click_where("http-node-name", named("GET Login")); + app.press(Key::ArrowRight, Modifiers::ALT); + app.eventually("the refusal is said", |tree| { + tree.text("http-rail-moved").is_some_and(|said| said.contains("Login")) + }); + }); step("a request renamed in place, the field left", || { app.click_where("http-node-name", named("WS Flux")); app.press(Key::F2, Modifiers::NONE); @@ -116,23 +102,20 @@ fn open(tree: &Tree) -> Vec { } fn in_tabs(app: &mut App) { - step( - "a request opens in its tab, and a draft asks before it closes", - || { - app.click_where("http-node-name", named("GET Login")); - app.eventually("the requests clicked have their tabs", |tree| { - open(tree) == ["GET Login", "WS Flux live"] - }); - app.click("http-tab-new"); - app.eventually("a draft opens beside them", |tree| tabs(tree).len() == 3); - app.click_nth("http-tab-close", 2); - app.wait_for("http-close-dialog"); - app.click("http-close-discard"); - app.eventually("the draft is gone", |tree| { - open(tree) == ["GET Login", "WS Flux live"] && !tree.has("http-close-dialog") - }); - }, - ); + step("a request opens in its tab, and a draft asks before it closes", || { + app.click_where("http-node-name", named("GET Login")); + app.eventually("the requests clicked have their tabs", |tree| { + open(tree) == ["GET Login", "WS Flux live"] + }); + app.click("http-tab-new"); + app.eventually("a draft opens beside them", |tree| tabs(tree).len() == 3); + app.click_nth("http-tab-close", 2); + app.wait_for("http-close-dialog"); + app.click("http-close-discard"); + app.eventually("the draft is gone", |tree| { + open(tree) == ["GET Login", "WS Flux live"] && !tree.has("http-close-dialog") + }); + }); } /// The first tab dragged past the second, kept so after the relaunch; the middle button closes a @@ -143,11 +126,7 @@ fn tabs_moved(app: &mut App) -> Vec { step("a tab dragged past the other takes its place", || { let tree = app.tree(); let before = tabs(&tree); - let bounds: Vec<_> = tree - .all("http-tab-open") - .into_iter() - .filter_map(Node::bounds) - .collect(); + let bounds: Vec<_> = tree.all("http-tab-open").into_iter().filter_map(Node::bounds).collect(); let [first, second, ..] = bounds[..] else { panic!("two tabs at least: {before:?}"); }; @@ -163,16 +142,12 @@ fn tabs_moved(app: &mut App) -> Vec { }); step("the middle button on a draft asks, then closes it", || { app.click("http-tab-new"); - app.eventually("a draft opens beside them", |tree| { - tabs(tree).len() == order.len() + 1 - }); + app.eventually("a draft opens beside them", |tree| tabs(tree).len() == order.len() + 1); let draft = app.tree().texts("http-tab-open")[order.len()].clone(); app.click_with("http-tab-open", PointerButton::Middle, named(&draft)); app.wait_for("http-close-dialog"); app.click("http-close-discard"); - app.eventually("the draft is gone", |tree| { - tabs(tree) == order && !tree.has("http-close-dialog") - }); + app.eventually("the draft is gone", |tree| tabs(tree) == order && !tree.has("http-close-dialog")); }); order .iter() @@ -196,64 +171,49 @@ fn append(app: &mut App, author_id: &str, words: &str) { } fn compose(app: &mut App) { - step( - "the query and its table kept in step, a header split, Ctrl+S", - || { - app.click_where("http-tab-open", named("GET Login")); - app.wait_for("http-url"); - append(app, "http-url", "?page=2&q=x"); - app.eventually("the table follows the URL", |tree| { - values(tree, "http-kv-key") == ["page", "q", ""] - }); - app.click_nth("http-kv-enabled", 0); - app.eventually("the URL follows the table", |tree| { - tree.find("http-url") - .and_then(Node::value) - .is_some_and(|url| url == "?q=x") - }); - app.click("http-section-headers"); - app.wait_for("http-implied-headers"); - app.click_nth("http-kv-key", 0); - app.type_text("Accept: application/json"); - app.eventually("the header is split into its two cells", |tree| { - values(tree, "http-kv-key").first().map(String::as_str) == Some("Accept") - && values(tree, "http-kv-value").first().map(String::as_str) - == Some("application/json") - }); - app.press(Key::S, Modifiers::COMMAND); - app.eventually("the tab is saved", |tree| { - tabs(tree).contains(&"GET Login".to_owned()) - }); - }, - ); + step("the query and its table kept in step, a header split, Ctrl+S", || { + app.click_where("http-tab-open", named("GET Login")); + app.wait_for("http-url"); + append(app, "http-url", "?page=2&q=x"); + app.eventually("the table follows the URL", |tree| values(tree, "http-kv-key") == ["page", "q", ""]); + app.click_nth("http-kv-enabled", 0); + app.eventually("the URL follows the table", |tree| { + tree.find("http-url").and_then(Node::value).is_some_and(|url| url == "?q=x") + }); + app.click("http-section-headers"); + app.wait_for("http-implied-headers"); + app.click_nth("http-kv-key", 0); + app.type_text("Accept: application/json"); + app.eventually("the header is split into its two cells", |tree| { + values(tree, "http-kv-key").first().map(String::as_str) == Some("Accept") + && values(tree, "http-kv-value").first().map(String::as_str) == Some("application/json") + }); + app.press(Key::S, Modifiers::COMMAND); + app.eventually("the tab is saved", |tree| tabs(tree).contains(&"GET Login".to_owned())); + }); } fn send(app: &mut App) { - step( - "sent from Rust on Ctrl+Enter: its status, time, size and body, then cleared", - || { - let port = e2e::serve(); - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(&format!("http://127.0.0.1:{port}/json")); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the answer is shown", |tree| { - tree.text("http-response-status").as_deref() == Some("200 OK") - && tree.has("http-response-time") - && tree.has("http-response-size") - && tree - .text("http-response-pretty") - .is_some_and(|body| body.contains("Ada")) - }); - app.click("http-response-section-timeline"); - app.eventually("the exchange is shown", |tree| { - tree.text("http-response-sent") - .is_some_and(|sent| sent.starts_with("GET http://127.0.0.1")) - }); - app.click("http-response-clear"); - app.wait_for("http-response-idle"); - }, - ); + step("sent from Rust on Ctrl+Enter: its status, time, size and body, then cleared", || { + let port = e2e::serve(); + app.click("http-url"); + app.press(Key::A, Modifiers::COMMAND); + app.type_text(&format!("http://127.0.0.1:{port}/json")); + app.press(Key::Enter, Modifiers::COMMAND); + app.eventually("the answer is shown", |tree| { + tree.text("http-response-status").as_deref() == Some("200 OK") + && tree.has("http-response-time") + && tree.has("http-response-size") + && tree.text("http-response-pretty").is_some_and(|body| body.contains("Ada")) + }); + app.click("http-response-section-timeline"); + app.eventually("the exchange is shown", |tree| { + tree.text("http-response-sent") + .is_some_and(|sent| sent.starts_with("GET http://127.0.0.1")) + }); + app.click("http-response-clear"); + app.wait_for("http-response-idle"); + }); step("the send in the history, read again, then reopened", || { app.click("http-history-open"); app.wait_for("http-history-item"); @@ -268,49 +228,38 @@ fn send(app: &mut App) { app.wait_for("http-url"); app.eventually("the page has gone", |tree| !tree.has("http-history")); }); - step( - "the cookie the answer set, in the jar, then thrown away", - || { - app.click("http-cookies-open"); - app.eventually("the cookie is listed", |tree| { - tree.text("http-cookie").as_deref() == Some("session") - }); - app.click("http-cookie-remove"); - app.wait_for("http-cookies-empty"); - app.click("http-cookies-close"); - app.eventually("the jar is closed", |tree| !tree.has("http-cookies-dialog")); - }, - ); + step("the cookie the answer set, in the jar, then thrown away", || { + app.click("http-cookies-open"); + app.eventually("the cookie is listed", |tree| tree.text("http-cookie").as_deref() == Some("session")); + app.click("http-cookie-remove"); + app.wait_for("http-cookies-empty"); + app.click("http-cookies-close"); + app.eventually("the jar is closed", |tree| !tree.has("http-cookies-dialog")); + }); } fn bodies(app: &mut App) { - step( - "a JSON body read as it is typed, said on a GET, taken back to none", - || { - app.click("http-section-body"); - app.click("http-body-kind-1"); - app.fill("http-body-text", "{\"amount\":4900}"); - app.eventually("the body reads and its type is said", |tree| { - tree.has("http-body-valid") - && tree - .text("http-body-type") - .is_some_and(|said| said.contains("application/json")) - }); - app.wait_for("http-body-unusual"); - app.wait_for("http-body-unusual-mark"); - app.click("http-body-to-none"); - app.eventually("no body, no warning", |tree| { - !tree.has("http-body-unusual") && !tree.has("http-body-text") - }); - }, - ); + step("a JSON body read as it is typed, said on a GET, taken back to none", || { + app.click("http-section-body"); + app.click("http-body-kind-1"); + app.fill("http-body-text", "{\"amount\":4900}"); + app.eventually("the body reads and its type is said", |tree| { + tree.has("http-body-valid") + && tree + .text("http-body-type") + .is_some_and(|said| said.contains("application/json")) + }); + app.wait_for("http-body-unusual"); + app.wait_for("http-body-unusual-mark"); + app.click("http-body-to-none"); + app.eventually("no body, no warning", |tree| { + !tree.has("http-body-unusual") && !tree.has("http-body-text") + }); + }); step("a GraphQL draft: its variable named, then added", || { app.click("http-tab-new-kind"); app.click("http-new-kind-graphql"); - app.fill( - "http-graphql-query", - "query One($code: ID!) { product(code: $code) { id } }", - ); + app.fill("http-graphql-query", "query One($code: ID!) { product(code: $code) { id } }"); app.wait_for("http-graphql-missing"); app.click("http-graphql-add"); app.eventually("the variable has its null", |tree| { @@ -327,47 +276,33 @@ fn bodies(app: &mut App) { } fn socket(app: &mut App) { - step( - "a socket connected, a message echoed, then disconnected", - || { - let port = e2e::serve_socket(); - app.click_where("http-tab-open", named("WS Flux live")); - app.wait_for("http-socket-message"); - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(&format!("ws://127.0.0.1:{port}/")); - app.click("http-socket-connect"); - app.eventually("the socket is open", |tree| { - tree.count("http-socket-entry") == 1 - }); - app.fill("http-socket-message", "ping"); - // A key overtakes what is still being typed: it would reach the area, not the message. - app.eventually("the message is typed", |tree| { - values(tree, "http-socket-message") - .first() - .map(String::as_str) - == Some("ping") - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the message came back", |tree| { - tree.count("http-socket-entry") == 3 - }); - app.click("http-socket-connect"); - app.eventually("the socket is closed", |tree| { - tree.count("http-socket-entry") == 4 - }); - app.press(Key::S, Modifiers::COMMAND); - }, - ); + step("a socket connected, a message echoed, then disconnected", || { + let port = e2e::serve_socket(); + app.click_where("http-tab-open", named("WS Flux live")); + app.wait_for("http-socket-message"); + app.click("http-url"); + app.press(Key::A, Modifiers::COMMAND); + app.type_text(&format!("ws://127.0.0.1:{port}/")); + app.click("http-socket-connect"); + app.eventually("the socket is open", |tree| tree.count("http-socket-entry") == 1); + app.fill("http-socket-message", "ping"); + // A key overtakes what is still being typed: it would reach the area, not the message. + app.eventually("the message is typed", |tree| { + values(tree, "http-socket-message").first().map(String::as_str) == Some("ping") + }); + app.press(Key::Enter, Modifiers::COMMAND); + app.eventually("the message came back", |tree| tree.count("http-socket-entry") == 3); + app.click("http-socket-connect"); + app.eventually("the socket is closed", |tree| tree.count("http-socket-entry") == 4); + app.press(Key::S, Modifiers::COMMAND); + }); } fn fold_kept(app: App, order: &[String]) -> App { let mut app = app; step("a folder folded, still folded after a relaunch", || { app.click_where("http-node-twisty", ends("Auth")); - app.eventually("the folder is folded", |tree| { - rows(tree) == [API, "Auth", "WS Flux live"] - }); + app.eventually("the folder is folded", |tree| rows(tree) == [API, "Auth", "WS Flux live"]); }); let mut app = app.relaunch_discarding(); step("unlocked again, the HTTP area shows the fold", || { @@ -382,22 +317,17 @@ fn fold_kept(app: App, order: &[String]) -> App { } fn delete(app: &mut App) { - step( - "the collection deleted after saying what goes with it", - || { - choose(app, API, &["http-node-delete"]); - app.wait_for("http-delete-count"); - app.click("http-delete-cancel"); - app.eventually("cancel keeps it", |tree| { - !tree.has("http-delete-confirm") && rows(tree).len() == 3 - }); - choose(app, API, &["http-node-delete"]); - app.click("http-delete-submit"); - app.eventually("the rail is empty again", |tree| { - rows(tree).is_empty() && tree.has("http-rail-empty") && tabs(tree).is_empty() - }); - }, - ); + step("the collection deleted after saying what goes with it", || { + choose(app, API, &["http-node-delete"]); + app.wait_for("http-delete-count"); + app.click("http-delete-cancel"); + app.eventually("cancel keeps it", |tree| !tree.has("http-delete-confirm") && rows(tree).len() == 3); + choose(app, API, &["http-node-delete"]); + app.click("http-delete-submit"); + app.eventually("the rail is empty again", |tree| { + rows(tree).is_empty() && tree.has("http-rail-empty") && tabs(tree).is_empty() + }); + }); } #[test] diff --git a/e2e/tests/31_http_environments.rs b/e2e/tests/31_http_environments.rs index 00cc19540..d79541b3b 100644 --- a/e2e/tests/31_http_environments.rs +++ b/e2e/tests/31_http_environments.rs @@ -28,9 +28,7 @@ fn a_request(app: &mut App) { app.click("http-node-new"); app.click("http-node-new-http"); create(app, "Login"); - app.eventually("the request is listed", |tree| { - tree.texts("http-node-name").len() == 2 - }); + app.eventually("the request is listed", |tree| tree.texts("http-node-name").len() == 2); app.click_where("http-node-name", ends("Login")); app.wait_for("http-url"); }); @@ -39,66 +37,56 @@ fn a_request(app: &mut App) { fn picker(app: &mut App) { step("the picker offers the globals alone", || { app.click("http-environment-picker"); - app.eventually("one entry, none", |tree| { - tree.count("http-environment-option") == 1 - }); + app.eventually("one entry, none", |tree| tree.count("http-environment-option") == 1); app.press(Key::Escape, Modifiers::NONE); app.eventually("it closes", |tree| !tree.has("http-environment-option")); }); } fn own_parts(app: &mut App) { - step( - "an inherited auth said, a token and a timeout set, Ctrl+S", - || { - app.click("http-section-auth"); - app.wait_for("http-auth-inherited"); - app.click("http-auth-kind"); - app.click("http-auth-kind-3"); - app.fill("http-auth-secret", "s3cret"); - app.click("http-section-settings"); - app.fill("http-transport-timeoutMs", "5000"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the field is settled", |tree| { - tree.find("http-transport-timeoutMs") - .and_then(Node::value) - .is_some_and(|value| value == "5000") - }); - app.press(Key::S, Modifiers::COMMAND); - }, - ); + step("an inherited auth said, a token and a timeout set, Ctrl+S", || { + app.click("http-section-auth"); + app.wait_for("http-auth-inherited"); + app.click("http-auth-kind"); + app.click("http-auth-kind-3"); + app.fill("http-auth-secret", "s3cret"); + app.click("http-section-settings"); + app.fill("http-transport-timeoutMs", "5000"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the field is settled", |tree| { + tree.find("http-transport-timeoutMs") + .and_then(Node::value) + .is_some_and(|value| value == "5000") + }); + app.press(Key::S, Modifiers::COMMAND); + }); } fn an_environment(app: &mut App) { - step( - "an environment made, a secret typed, used from the picker", - || { - app.click("http-environment-picker"); - app.click("http-environment-manage"); - app.wait_for("http-environments"); - app.click("http-environment-create-open"); - app.fill("http-environment-create-input", "Production"); - app.click("http-environment-create-submit"); - app.wait_for("http-environment-name"); - app.click_nth("http-variable-name", 0); - app.type_text("apiKey"); - app.click_nth("http-variable-value", 0); - app.type_text("s3cret"); - app.click_nth("http-variable-kind", 0); - app.click("http-variable-kind-2"); - app.eventually("the value is masked", |tree| { - tree.has("http-variable-reveal") - && tree - .find("http-variable-value") - .and_then(Node::value) - .is_some_and(|value| value != "s3cret") - }); - app.click("http-environment-use"); - app.eventually("it is the active one", |tree| { - !tree.has("http-environment-use") - }); - }, - ); + step("an environment made, a secret typed, used from the picker", || { + app.click("http-environment-picker"); + app.click("http-environment-manage"); + app.wait_for("http-environments"); + app.click("http-environment-create-open"); + app.fill("http-environment-create-input", "Production"); + app.click("http-environment-create-submit"); + app.wait_for("http-environment-name"); + app.click_nth("http-variable-name", 0); + app.type_text("apiKey"); + app.click_nth("http-variable-value", 0); + app.type_text("s3cret"); + app.click_nth("http-variable-kind", 0); + app.click("http-variable-kind-2"); + app.eventually("the value is masked", |tree| { + tree.has("http-variable-reveal") + && tree + .find("http-variable-value") + .and_then(Node::value) + .is_some_and(|value| value != "s3cret") + }); + app.click("http-environment-use"); + app.eventually("it is the active one", |tree| !tree.has("http-environment-use")); + }); } fn protected(app: &mut App) { @@ -117,9 +105,7 @@ fn protected(app: &mut App) { app.wait_for("http-protected-confirm"); assert!(!app.has("http-response-status"), "nothing left yet"); app.click("http-protected-cancel"); - app.eventually("the question goes", |tree| { - !tree.has("http-protected-confirm") - }); + app.eventually("the question goes", |tree| !tree.has("http-protected-confirm")); app.click("http-send"); app.click("http-protected-send"); app.wait_for("http-response-status"); @@ -129,23 +115,20 @@ fn protected(app: &mut App) { /// The active environment's secret, named in the URL: its chip's card says where it comes from, /// masks it, and shows it when asked. fn pointed_at(app: &mut App) { - step( - "a variable pointed at says where it is from, and its value", - || { - app.click("http-url"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text("https://example.test/{{apiKey}}"); - app.wait_for("http-used-variable"); - app.hover("http-used-variable"); - app.eventually("the card masks the secret", |tree| { - tree.text("http-used-variable-value").as_deref() == Some("••••••••") - }); - app.click("http-used-variable-reveal"); - app.eventually("and shows it", |tree| { - tree.text("http-used-variable-value").as_deref() == Some("s3cret") - }); - }, - ); + step("a variable pointed at says where it is from, and its value", || { + app.click("http-url"); + app.press(Key::A, Modifiers::COMMAND); + app.type_text("https://example.test/{{apiKey}}"); + app.wait_for("http-used-variable"); + app.hover("http-used-variable"); + app.eventually("the card masks the secret", |tree| { + tree.text("http-used-variable-value").as_deref() == Some("••••••••") + }); + app.click("http-used-variable-reveal"); + app.eventually("and shows it", |tree| { + tree.text("http-used-variable-value").as_deref() == Some("s3cret") + }); + }); } fn read_back(app: App) -> App { diff --git a/e2e/tests/32_http_code.rs b/e2e/tests/32_http_code.rs index 4d244fbaa..17f847880 100644 --- a/e2e/tests/32_http_code.rs +++ b/e2e/tests/32_http_code.rs @@ -45,9 +45,7 @@ fn secret(app: &mut App) { app.click_nth("http-variable-value", 0); app.type_text("invoices"); app.click("http-environment-use"); - app.eventually("it is the active one", |tree| { - !tree.has("http-environment-use") - }); + app.eventually("it is the active one", |tree| !tree.has("http-environment-use")); app.click("http-environments-open"); app.wait_for("http-url"); }); @@ -57,9 +55,7 @@ fn generated(app: &mut App) { step("cURL from the active environment, then as written", || { app.click("http-code-open"); app.wait_for("http-code-dialog"); - app.eventually("the URL is resolved", |tree| { - code(tree).contains("https://api.exemple.fr/invoices") - }); + app.eventually("the URL is resolved", |tree| code(tree).contains("https://api.exemple.fr/invoices")); app.click("http-code-resolve"); app.eventually("the URL is as written", |tree| { code(tree).contains("https://api.exemple.fr/{{path}}") diff --git a/e2e/tests/33_calc.rs b/e2e/tests/33_calc.rs index 3ba3ff065..b5707c9f6 100644 --- a/e2e/tests/33_calc.rs +++ b/e2e/tests/33_calc.rs @@ -40,27 +40,21 @@ fn calc() { app.wait_for("calc-counts"); }); - step( - "each line is computed, and an error stays on its line", - || { - app.click("editor-body"); - app.paste(SHEET); - app.eventually("the results computed", |tree| { - let results = results(tree); - results.contains(&"10551".to_owned()) && results.contains(&"200".to_owned()) - }); - app.eventually("two lines refused, on their lines", |tree| { - tree.count("calc-failure") == 2 - }); - app.capture("sheet"); - }, - ); + step("each line is computed, and an error stays on its line", || { + app.click("editor-body"); + app.paste(SHEET); + app.eventually("the results computed", |tree| { + let results = results(tree); + results.contains(&"10551".to_owned()) && results.contains(&"200".to_owned()) + }); + app.eventually("two lines refused, on their lines", |tree| tree.count("calc-failure") == 2); + app.capture("sheet"); + }); step("a result picked is summed in the footer", || { app.click_nth("calc-result", 0); app.eventually("the sum said", |tree| { - tree.text("calc-summary") - .is_some_and(|said| digits(&said).contains("10052")) + tree.text("calc-summary").is_some_and(|said| digits(&said).contains("10052")) }); app.capture("picked"); }); @@ -71,26 +65,19 @@ fn calc() { app.capture("card"); }); - step( - "a short date before an accent leaves the sheet listed", - || { - app.click("new-note-kind"); - app.click("new-note-calc"); - app.fill("editor-title", "Agenda"); - app.click("editor-body"); - app.paste("RDV le 5/11/24 à 10h\n2 + 2"); - app.eventually("the line computed", |tree| { - results(tree).contains(&"4".to_owned()) - }); - app.click("editor-close"); - app.eventually("the card listed", |tree| { - tree.texts("note-card-title") - .iter() - .any(|title| title == "Agenda") - }); - app.capture("short-date"); - }, - ); + step("a short date before an accent leaves the sheet listed", || { + app.click("new-note-kind"); + app.click("new-note-calc"); + app.fill("editor-title", "Agenda"); + app.click("editor-body"); + app.paste("RDV le 5/11/24 à 10h\n2 + 2"); + app.eventually("the line computed", |tree| results(tree).contains(&"4".to_owned())); + app.click("editor-close"); + app.eventually("the card listed", |tree| { + tree.texts("note-card-title").iter().any(|title| title == "Agenda") + }); + app.capture("short-date"); + }); app.quit(); } diff --git a/e2e/tests/34_http_scripts.rs b/e2e/tests/34_http_scripts.rs index 8f916416a..98c8d9213 100644 --- a/e2e/tests/34_http_scripts.rs +++ b/e2e/tests/34_http_scripts.rs @@ -28,9 +28,7 @@ fn request(app: &mut App) { app.click("http-node-new"); app.click("http-node-new-http"); create(app, "Commander"); - app.eventually("the request is listed", |tree| { - tree.texts("http-node-name").len() == 2 - }); + app.eventually("the request is listed", |tree| tree.texts("http-node-name").len() == 2); app.click_where("http-node-name", ends("Commander")); app.fill("http-url", &format!("http://127.0.0.1:{port}/json")); }); @@ -41,37 +39,27 @@ fn counted(tree: &Tree) -> Vec { } fn kept_value(app: &mut App) { - step( - "a script after the answer keeps a value in the globals", - || { - app.click("http-section-scripts"); - app.wait_for("http-script-code"); - app.click("http-script-phase-1"); - app.fill("http-script-code", "env.set('who', res.json().name);"); - app.eventually("the tab counts it", |tree| { - counted(tree).contains(&"1".to_owned()) - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.wait_for("http-response-status"); - app.click("http-environments-open"); - app.eventually("the value is in the globals", |tree| { - tree.all("http-variable-value") - .iter() - .any(|node| node.value() == Some("Ada")) - }); - app.click("http-environments-open"); - app.wait_for("http-url"); - }, - ); + step("a script after the answer keeps a value in the globals", || { + app.click("http-section-scripts"); + app.wait_for("http-script-code"); + app.click("http-script-phase-1"); + app.fill("http-script-code", "env.set('who', res.json().name);"); + app.eventually("the tab counts it", |tree| counted(tree).contains(&"1".to_owned())); + app.press(Key::Enter, Modifiers::COMMAND); + app.wait_for("http-response-status"); + app.click("http-environments-open"); + app.eventually("the value is in the globals", |tree| { + tree.all("http-variable-value").iter().any(|node| node.value() == Some("Ada")) + }); + app.click("http-environments-open"); + app.wait_for("http-url"); + }); } fn tests_and_console(app: &mut App) { step("the tests of an answer, and what the console heard", || { app.click("http-section-tests"); - app.fill( - "http-script-code", - "test('the status is 200', () => { expect(res.status).toBe(200); });", - ); + app.fill("http-script-code", "test('the status is 200', () => { expect(res.status).toBe(200); });"); app.eventually("the test is typed", |tree| { tree.find("http-script-code") .and_then(Node::value) @@ -131,28 +119,25 @@ fn file_asked(app: &mut App, path: &str) { } fn stopped(app: &mut App) { - step( - "a throw before the send stops it, and leads to its line", - || { - app.click("http-section-scripts"); - app.click("http-script-phase-0"); - app.fill("http-script-code", "\nthrow new Error('refused');"); - // A key overtakes what is still being typed. - app.eventually("the script is typed", |tree| { - tree.find("http-script-code") - .and_then(Node::value) - .is_some_and(|text| text.contains("refused")) - }); - app.press(Key::Enter, Modifiers::COMMAND); - app.eventually("the stop is said", |tree| { - tree.text("http-script-stop-message") - .is_some_and(|said| said.contains("refused")) - }); - app.wait_for("http-script-stop-where"); - app.click("http-script-open"); - app.wait_for("http-script-code"); - }, - ); + step("a throw before the send stops it, and leads to its line", || { + app.click("http-section-scripts"); + app.click("http-script-phase-0"); + app.fill("http-script-code", "\nthrow new Error('refused');"); + // A key overtakes what is still being typed. + app.eventually("the script is typed", |tree| { + tree.find("http-script-code") + .and_then(Node::value) + .is_some_and(|text| text.contains("refused")) + }); + app.press(Key::Enter, Modifiers::COMMAND); + app.eventually("the stop is said", |tree| { + tree.text("http-script-stop-message") + .is_some_and(|said| said.contains("refused")) + }); + app.wait_for("http-script-stop-where"); + app.click("http-script-open"); + app.wait_for("http-script-code"); + }); } #[test] diff --git a/e2e/tests/35_http_runner.rs b/e2e/tests/35_http_runner.rs index 6abb234d8..08eb2a797 100644 --- a/e2e/tests/35_http_runner.rs +++ b/e2e/tests/35_http_runner.rs @@ -31,19 +31,14 @@ fn a_request(app: &mut App, name: &str, url: &str) { app.fill("http-url", url); app.click("http-section-tests"); app.wait_for("http-script-code"); - app.fill( - "http-script-code", - "test('found', () => { expect(res.status).toBe(200); });", - ); + app.fill("http-script-code", "test('found', () => { expect(res.status).toBe(200); });"); app.eventually("the test is typed", |tree| { tree.find("http-script-code") .and_then(Node::value) .is_some_and(|text| text.contains("toBe(200)")) }); app.click("http-save"); - app.eventually("the request is saved", |tree| { - tree.find("http-save").is_some_and(Node::is_disabled) - }); + app.eventually("the request is saved", |tree| tree.find("http-save").is_some_and(Node::is_disabled)); } fn collection(app: &mut App) { @@ -62,9 +57,7 @@ fn collection(app: &mut App) { fn open_runner(app: &mut App) { app.click_where("http-node-menu", ends(API)); app.click("http-node-run"); - app.eventually("the order is read", |tree| { - tree.count("http-runner-row") == 2 - }); + app.eventually("the order is read", |tree| tree.count("http-runner-row") == 2); } fn figures(tree: &Tree) -> String { @@ -92,17 +85,13 @@ fn over_iterations(app: &mut App) { assert_eq!(tree.count("http-runner-result-failed"), 2); assert_eq!(tree.count("http-runner-test"), 2); app.click("http-runner-filter-failed"); - app.eventually("only the failed are shown", |tree| { - tree.count("http-runner-result-passed") == 0 - }); + app.eventually("only the failed are shown", |tree| tree.count("http-runner-result-passed") == 0); app.click("http-runner-filter-all"); }); step("a run writes no history", || { app.click("http-history-open"); app.wait_for("http-history"); - app.eventually("nothing is listed", |tree| { - tree.count("http-history-item") == 0 - }); + app.eventually("nothing is listed", |tree| tree.count("http-history-item") == 0); }); } @@ -166,15 +155,12 @@ fn http_runner() { app.wait_for("http-url"); app.fill("http-url", "/changed"); app.eventually("the request has changes", |tree| { - tree.find("http-save") - .is_some_and(|save| !save.is_disabled()) + tree.find("http-save").is_some_and(|save| !save.is_disabled()) }); app.act("quit"); app.wait_for("http-leave-dialog"); app.click("http-leave-cancel"); - app.eventually("the question is gone", |tree| { - !tree.has("http-leave-dialog") - }); + app.eventually("the question is gone", |tree| !tree.has("http-leave-dialog")); app.act("quit"); app.wait_for("http-leave-dialog"); app.click("http-leave-save"); diff --git a/e2e/tests/36_recette_libraries.rs b/e2e/tests/36_recette_libraries.rs index abb2b40af..7b4cac137 100644 --- a/e2e/tests/36_recette_libraries.rs +++ b/e2e/tests/36_recette_libraries.rs @@ -29,11 +29,7 @@ fn pass_the_gate(app: &mut App) { /// The key file of the only library of `profile`. fn key_file(profile: &std::path::Path) -> PathBuf { let libraries = profile.join("libraries"); - let library = std::fs::read_dir(libraries) - .unwrap() - .next() - .unwrap() - .unwrap(); + let library = std::fs::read_dir(libraries).unwrap().next().unwrap().unwrap(); library.path().join("vault.json") } @@ -42,23 +38,16 @@ fn recette_libraries() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch("36_recette_libraries", profile.path()); - step( - "LIB-01 the gate says the floor before anything is typed", - || { - app.wait_for("vault-minimum"); - assert!(app.has("vault-confirmation")); - }, - ); + step("LIB-01 the gate says the floor before anything is typed", || { + app.wait_for("vault-minimum"); + assert!(app.has("vault-confirmation")); + }); step("LIB-03 two different phrases are said to differ", || { app.fill("vault-passphrase", PASSPHRASE); app.fill("vault-confirmation", "correct horse battery stapler"); app.wait_for("vault-problem"); - assert!( - app.tree() - .find("vault-submit") - .is_some_and(egui::accesskit::Node::is_disabled) - ); + assert!(app.tree().find("vault-submit").is_some_and(egui::accesskit::Node::is_disabled)); }); // A field that reveals keeps its role and no value: the picture is what says it. @@ -112,15 +101,12 @@ fn recette_libraries() { let mut app = app.relaunch(); - step( - "LIB-08 no length rule at the unlock, only a refusal", - || { - app.fill("vault-passphrase", TOO_SHORT); - app.click("vault-submit"); - app.wait_for("vault-problem"); - assert!(!app.has("vault-minimum")); - }, - ); + step("LIB-08 no length rule at the unlock, only a refusal", || { + app.fill("vault-passphrase", TOO_SHORT); + app.click("vault-submit"); + app.wait_for("vault-problem"); + assert!(!app.has("vault-minimum")); + }); app.quit(); } @@ -143,11 +129,8 @@ fn recette_a_lost_key_file() { std::fs::rename(&kept, &key).unwrap(); let mut app = App::launch("36_recette_key_file", profile.path()); - step( - "LIB-20 the file put back, the phrase opens it again", - || { - pass_the_gate(&mut app); - }, - ); + step("LIB-20 the file put back, the phrase opens it again", || { + pass_the_gate(&mut app); + }); app.quit(); } diff --git a/e2e/tests/37_recette_socle.rs b/e2e/tests/37_recette_socle.rs index e2d95927a..271b54c3c 100644 --- a/e2e/tests/37_recette_socle.rs +++ b/e2e/tests/37_recette_socle.rs @@ -116,11 +116,7 @@ fn recette_security() { app.fill("change-passphrase-next", "court-08"); app.fill("change-passphrase-confirmation", "court-08"); app.wait_for("change-passphrase-problem"); - assert!( - app.tree() - .find("change-passphrase-submit") - .is_some_and(Node::is_disabled) - ); + assert!(app.tree().find("change-passphrase-submit").is_some_and(Node::is_disabled)); app.click("change-passphrase-cancel"); app.eventually("the dialog closed", |tree| !tree.has("change-passphrase")); }); @@ -144,56 +140,40 @@ fn recette_security() { } fn restoring(app: &mut App, profile: &Path) { - step( - "SEC-08 the restore says what leaves, and Cancel keeps it", - || { - a_note(app, LATER, "echo after"); - security(app); - app.scroll_to("settings-content", "backup-row"); - app.click("backup-restore"); - app.wait_for("backup-confirm"); - app.capture("restore-confirm"); - app.click("backup-cancel"); - app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); - close(app); - app.eventually("the note stays", |tree| { - tree.texts("note-card-title").iter().any(|it| it == LATER) - }); - }, - ); - - step( - "SEC-09 a restore sets the library aside in replaced", - || { - security(app); - app.scroll_to("settings-content", "backup-row"); - app.click("backup-restore"); - app.scroll_above( - "settings-content", - "backup-confirm-restore", - "settings-cancel", - ); - app.click("backup-confirm-restore"); - app.wait_for("vault-passphrase"); - app.wait_for("status-toast"); - app.capture("restored"); - let replaced = the_library(profile).join("replaced"); - assert!(std::fs::read_dir(replaced).unwrap().next().is_some()); - }, - ); - - step( - "SEC-10 a copy older than the change opens with the new phrase", - || { - app.fill("vault-passphrase", PASSPHRASE); - app.click("vault-submit"); - app.eventually("the old phrase is refused", |tree| { - tree.text("vault-problem") - .is_some_and(|said| !said.is_empty()) - }); - unlock(app, NEXT); - }, - ); + step("SEC-08 the restore says what leaves, and Cancel keeps it", || { + a_note(app, LATER, "echo after"); + security(app); + app.scroll_to("settings-content", "backup-row"); + app.click("backup-restore"); + app.wait_for("backup-confirm"); + app.capture("restore-confirm"); + app.click("backup-cancel"); + app.eventually("the strip is gone", |tree| !tree.has("backup-confirm")); + close(app); + app.eventually("the note stays", |tree| tree.texts("note-card-title").iter().any(|it| it == LATER)); + }); + + step("SEC-09 a restore sets the library aside in replaced", || { + security(app); + app.scroll_to("settings-content", "backup-row"); + app.click("backup-restore"); + app.scroll_above("settings-content", "backup-confirm-restore", "settings-cancel"); + app.click("backup-confirm-restore"); + app.wait_for("vault-passphrase"); + app.wait_for("status-toast"); + app.capture("restored"); + let replaced = the_library(profile).join("replaced"); + assert!(std::fs::read_dir(replaced).unwrap().next().is_some()); + }); + + step("SEC-10 a copy older than the change opens with the new phrase", || { + app.fill("vault-passphrase", PASSPHRASE); + app.click("vault-submit"); + app.eventually("the old phrase is refused", |tree| { + tree.text("vault-problem").is_some_and(|said| !said.is_empty()) + }); + unlock(app, NEXT); + }); step("SEC-09 what was written after the copy is gone", || { let titles = app.tree().texts("note-card-title"); @@ -210,21 +190,16 @@ fn recette_nothing_readable_on_the_disk() { a_note(&mut app, SECRET, SECRET); app.quit(); - step( - "SEC-12 neither title nor body can be read on the disk", - || { - let mut files = Vec::new(); - files_under(&profile.join("libraries"), &mut files); - assert!(!files.is_empty()); - for file in files { - let bytes = std::fs::read(&file).unwrap(); - let found = bytes - .windows(SECRET.len()) - .any(|window| window == SECRET.as_bytes()); - assert!(!found, "{} reads in the clear", file.display()); - } - }, - ); + step("SEC-12 neither title nor body can be read on the disk", || { + let mut files = Vec::new(); + files_under(&profile.join("libraries"), &mut files); + assert!(!files.is_empty()); + for file in files { + let bytes = std::fs::read(&file).unwrap(); + let found = bytes.windows(SECRET.len()).any(|window| window == SECRET.as_bytes()); + assert!(!found, "{} reads in the clear", file.display()); + } + }); } #[test] @@ -278,9 +253,7 @@ fn recette_window() { step("APP-07 the bar's theme switches in one click", || { let word = app.tree().text("theme-toggle").unwrap_or_default(); app.click("theme-toggle"); - app.eventually("the word changed", |tree| { - tree.text("theme-toggle").is_some_and(|now| now != word) - }); + app.eventually("the word changed", |tree| tree.text("theme-toggle").is_some_and(|now| now != word)); }); let word = app.tree().text("theme-toggle").unwrap_or_default(); @@ -291,31 +264,24 @@ fn recette_window() { assert_eq!(app.tree().text("theme-toggle").unwrap_or_default(), word); }); - step( - "APP-13 quitting takes two clicks, a click elsewhere calls it off", - || { - app.click("file-menu"); - let word = app.tree().text("file-quit").unwrap_or_default(); - app.click("file-quit"); - app.eventually("the entry asks", |tree| { - tree.text("file-quit").is_some_and(|now| now != word) - }); - app.press(Key::ArrowUp, Modifiers::NONE); - app.eventually("the arrows call it off", |tree| { - tree.text("file-quit").is_some_and(|now| now == word) - }); - app.click("file-quit"); - app.eventually("the entry asks again", |tree| { - tree.text("file-quit").is_some_and(|now| now != word) - }); - app.click("file-menu"); - app.eventually("the menu closed", |tree| !tree.has("file-quit")); - app.click("file-menu"); - assert_eq!(app.tree().text("file-quit").unwrap_or_default(), word); - app.click("file-quit"); - app.click("file-quit"); - }, - ); + step("APP-13 quitting takes two clicks, a click elsewhere calls it off", || { + app.click("file-menu"); + let word = app.tree().text("file-quit").unwrap_or_default(); + app.click("file-quit"); + app.eventually("the entry asks", |tree| tree.text("file-quit").is_some_and(|now| now != word)); + app.press(Key::ArrowUp, Modifiers::NONE); + app.eventually("the arrows call it off", |tree| { + tree.text("file-quit").is_some_and(|now| now == word) + }); + app.click("file-quit"); + app.eventually("the entry asks again", |tree| tree.text("file-quit").is_some_and(|now| now != word)); + app.click("file-menu"); + app.eventually("the menu closed", |tree| !tree.has("file-quit")); + app.click("file-menu"); + assert_eq!(app.tree().text("file-quit").unwrap_or_default(), word); + app.click("file-quit"); + app.click("file-quit"); + }); app.ended(); } @@ -342,66 +308,53 @@ fn recette_preferences() { app.capture("preferences"); }); - step( - "PRF-02 theme and density preview, Cancel takes both back", - || { - app.click(THEME_DARK); - app.click(COMFORTABLE); - app.click("settings-apply"); - let word = app.tree().text("theme-toggle").unwrap_or_default(); - let before = std::fs::read(app.capture("density-before")).unwrap(); - app.click(THEME_LIGHT); - app.click(COMPACT); - app.eventually("the theme previews", |tree| { - tree.text("theme-toggle").is_some_and(|now| now != word) - }); - assert_ne!(before, std::fs::read(app.capture("density-after")).unwrap()); - app.click("settings-cancel"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - assert_eq!(app.tree().text("theme-toggle").unwrap_or_default(), word); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_DARK))); - assert!(is_on(app.tree().find(COMFORTABLE))); - }, - ); - - step( - "PRF-05 three changes waiting are counted, each way out does as it says", - || { - app.click(THEME_LIGHT); - app.click(COMPACT); - app.click("setting-locale"); - app.click(ENGLISH); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("the footer counts them", |tree| { - tree.text("settings-unapplied") - .is_some_and(|said| said.contains('3')) - }); - app.capture("unapplied"); - app.click("settings-discard"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_DARK))); - - app.click(THEME_LIGHT); - app.press(Key::Escape, Modifiers::NONE); - app.click("settings-apply-close"); - app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); - preferences(&mut app); - assert!(is_on(app.tree().find(THEME_LIGHT))); - app.click(THEME_DARK); - close(&mut app); - }, - ); + step("PRF-02 theme and density preview, Cancel takes both back", || { + app.click(THEME_DARK); + app.click(COMFORTABLE); + app.click("settings-apply"); + let word = app.tree().text("theme-toggle").unwrap_or_default(); + let before = std::fs::read(app.capture("density-before")).unwrap(); + app.click(THEME_LIGHT); + app.click(COMPACT); + app.eventually("the theme previews", |tree| tree.text("theme-toggle").is_some_and(|now| now != word)); + assert_ne!(before, std::fs::read(app.capture("density-after")).unwrap()); + app.click("settings-cancel"); + app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); + assert_eq!(app.tree().text("theme-toggle").unwrap_or_default(), word); + preferences(&mut app); + assert!(is_on(app.tree().find(THEME_DARK))); + assert!(is_on(app.tree().find(COMFORTABLE))); + }); + + step("PRF-05 three changes waiting are counted, each way out does as it says", || { + app.click(THEME_LIGHT); + app.click(COMPACT); + app.click("setting-locale"); + app.click(ENGLISH); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("the footer counts them", |tree| { + tree.text("settings-unapplied").is_some_and(|said| said.contains('3')) + }); + app.capture("unapplied"); + app.click("settings-discard"); + app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); + preferences(&mut app); + assert!(is_on(app.tree().find(THEME_DARK))); + + app.click(THEME_LIGHT); + app.press(Key::Escape, Modifiers::NONE); + app.click("settings-apply-close"); + app.eventually("the panel closed", |tree| !tree.has("settings-dialog")); + preferences(&mut app); + assert!(is_on(app.tree().find(THEME_LIGHT))); + app.click(THEME_DARK); + close(&mut app); + }); step("PRF-15 a canvas key refuses the navigation's keys", || { preferences(&mut app); app.click("settings-page-shortcuts"); - app.scroll_above( - "settings-content", - "shortcut-field-canvas.pin", - "settings-cancel", - ); + app.scroll_above("settings-content", "shortcut-field-canvas.pin", "settings-cancel"); app.click("shortcut-field-canvas.pin"); assert!(app.has("settings-dialog")); app.press(Key::ArrowUp, Modifiers::NONE); diff --git a/e2e/tests/38_recette_notes.rs b/e2e/tests/38_recette_notes.rs index 7167679ae..17baa803b 100644 --- a/e2e/tests/38_recette_notes.rs +++ b/e2e/tests/38_recette_notes.rs @@ -44,9 +44,7 @@ fn close_editor(app: &mut App) { } fn open_card(app: &mut App, title: &str) { - app.click_where("note-card-open", |node| { - node.label().is_some_and(|label| label.contains(title)) - }); + app.click_where("note-card-open", |node| node.label().is_some_and(|label| label.contains(title))); app.wait_for("editor-title"); } @@ -67,10 +65,7 @@ fn a_snippet(app: &mut App, title: &str, body: &str) { } fn code(tree: &Tree) -> String { - tree.find("editor-body") - .and_then(Node::value) - .unwrap_or_default() - .to_owned() + tree.find("editor-body").and_then(Node::value).unwrap_or_default().to_owned() } /// A snippet holding Markdown, made a Note: what a file of Markdown comes in as. @@ -88,9 +83,7 @@ fn choose_language(app: &mut App, typed: &str, option: &str) { app.click("editor-language"); app.wait_for("editor-language-filter"); app.click("editor-language-filter"); - app.eventually("the filter has the focus", |tree| { - tree.focused().starts_with("editor-language-filter") - }); + app.eventually("the filter has the focus", |tree| tree.focused().starts_with("editor-language-filter")); app.type_text(typed); app.click(option); } @@ -147,8 +140,7 @@ fn recette_creating() { app.press(Key::A, Modifiers::COMMAND); app.type_text("Titre modifié au clic"); app.capture("not-07-before"); - let psql = - |node: &egui::accesskit::Node| node.label().is_some_and(|it| it.contains("Psql")); + let psql = |node: &egui::accesskit::Node| node.label().is_some_and(|it| it.contains("Psql")); // In a window too narrow to keep the cards beside the editor, none is there to click. let beside = app.tree().all("note-card-open").into_iter().any(psql); if beside { @@ -163,9 +155,7 @@ fn recette_creating() { if app.has("editor-title") { close_editor(&mut app); } - app.eventually("the first note wears its new title", |tree| { - has_card(tree, "Titre modifié au clic") - }); + app.eventually("the first note wears its new title", |tree| has_card(tree, "Titre modifié au clic")); }); step("NOT-10 a snippet made a Note, and taken back", || { @@ -187,21 +177,17 @@ fn recette_a_snippet_and_a_list() { let profile = tempfile::tempdir().unwrap(); let mut app = a_new_library("38_recette_snippet", profile.path()); - step( - "COD-01 the language menu filters, and the card says it", - || { - app.click("new-note"); - app.fill("editor-title", "Rouille"); - app.fill("editor-body", "fn main() { println!(\"bonjour\"); }"); - choose_language(&mut app, "rus", RUST); - app.eventually("the language is chosen", |tree| { - tree.text("editor-stats") - .is_some_and(|said| said.starts_with("RS")) - }); - app.capture("cod-01-coloured"); - close_editor(&mut app); - }, - ); + step("COD-01 the language menu filters, and the card says it", || { + app.click("new-note"); + app.fill("editor-title", "Rouille"); + app.fill("editor-body", "fn main() { println!(\"bonjour\"); }"); + choose_language(&mut app, "rus", RUST); + app.eventually("the language is chosen", |tree| { + tree.text("editor-stats").is_some_and(|said| said.starts_with("RS")) + }); + app.capture("cod-01-coloured"); + close_editor(&mut app); + }); step("COD-09 a formatted snippet keeps its fields", || { app.click("new-note"); @@ -225,14 +211,11 @@ fn recette_a_snippet_and_a_list() { app.wait_for("search-field"); app.type_text("foo"); app.eventually("three are counted", |tree| { - tree.text("search-count") - .is_some_and(|said| said.ends_with("/ 3")) + tree.text("search-count").is_some_and(|said| said.ends_with("/ 3")) }); let count = app.tree().text("search-count").unwrap_or_default(); app.press(Key::Enter, Modifiers::NONE); - app.eventually("the next one", |tree| { - tree.text("search-count").is_some_and(|said| said != count) - }); + app.eventually("the next one", |tree| tree.text("search-count").is_some_and(|said| said != count)); app.click("search-previous"); app.eventually("back to the first", |tree| { tree.text("search-count").is_some_and(|said| said == count) @@ -247,9 +230,7 @@ fn recette_a_snippet_and_a_list() { app.press(Key::L, SHIFT_COMMAND); app.fill("editor-title", "Tâches"); app.click("checklist-add"); - app.eventually("the row takes the caret", |tree| { - tree.focused().starts_with("checklist-text") - }); + app.eventually("the row takes the caret", |tree| tree.focused().starts_with("checklist-text")); app.type_text("Préparer"); app.press(Key::Enter, Modifiers::NONE); app.type_text("Déployer"); @@ -265,9 +246,7 @@ fn recette_a_snippet_and_a_list() { step("TCH-06 ticked from its card, the progress follows", || { app.click_nth("note-card-item", 0); app.eventually("the progress moved", |tree| { - tree.texts("note-card-progress") - .iter() - .any(|it| it.contains("1/2")) + tree.texts("note-card-progress").iter().any(|it| it.contains("1/2")) }); }); @@ -305,63 +284,53 @@ fn recette_a_formatted_note() { close_editor(&mut app); }); - step( - "RIC-08 a final code block is left by the down arrow", - || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Bloc final"); - app.click("editor-rich"); - app.click("rich-codeBlock"); - app.type_text("let x = 1;"); - app.press(Key::ArrowDown, Modifiers::NONE); - app.type_text("Suite"); - app.eventually("the text is under the block", |tree| { - tree.find("editor-rich") - .and_then(Node::value) - .is_some_and(|text| text.contains("let x = 1;") && text.contains("\nSuite")) - }); - close_editor(&mut app); - }, - ); - - step( - "RIC-09 what looks like Markdown comes back as typed", - || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Littéral"); - app.click("editor-rich"); - for line in LITERAL.lines() { - app.type_text(line); - app.press(Key::Enter, Modifiers::NONE); - } - close_editor(&mut app); - open_card(&mut app, "Littéral"); - app.capture("ric-09"); - close_editor(&mut app); - }, - ); - - step( - "RIC-19 a Note presented: cover, then a slide per heading", - || { - a_note_of(&mut app, "Lancement", SLIDES); - app.click("editor-present"); - app.wait_for("presentation"); - app.wait_for("presentation-cover"); - app.capture("ric-19-cover"); - let count = app.tree().text("presentation-count").unwrap_or_default(); - assert!(count.contains('1') && count.contains('4'), "{count}"); - app.press(Key::ArrowRight, Modifiers::NONE); - app.eventually("the next slide", |tree| { - tree.text("presentation-count") - .is_some_and(|now| now != count) - }); - app.capture("ric-19-slide"); - app.press(Key::Escape, Modifiers::NONE); - app.eventually("it left", |tree| !tree.has("presentation")); - close_editor(&mut app); - }, - ); + step("RIC-08 a final code block is left by the down arrow", || { + app.press(Key::N, SHIFT_COMMAND); + app.fill("editor-title", "Bloc final"); + app.click("editor-rich"); + app.click("rich-codeBlock"); + app.type_text("let x = 1;"); + app.press(Key::ArrowDown, Modifiers::NONE); + app.type_text("Suite"); + app.eventually("the text is under the block", |tree| { + tree.find("editor-rich") + .and_then(Node::value) + .is_some_and(|text| text.contains("let x = 1;") && text.contains("\nSuite")) + }); + close_editor(&mut app); + }); + + step("RIC-09 what looks like Markdown comes back as typed", || { + app.press(Key::N, SHIFT_COMMAND); + app.fill("editor-title", "Littéral"); + app.click("editor-rich"); + for line in LITERAL.lines() { + app.type_text(line); + app.press(Key::Enter, Modifiers::NONE); + } + close_editor(&mut app); + open_card(&mut app, "Littéral"); + app.capture("ric-09"); + close_editor(&mut app); + }); + + step("RIC-19 a Note presented: cover, then a slide per heading", || { + a_note_of(&mut app, "Lancement", SLIDES); + app.click("editor-present"); + app.wait_for("presentation"); + app.wait_for("presentation-cover"); + app.capture("ric-19-cover"); + let count = app.tree().text("presentation-count").unwrap_or_default(); + assert!(count.contains('1') && count.contains('4'), "{count}"); + app.press(Key::ArrowRight, Modifiers::NONE); + app.eventually("the next slide", |tree| { + tree.text("presentation-count").is_some_and(|now| now != count) + }); + app.capture("ric-19-slide"); + app.press(Key::Escape, Modifiers::NONE); + app.eventually("it left", |tree| !tree.has("presentation")); + close_editor(&mut app); + }); app.quit(); } @@ -382,25 +351,18 @@ fn recette_a_sheet_and_a_drawing() { app.paste(SHEET); app.eventually("the figures are there", |tree| { let results = calc_results(tree); - [ - "9855", "68", "25", "300", "250", "2500", "200", "1000", "6000", "2000", "5000", - ] - .iter() - .all(|it| results.contains(&(*it).to_owned())) - }); - app.eventually("one line refused, the next carries on", |tree| { - tree.count("calc-failure") == 1 + ["9855", "68", "25", "300", "250", "2500", "200", "1000", "6000", "2000", "5000"] + .iter() + .all(|it| results.contains(&(*it).to_owned())) }); + app.eventually("one line refused, the next carries on", |tree| tree.count("calc-failure") == 1); app.capture("cal-45"); }); step("CAL-37 results picked: a range, then a stranger", || { - app.click_where("calc-result", |node| { - node.value().is_some_and(|it| digits(it) == "1000") - }); + app.click_where("calc-result", |node| node.value().is_some_and(|it| digits(it) == "1000")); app.eventually("the footer sums it", |tree| { - tree.text("calc-summary") - .is_some_and(|said| digits(&said).contains("1000")) + tree.text("calc-summary").is_some_and(|said| digits(&said).contains("1000")) }); close_editor(&mut app); }); @@ -423,8 +385,7 @@ fn recette_a_sheet_and_a_drawing() { app.drag_in("drawing-stage", from, to); } app.eventually("the footer counts three", |tree| { - tree.text("editor-stats") - .is_some_and(|said| said.contains('3')) + tree.text("editor-stats").is_some_and(|said| said.contains('3')) }); app.capture("des-02"); }); @@ -435,23 +396,19 @@ fn recette_a_sheet_and_a_drawing() { app.click("note-card-drawing"); app.wait_for("drawing-stage"); app.eventually("the footer still counts three", |tree| { - tree.text("editor-stats") - .is_some_and(|said| said.contains('3')) + tree.text("editor-stats").is_some_and(|said| said.contains('3')) }); close_editor(&mut app); }); - step( - "DES-13 a drawing inserted into a Note shows its picture", - || { - app.press(Key::N, SHIFT_COMMAND); - app.fill("editor-title", "Avec dessin"); - app.click("rich-embed-drawing"); - app.click("rich-embed-drawing-0"); - app.wait_for("rich-embed"); - app.capture("des-13"); - }, - ); + step("DES-13 a drawing inserted into a Note shows its picture", || { + app.press(Key::N, SHIFT_COMMAND); + app.fill("editor-title", "Avec dessin"); + app.click("rich-embed-drawing"); + app.click("rich-embed-drawing-0"); + app.wait_for("rich-embed"); + app.capture("des-13"); + }); step("a drawing in a Note is resized, and stays so", || { let width = |tree: &Tree| { @@ -463,13 +420,9 @@ fn recette_a_sheet_and_a_drawing() { app.wait_for("rich-embed-resize"); let whole = width(&app.tree()); app.click("rich-embed-size-1"); - app.eventually("a quarter of the width", |tree| { - (width(tree) - whole / 4.0).abs() < 2.0 - }); + app.eventually("a quarter of the width", |tree| (width(tree) - whole / 4.0).abs() < 2.0); app.drag_in("rich-embed-resize", (12.0, 12.0), (1_200.0, 12.0)); - app.eventually("the whole width again", |tree| { - (width(tree) - whole).abs() < 2.0 - }); + app.eventually("the whole width again", |tree| (width(tree) - whole).abs() < 2.0); app.capture("des-13-sized"); close_editor(&mut app); open_card(&mut app, "Avec dessin"); @@ -513,14 +466,10 @@ fn recette_on_the_canvas() { let pinned = app.tree().count("note-card-pin"); app.press(Key::ArrowDown, Modifiers::NONE); app.press(Key::P, Modifiers::NONE); - app.eventually("the pin moved", |tree| { - tree.count("note-card-pin") != pinned - }); + app.eventually("the pin moved", |tree| tree.count("note-card-pin") != pinned); assert_eq!(sorted(app.tree().texts("note-card-when")), when); app.click("undo-restore"); - app.eventually("the pin is back", |tree| { - tree.count("note-card-pin") == pinned - }); + app.eventually("the pin is back", |tree| tree.count("note-card-pin") == pinned); }); step("CLV-02 C copies a plain card and says so", || { @@ -530,29 +479,24 @@ fn recette_on_the_canvas() { app.capture("clv-02"); }); - step( - "SEL-02 a selection moved to a space, and taken back", - || { - app.click("space-create-open"); - app.fill("space-create-input", "Perso"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the new space is shown, empty", |tree| { - !tree.has("note-card") - }); - app.click("space-option-all"); - app.eventually("the cards are back", |tree| tree.has("note-card")); - app.press(Key::ArrowDown, Modifiers::NONE); - for key in [Key::X, Key::ArrowRight, Key::X] { - app.press(key, Modifiers::NONE); - } - app.click("selection-move"); - app.click_where("selection-move-place", |node| node.label() == Some("Perso")); - app.wait_for("undo-text"); - app.capture("sel-02"); - app.click("undo-restore"); - app.eventually("the bar went", |tree| !tree.has("undo-text")); - }, - ); + step("SEL-02 a selection moved to a space, and taken back", || { + app.click("space-create-open"); + app.fill("space-create-input", "Perso"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the new space is shown, empty", |tree| !tree.has("note-card")); + app.click("space-option-all"); + app.eventually("the cards are back", |tree| tree.has("note-card")); + app.press(Key::ArrowDown, Modifiers::NONE); + for key in [Key::X, Key::ArrowRight, Key::X] { + app.press(key, Modifiers::NONE); + } + app.click("selection-move"); + app.click_where("selection-move-place", |node| node.label() == Some("Perso")); + app.wait_for("undo-text"); + app.capture("sel-02"); + app.click("undo-restore"); + app.eventually("the bar went", |tree| !tree.has("undo-text")); + }); step("SEL-09 a selection trashed, then given back whole", || { let cards = app.tree().count("note-card"); @@ -577,27 +521,22 @@ fn recette_a_line_gone_to() { let profile = tempfile::tempdir().unwrap(); let mut app = a_new_library("38_recette_go_to_line", profile.path()); - step( - "COD-15 Ctrl+Alt+G goes to a line, the keys back in the code", - || { - app.click("new-note"); - app.fill("editor-title", "Lignes"); - app.click("editor-body"); - app.paste("un\ndeux\ntrois"); - app.press(Key::G, Modifiers::COMMAND | Modifiers::ALT); - app.eventually("the field has the focus", |tree| { - tree.focused().starts_with("go-to-line-input") - }); - app.type_text("2"); - app.press(Key::Enter, Modifiers::NONE); - app.eventually("the code has the focus", |tree| { - !tree.has("go-to-line-input") && tree.focused().starts_with("editor-body") - }); - app.type_text("X"); - app.eventually("typed on line 2", |tree| code(tree) == "un\nXdeux\ntrois"); - close_editor(&mut app); - }, - ); + step("COD-15 Ctrl+Alt+G goes to a line, the keys back in the code", || { + app.click("new-note"); + app.fill("editor-title", "Lignes"); + app.click("editor-body"); + app.paste("un\ndeux\ntrois"); + app.press(Key::G, Modifiers::COMMAND | Modifiers::ALT); + app.eventually("the field has the focus", |tree| tree.focused().starts_with("go-to-line-input")); + app.type_text("2"); + app.press(Key::Enter, Modifiers::NONE); + app.eventually("the code has the focus", |tree| { + !tree.has("go-to-line-input") && tree.focused().starts_with("editor-body") + }); + app.type_text("X"); + app.eventually("typed on line 2", |tree| code(tree) == "un\nXdeux\ntrois"); + close_editor(&mut app); + }); app.quit(); } diff --git a/e2e/tests/39_recette_tools.rs b/e2e/tests/39_recette_tools.rs index 5dffe48c3..23f3c76e9 100644 --- a/e2e/tests/39_recette_tools.rs +++ b/e2e/tests/39_recette_tools.rs @@ -11,13 +11,7 @@ const PIXEL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAA const SCHEMA: &str = r#"{"type":"object","required":["id","email","age","role"],"properties":{"id":{"type":"string","format":"uuid"},"email":{"type":"string","format":"email"},"age":{"type":"integer","minimum":18,"maximum":99},"role":{"enum":["admin","lecteur","redacteur"]}}}"#; /// One line of the sheet: the tool, its field, what is typed, and what must be read. -type Case = ( - &'static str, - &'static str, - &'static str, - &'static str, - &'static [&'static str], -); +type Case = (&'static str, &'static str, &'static str, &'static str, &'static [&'static str]); const CASES: &[Case] = &[ ( @@ -82,55 +76,13 @@ const CASES: &[Case] = &[ r#"{"service":"billing","replicas":2,"tags":["api","web"],"debug":null}"#, &["service: billing", "replicas: 2", "debug: null"], ), - ( - "ENC-19", - "colour", - "colour-input", - "#1e90ff", - &["#1e90ff", "30 144 255", "209.6", "oklch("], - ), - ( - "GEN-18", - "qr", - "qr-url", - "https://devnotes.fr", - &["Récupérable"], - ), - ( - "TPS-01", - "dates", - "dates-input", - "1790000000", - &["2026-09-21T14:13:20Z", "secondes", "lundi"], - ), - ( - "TPS-18", - "cron", - "cron-input", - "*/15 9-18 * * MON-FRI", - &["15 minutes", "lundi", "vendredi"], - ), - ( - "CMP-01", - "sizes", - "sizes-input", - "1,5 Go", - &["1 500 000 000", "1,397", "1 430,51", "12"], - ), - ( - "CMP-07", - "permissions", - "permissions-octal", - "755", - &["rwxr-xr-x", "chmod"], - ), - ( - "CMP-13", - "checks", - "checks-input", - "4111 1111 1111 1111", - &["Valide", "Visa"], - ), + ("ENC-19", "colour", "colour-input", "#1e90ff", &["#1e90ff", "30 144 255", "209.6", "oklch("]), + ("GEN-18", "qr", "qr-url", "https://devnotes.fr", &["Récupérable"]), + ("TPS-01", "dates", "dates-input", "1790000000", &["2026-09-21T14:13:20Z", "secondes", "lundi"]), + ("TPS-18", "cron", "cron-input", "*/15 9-18 * * MON-FRI", &["15 minutes", "lundi", "vendredi"]), + ("CMP-01", "sizes", "sizes-input", "1,5 Go", &["1 500 000 000", "1,397", "1 430,51", "12"]), + ("CMP-07", "permissions", "permissions-octal", "755", &["rwxr-xr-x", "chmod"]), + ("CMP-13", "checks", "checks-input", "4111 1111 1111 1111", &["Valide", "Visa"]), ( "CMP-13", "checks", @@ -138,20 +90,8 @@ const CASES: &[Case] = &[ "4111 1111 1111 1112", &["Invalide", "Le dernier chiffre devrait être 1."], ), - ( - "CMP-13", - "checks", - "checks-input", - "378282246310005", - &["Valide", "American Express"], - ), - ( - "CMP-13", - "checks", - "checks-input", - "5555 5555 5555 4444", - &["Valide", "Mastercard"], - ), + ("CMP-13", "checks", "checks-input", "378282246310005", &["Valide", "American Express"]), + ("CMP-13", "checks", "checks-input", "5555 5555 5555 4444", &["Valide", "Mastercard"]), ( "CMP-14", "checks", @@ -244,11 +184,7 @@ fn recette_tools_of_several_gestures() { step("TXT-07 mixed endings are read and put right", || { open_tool(&mut app, "line-breaks"); - retype( - &mut app, - "line-breaks-input", - "un\r\ndeux \ntrois\rquatre ", - ); + retype(&mut app, "line-breaks-input", "un\r\ndeux \ntrois\rquatre "); app.wait_for("line-breaks-found"); app.capture("TXT-06"); app.click("line-breaks-trim"); @@ -273,11 +209,7 @@ fn recette_tools_of_several_gestures() { step("TXT-14 two documents compared as data", || { app.click("diff-mode-1"); - retype( - &mut app, - "structured-diff-a", - r#"{"total":126,"client":{"ville":"Lyon"},"remise":null}"#, - ); + retype(&mut app, "structured-diff-a", r#"{"total":126,"client":{"ville":"Lyon"},"remise":null}"#); retype( &mut app, "structured-diff-b", @@ -301,10 +233,7 @@ fn recette_crypto() { retype(&mut app, "hash-input", "DevNotes"); app.click("hash-hmac"); retype(&mut app, "hash-key", "secret"); - reads( - &mut app, - &["4b86bba0e71ff3bea4180fc0ee8abc4d7f5939927d5f1a1acee89b837e47ec7a"], - ); + reads(&mut app, &["4b86bba0e71ff3bea4180fc0ee8abc4d7f5939927d5f1a1acee89b837e47ec7a"]); app.click("hash-encoding-1"); reads(&mut app, &["S4a7oOcf876kGA/A7oq8TX9ZOZJ9Xxoazuibg35H7Ho="]); app.capture("CRY-03"); @@ -316,9 +245,7 @@ fn recette_crypto() { app.capture("CRY-08"); let first = app.tree().texts("output-value"); app.click("password-generate"); - app.eventually("others are drawn", |tree| { - tree.texts("output-value") != first - }); + app.eventually("others are drawn", |tree| tree.texts("output-value") != first); }); step("CRY-11 identifiers of each kind", || { @@ -330,10 +257,7 @@ fn recette_crypto() { step("CRY-12 identifiers read back", || { for (id, words) in [ ("01ARZ3NDEKTSV4RRFFQ69G5FAV", &["ULID", "2016"][..]), - ( - "550e8400-e29b-41d4-a716-446655440000", - &["UUID", "RFC 9562"], - ), + ("550e8400-e29b-41d4-a716-446655440000", &["UUID", "RFC 9562"]), ("507f1f77bcf86cd799439011", &["ObjectId", "2012"]), ("00000000-0000-0000-0000-000000000000", &["UUID nul"]), ("bonjour", &["Aucun identifiant connu"]), @@ -370,19 +294,7 @@ fn recette_encoders() { "url-parser-input", "https://ada:pwd@api.exemple.fr:8443/v1/factures?statut=payée&page=2#total", ); - reads( - &mut app, - &[ - "https", - "ada", - "pwd", - "api.exemple.fr", - "8443", - "/v1/factures", - "payée", - "total", - ], - ); + reads(&mut app, &["https", "ada", "pwd", "api.exemple.fr", "8443", "/v1/factures", "payée", "total"]); app.capture("ENC-04"); }); @@ -404,20 +316,17 @@ fn recette_encoders() { app.capture("ENC-11"); }); - step( - "ENC-19 what is no colour, ENC-20 a contrast put right", - || { - open_tool(&mut app, "colour"); - retype(&mut app, "colour-input", "pas-une-couleur"); - app.wait_for("colour-invalid"); - retype(&mut app, "colour-input", "#777777"); - retype(&mut app, "colour-against", "#ffffff"); - reads(&mut app, &["4,48"]); - app.click("colour-fix"); - reads(&mut app, &["4,5"]); - app.capture("ENC-20"); - }, - ); + step("ENC-19 what is no colour, ENC-20 a contrast put right", || { + open_tool(&mut app, "colour"); + retype(&mut app, "colour-input", "pas-une-couleur"); + app.wait_for("colour-invalid"); + retype(&mut app, "colour-input", "#777777"); + retype(&mut app, "colour-against", "#ffffff"); + reads(&mut app, &["4,48"]); + app.click("colour-fix"); + reads(&mut app, &["4,5"]); + app.capture("ENC-20"); + }); app.quit(); } @@ -437,10 +346,7 @@ fn recette_the_rest() { step("GEN-16 lorem ipsum, opening on its words", || { open_tool(&mut app, "lorem"); - reads( - &mut app, - &["Lorem ipsum dolor sit amet, consectetur adipiscing elit"], - ); + reads(&mut app, &["Lorem ipsum dolor sit amet, consectetur adipiscing elit"]); let first = app.tree().text("lorem-output"); app.click("lorem-again"); app.eventually("another text", |tree| tree.text("lorem-output") != first); @@ -504,15 +410,12 @@ fn recette_the_home() { app.capture("OUT-01"); }); - step( - "OUT-02 a category found by its name, without its accents", - || { - app.fill("tools-search", "generateur"); - for tool in ["json-generator", "identity", "lorem", "qr"] { - app.wait_for(&format!("tools-entry-{tool}")); - } - }, - ); + step("OUT-02 a category found by its name, without its accents", || { + app.fill("tools-search", "generateur"); + for tool in ["json-generator", "identity", "lorem", "qr"] { + app.wait_for(&format!("tools-entry-{tool}")); + } + }); step("OUT-03 a reference found, opened by Enter", || { app.press(Key::A, Modifiers::COMMAND); diff --git a/e2e/tests/40_recette_http.rs b/e2e/tests/40_recette_http.rs index d9983ddca..dee05238d 100644 --- a/e2e/tests/40_recette_http.rs +++ b/e2e/tests/40_recette_http.rs @@ -21,10 +21,7 @@ fn values(tree: &Tree, author_id: &str) -> Vec { } fn url_of(tree: &Tree) -> String { - tree.find("http-url") - .and_then(Node::value) - .unwrap_or_default() - .to_owned() + tree.find("http-url").and_then(Node::value).unwrap_or_default().to_owned() } fn set_url(app: &mut App, url: &str) { @@ -82,9 +79,7 @@ fn recette_composing() { app.click("http-rail-empty-create"); app.fill("http-create-input", COLLECTION); app.press(Key::Enter, Modifiers::NONE); - app.eventually("it is listed", |tree| { - tree.texts("http-node-name") == [COLLECTION] - }); + app.eventually("it is listed", |tree| tree.texts("http-node-name") == [COLLECTION]); }); step("HRQ-02 saved: a name is asked, and a place", || { @@ -101,23 +96,18 @@ fn recette_composing() { app.fill("http-save-name", "Lire une facture"); app.click("http-save-submit"); app.eventually("it is in the rail", |tree| { - tree.texts("http-node-name") - .iter() - .any(|it| it.ends_with("Lire une facture")) + tree.texts("http-node-name").iter().any(|it| it.ends_with("Lire une facture")) }); }); - step( - "HRQ-04 a saved request changed asks before it closes", - || { - set_url(&mut app, "https://exemple.fr/autre"); - app.capture("hrq-04-dot"); - app.click_nth("http-tab-close", 0); - app.wait_for("http-close-modified"); - app.click("http-close-cancel"); - app.eventually("the dialog closed", |tree| !tree.has("http-close-dialog")); - }, - ); + step("HRQ-04 a saved request changed asks before it closes", || { + set_url(&mut app, "https://exemple.fr/autre"); + app.capture("hrq-04-dot"); + app.click_nth("http-tab-close", 0); + app.wait_for("http-close-modified"); + app.click("http-close-cancel"); + app.eventually("the dialog closed", |tree| !tree.has("http-close-dialog")); + }); step("HRQ-05 the URL and its table agree", || { set_url(&mut app, "https://exemple.fr/get?page=2&q=café"); @@ -132,38 +122,31 @@ fn recette_composing() { app.type_text("limit"); app.click_nth("http-kv-value", 2); app.type_text("10"); - app.eventually("limit joins the URL", |tree| { - url_of(tree).contains("limit=10") - }); + app.eventually("limit joins the URL", |tree| url_of(tree).contains("limit=10")); append_to_url(&mut app, "&x={{page}}"); - app.eventually("a variable stays as written", |tree| { - url_of(tree).contains("{{page}}") - }); + app.eventually("a variable stays as written", |tree| url_of(tree).contains("{{page}}")); }); - step( - "HRQ-06 headers pasted are as many rows, typed ones split", - || { - app.click("http-section-headers"); - app.wait_for("http-implied-headers"); - app.click_nth("http-kv-key", 0); - app.paste("Accept: application/json\nX-Trace: abc\nX-Tenant: recette"); - app.eventually("three rows", |tree| { - values(tree, "http-kv-key").starts_with(&[ - "Accept".to_owned(), - "X-Trace".to_owned(), - "X-Tenant".to_owned(), - ]) - }); - let last = app.tree().count("http-kv-key") - 1; - app.click_nth("http-kv-key", last); - app.type_text("X-Recette: 1"); - app.eventually("key and value apart", |tree| { - values(tree, "http-kv-key").contains(&"X-Recette".to_owned()) - && values(tree, "http-kv-value").contains(&"1".to_owned()) - }); - }, - ); + step("HRQ-06 headers pasted are as many rows, typed ones split", || { + app.click("http-section-headers"); + app.wait_for("http-implied-headers"); + app.click_nth("http-kv-key", 0); + app.paste("Accept: application/json\nX-Trace: abc\nX-Tenant: recette"); + app.eventually("three rows", |tree| { + values(tree, "http-kv-key").starts_with(&[ + "Accept".to_owned(), + "X-Trace".to_owned(), + "X-Tenant".to_owned(), + ]) + }); + let last = app.tree().count("http-kv-key") - 1; + app.click_nth("http-kv-key", last); + app.type_text("X-Recette: 1"); + app.eventually("key and value apart", |tree| { + values(tree, "http-kv-key").contains(&"X-Recette".to_owned()) + && values(tree, "http-kv-value").contains(&"1".to_owned()) + }); + }); what_goes_with_it(&mut app); app.quit_discarding(); @@ -184,20 +167,15 @@ fn what_goes_with_it(app: &mut App) { app.capture("hrq-09"); }); - step( - "HRL-06 a folder deleted says which change goes with it", - || { - app.click_where("http-node-menu", |node| { - node.label().is_some_and(|it| it.ends_with(COLLECTION)) - }); - app.click("http-node-delete"); - app.wait_for("http-delete-unsaved"); - app.capture("hrl-06"); - app.click("http-delete-cancel"); - app.eventually("nothing went", |tree| !tree.has("http-delete-unsaved")); - assert_eq!(app.tree().count("http-node-name"), 2); - }, - ); + step("HRL-06 a folder deleted says which change goes with it", || { + app.click_where("http-node-menu", |node| node.label().is_some_and(|it| it.ends_with(COLLECTION))); + app.click("http-node-delete"); + app.wait_for("http-delete-unsaved"); + app.capture("hrl-06"); + app.click("http-delete-cancel"); + app.eventually("nothing went", |tree| !tree.has("http-delete-unsaved")); + assert_eq!(app.tree().count("http-node-name"), 2); + }); } fn append_to_url(app: &mut App, words: &str) { @@ -272,11 +250,7 @@ fn recette_sending() { app.click("http-method"); app.click("http-method-0"); send(&mut app, &at("/json")); - for view in [ - "http-response-view-0", - "http-response-view-1", - "http-response-view-3", - ] { + for view in ["http-response-view-0", "http-response-view-1", "http-response-view-3"] { app.click(view); app.capture(view); } diff --git a/e2e/tests/41_note_fullscreen.rs b/e2e/tests/41_note_fullscreen.rs index bec34bc68..5eccac03c 100644 --- a/e2e/tests/41_note_fullscreen.rs +++ b/e2e/tests/41_note_fullscreen.rs @@ -32,13 +32,9 @@ fn note_left(tree: &Tree) -> f64 { fn sidebar_folded_under_an_expanded_note(app: &mut App) { let left = note_left(&app.tree()); app.click("library-rail-toggle"); - app.eventually("the note took the sidebar's room", |tree| { - note_left(tree) < left - 100.0 - }); + app.eventually("the note took the sidebar's room", |tree| note_left(tree) < left - 100.0); app.click("library-rail-toggle"); - app.eventually("and gave it back", |tree| { - (note_left(tree) - left).abs() < 1.0 - }); + app.eventually("and gave it back", |tree| (note_left(tree) - left).abs() < 1.0); } #[test] @@ -50,31 +46,26 @@ fn note_fullscreen() { // Room for the details beside the body. app.resize(1_440, 900); - step( - "a snippet expanded: its fields over the code, filled under it, details beside", - || { - app.click("new-note-kind"); - app.click("new-note-snippet"); - app.fill("editor-title", "Connexion"); - app.click("editor-body"); - app.paste("psql -h {{host}} -p {{port=5432}}"); - app.click("editor-title"); - app.wait_for("placeholder-input"); - app.click("editor-fullscreen"); - app.eventually("the column and the filled text", |tree| { - !tree.has("note-card") && tree.has("editor-space") && tree.has("editor-filled") - }); - app.click_nth("placeholder-input", 0); - app.type_text("db.internal"); - app.click("editor-title"); - app.eventually("one field of two filled", |tree| { - tree.find("placeholder-panel-toggle") - .and_then(|toggle| toggle.value()) - == Some("1/2") - }); - app.capture("snippet"); - }, - ); + step("a snippet expanded: its fields over the code, filled under it, details beside", || { + app.click("new-note-kind"); + app.click("new-note-snippet"); + app.fill("editor-title", "Connexion"); + app.click("editor-body"); + app.paste("psql -h {{host}} -p {{port=5432}}"); + app.click("editor-title"); + app.wait_for("placeholder-input"); + app.click("editor-fullscreen"); + app.eventually("the column and the filled text", |tree| { + !tree.has("note-card") && tree.has("editor-space") && tree.has("editor-filled") + }); + app.click_nth("placeholder-input", 0); + app.type_text("db.internal"); + app.click("editor-title"); + app.eventually("one field of two filled", |tree| { + tree.find("placeholder-panel-toggle").and_then(|toggle| toggle.value()) == Some("1/2") + }); + app.capture("snippet"); + }); step("the details are put away, then shown again", || { app.click("editor-details"); @@ -99,36 +90,27 @@ fn note_fullscreen() { let all = app.tree().count("checklist-text"); app.click_nth("checklist-check", 0); app.click("checklist-shown-2"); - app.eventually("the task done, alone", |tree| { - tree.count("checklist-text") == 1 - }); + app.eventually("the task done, alone", |tree| tree.count("checklist-text") == 1); app.capture("tasks"); app.click("checklist-shown-0"); - app.eventually("every task again", |tree| { - tree.count("checklist-text") == all - }); + app.eventually("every task again", |tree| tree.count("checklist-text") == all); close(&mut app); }); - step( - "a title typed is written when J opens the next note", - || { - app.click_nth("note-card-open", 0); - app.wait_for("editor-position"); - app.click("editor-title"); - app.press(Key::A, Modifiers::COMMAND); - app.type_text(RENAMED); - // The title takes the keys: Escape gives it up first. - app.press(Key::Escape, Modifiers::NONE); - app.press(Key::J, Modifiers::NONE); - app.eventually("the next note open", |tree| { - tree.has("editor-title") && open_title(tree) != RENAMED - }); - // Stepped to, the note leaves the keys to J and K. - app.press(Key::K, Modifiers::NONE); - app.eventually("the draft written", |tree| open_title(tree) == RENAMED); - }, - ); + step("a title typed is written when J opens the next note", || { + app.click_nth("note-card-open", 0); + app.wait_for("editor-position"); + app.click("editor-title"); + app.press(Key::A, Modifiers::COMMAND); + app.type_text(RENAMED); + // The title takes the keys: Escape gives it up first. + app.press(Key::Escape, Modifiers::NONE); + app.press(Key::J, Modifiers::NONE); + app.eventually("the next note open", |tree| tree.has("editor-title") && open_title(tree) != RENAMED); + // Stepped to, the note leaves the keys to J and K. + app.press(Key::K, Modifiers::NONE); + app.eventually("the draft written", |tree| open_title(tree) == RENAMED); + }); app.quit(); } diff --git a/e2e/tests/43_close_to_tray.rs b/e2e/tests/43_close_to_tray.rs index 6eaf49e33..52c372996 100644 --- a/e2e/tests/43_close_to_tray.rs +++ b/e2e/tests/43_close_to_tray.rs @@ -53,26 +53,18 @@ fn close_to_tray() { tree.count("note-card") == CARDS && tree.has("window-shown") }); - step( - "closed, it hides, and a second launch, as the menu's entry, brings it back", - || { - let before = close(&mut app); - app.launch_again(); - back(&mut app, before, |tree| { - tree.count("note-card") == CARDS && !tree.has("palette-input") - }); - }, - ); - - step( - "hidden, the palette's global action brings it back with the palette", - || { - let before = close(&mut app); - app.act("palette"); - back(&mut app, before, with_the_palette); - close_the_palette(&mut app); - }, - ); + step("closed, it hides, and a second launch, as the menu's entry, brings it back", || { + let before = close(&mut app); + app.launch_again(); + back(&mut app, before, |tree| tree.count("note-card") == CARDS && !tree.has("palette-input")); + }); + + step("hidden, the palette's global action brings it back with the palette", || { + let before = close(&mut app); + app.act("palette"); + back(&mut app, before, with_the_palette); + close_the_palette(&mut app); + }); step("the tray's Palette does the same", || { let before = close(&mut app); @@ -95,11 +87,8 @@ fn close_to_tray() { #[test] fn with_the_preference_off_the_close_button_ends_the_application() { let profile = tempfile::tempdir().unwrap(); - std::fs::write( - profile.path().join("preferences.json"), - r#"{ "devnotes.closeToTray": "false" }"#, - ) - .unwrap(); + std::fs::write(profile.path().join("preferences.json"), r#"{ "devnotes.closeToTray": "false" }"#) + .unwrap(); let mut app = App::launch("43_close_to_tray", profile.path()); app.wait_for("vault-confirmation"); @@ -113,29 +102,21 @@ fn the_linux_tray_answers_a_watcher_started_after_it() { let profile = tempfile::tempdir().unwrap(); let mut app = App::launch_on_bus("43_close_to_tray", profile.path(), &bus.address); app.create_library(); - app.eventually("the samples are drawn", |tree| { - tree.count("note-card") == CARDS - }); + app.eventually("the samples are drawn", |tree| tree.count("note-card") == CARDS); let watcher = linux::Watcher::serve(&bus.address); let menu = linux::Menu::of(&watcher); - step( - "a watcher started after the application gets its item and menu", - || { - assert_eq!(menu.entries.len(), 6, "{:?}", menu.entries); - assert_eq!(menu.entries[4].1, "separator"); - }, - ); - - step( - "hidden, the menu's Palette brings the window back with the palette", - || { - let before = close(&mut app); - menu.click(menu.entries[3].0); - back(&mut app, before, with_the_palette); - close_the_palette(&mut app); - }, - ); + step("a watcher started after the application gets its item and menu", || { + assert_eq!(menu.entries.len(), 6, "{:?}", menu.entries); + assert_eq!(menu.entries[4].1, "separator"); + }); + + step("hidden, the menu's Palette brings the window back with the palette", || { + let before = close(&mut app); + menu.click(menu.entries[3].0); + back(&mut app, before, with_the_palette); + close_the_palette(&mut app); + }); menu.click(menu.entries[5].0); app.ended(); @@ -173,10 +154,7 @@ mod linux { BufReader::new(daemon.stdout.take().expect("its address")) .read_line(&mut address) .expect("dbus-daemon says its address"); - Bus { - daemon, - address: address.trim().to_owned(), - } + Bus { daemon, address: address.trim().to_owned() } } } @@ -195,10 +173,7 @@ mod linux { #[zbus::interface(name = "org.kde.StatusNotifierWatcher")] impl Registry { /// By its bus name, or by its path from its own connection. - #[expect( - clippy::needless_pass_by_value, - reason = "zbus hands the header over by value" - )] + #[expect(clippy::needless_pass_by_value, reason = "zbus hands the header over by value")] fn register_status_notifier_item( &self, service: &str, @@ -229,10 +204,7 @@ mod linux { .unwrap() .build() .unwrap(); - Watcher { - connection, - registered, - } + Watcher { connection, registered } } } @@ -257,16 +229,11 @@ mod linux { ) .unwrap(); let path: OwnedObjectPath = sni.get_property("Menu").unwrap(); - let proxy = Proxy::new( - &watcher.connection, - item, - path.as_str().to_owned(), - "com.canonical.dbusmenu", - ) - .unwrap(); - let (_, (_, _, children)): (u32, Entry) = proxy - .call("GetLayout", &(0_i32, 1_i32, Vec::::new())) - .unwrap(); + let proxy = + Proxy::new(&watcher.connection, item, path.as_str().to_owned(), "com.canonical.dbusmenu") + .unwrap(); + let (_, (_, _, children)): (u32, Entry) = + proxy.call("GetLayout", &(0_i32, 1_i32, Vec::::new())).unwrap(); let entries = children.iter().map(entry).collect(); Menu { proxy, entries } } @@ -282,8 +249,7 @@ mod linux { let child = Structure::try_from(child.try_clone().unwrap()).expect("an entry"); let fields = child.fields(); let id = i32::try_from(&fields[0]).expect("an entry's id"); - let properties = - HashMap::::try_from(fields[1].try_clone().unwrap()).unwrap(); + let properties = HashMap::::try_from(fields[1].try_clone().unwrap()).unwrap(); let kind = properties .get("type") .and_then(|kind| kind.downcast_ref::().ok()) diff --git a/e2e/tests/44_window_controls.rs b/e2e/tests/44_window_controls.rs index 6668f255b..799160b6c 100644 --- a/e2e/tests/44_window_controls.rs +++ b/e2e/tests/44_window_controls.rs @@ -16,9 +16,7 @@ fn maximized_on_disk(profile: &Path) -> bool { } fn name_of(app: &mut App, author_id: &str) -> String { - app.tree() - .text(author_id) - .unwrap_or_else(|| panic!("{author_id} is named")) + app.tree().text(author_id).unwrap_or_else(|| panic!("{author_id} is named")) } #[test] @@ -31,8 +29,7 @@ fn maximised_then_restored_and_the_next_launch_remembers() { step("maximised, the control names the restore", || { app.click("window-maximize"); app.eventually("the window is maximised", |tree| { - tree.text("window-maximize") - .is_some_and(|name| name != maximize) + tree.text("window-maximize").is_some_and(|name| name != maximize) }); app.capture("maximised"); }); @@ -41,8 +38,7 @@ fn maximised_then_restored_and_the_next_launch_remembers() { step("the next launch opens maximised", || { assert!(maximized_on_disk(profile.path())); app.eventually("the window comes back maximised", |tree| { - tree.text("window-maximize") - .is_some_and(|name| name != maximize) + tree.text("window-maximize").is_some_and(|name| name != maximize) }); }); @@ -81,11 +77,8 @@ fn minimised_it_goes_out_of_sight_and_a_launch_brings_it_back() { #[test] fn with_the_preference_off_close_ends_the_application() { let profile = tempfile::tempdir().unwrap(); - std::fs::write( - profile.path().join("preferences.json"), - r#"{ "devnotes.closeToTray": "false" }"#, - ) - .unwrap(); + std::fs::write(profile.path().join("preferences.json"), r#"{ "devnotes.closeToTray": "false" }"#) + .unwrap(); let mut app = App::launch("44_window_controls", profile.path()); app.wait_for("window-close"); diff --git a/golden/intl/cases.json b/golden/intl/cases.json index 641776101..12b15c937 100644 --- a/golden/intl/cases.json +++ b/golden/intl/cases.json @@ -271,438 +271,6 @@ }, "output": "Monday, November 8, 1971" }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "http-history.store draft name", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "11:05" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "http-history.store draft name", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "00:59" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "http-history.store draft name", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "01:00" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "http-history.store draft name", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "05:25" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "http-history.store draft name", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "11:05 AM" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "http-history.store draft name", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "12:59 AM" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "http-history.store draft name", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "01:00 AM" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "http-history.store draft name", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit" - }, - "output": "05:25 AM" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "history-page day", - "lang": "fr", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "samedi 25 juillet" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "history-page day", - "lang": "fr", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "vendredi 1 janvier" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "history-page day", - "lang": "fr", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "vendredi 1 janvier" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "history-page day", - "lang": "fr", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "lundi 8 novembre" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "history-page day", - "lang": "en", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "Saturday, July 25" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "history-page day", - "lang": "en", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "Friday, January 1" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "history-page day", - "lang": "en", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "Friday, January 1" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "history-page day", - "lang": "en", - "weekday": "long", - "day": "numeric", - "month": "long" - }, - "output": "Monday, November 8" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "history-page time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "11:05:07" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "history-page time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "00:59:59" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "history-page time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "01:00:00" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "history-page time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "05:25:55" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "history-page time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "11:05:07 AM" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "history-page time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "12:59:59 AM" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "history-page time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "01:00:00 AM" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "history-page time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit" - }, - "output": "05:25:55 AM" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "fr", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "25 juil. 2026, 11:05" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "fr", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "1 janv. 2027, 00:59" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "fr", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "1 janv. 2027, 01:00" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "fr", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "8 nov. 1971, 05:25" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "en", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "Jul 25, 2026, 11:05 AM" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "en", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "Jan 1, 2027, 12:59 AM" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "en", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "Jan 1, 2027, 1:00 AM" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "cookie-jar-dialog expiry", - "lang": "en", - "dateStyle": "medium", - "timeStyle": "short" - }, - "output": "Nov 8, 1971, 5:25 AM" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "socket-log time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "11:05:07,123" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "socket-log time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "00:59:59,999" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "socket-log time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "01:00:00,000" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "socket-log time", - "lang": "fr", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "05:25:55,000" - }, - { - "input": "2026-07-25T09:05:07.123Z", - "options": { - "site": "socket-log time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "11:05:07.123 AM" - }, - { - "input": "2026-12-31T23:59:59.999Z", - "options": { - "site": "socket-log time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "12:59:59.999 AM" - }, - { - "input": "2027-01-01T00:00:00.000Z", - "options": { - "site": "socket-log time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "01:00:00.000 AM" - }, - { - "input": "1971-11-08T04:25:55.000Z", - "options": { - "site": "socket-log time", - "lang": "en", - "hour": "2-digit", - "minute": "2-digit", - "second": "2-digit", - "fractionalSecondDigits": 3 - }, - "output": "05:25:55.000 AM" - }, { "input": "2026-07-25T09:05:07.123Z", "options": { @@ -1560,278 +1128,152 @@ { "input": 999.95, "options": { - "site": "search-bar count", - "lang": "en" - }, - "output": "999.95" - }, - { - "input": 1234567.891, - "options": { - "site": "search-bar count", - "lang": "en" - }, - "output": "1,234,567.891" - }, - { - "input": -1234.5, - "options": { - "site": "search-bar count", - "lang": "en" - }, - "output": "-1,234.5" - }, - { - "input": 0, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "-0,5" - }, - { - "input": 1.25, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "1,3" - }, - { - "input": 12.345, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "12,3" - }, - { - "input": 999.95, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "1 000" - }, - { - "input": 1234567.891, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "1 234 567,9" - }, - { - "input": -1234.5, - "options": { - "site": "json-explorer size", - "lang": "fr", - "maximumFractionDigits": 1 - }, - "output": "-1 234,5" - }, - { - "input": 0, - "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 - }, - "output": "-0.5" - }, - { - "input": 1.25, - "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 - }, - "output": "1.3" - }, - { - "input": 12.345, - "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 - }, - "output": "12.3" - }, - { - "input": 999.95, - "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 + "site": "search-bar count", + "lang": "en" }, - "output": "1,000" + "output": "999.95" }, { "input": 1234567.891, "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 + "site": "search-bar count", + "lang": "en" }, - "output": "1,234,567.9" + "output": "1,234,567.891" }, { "input": -1234.5, "options": { - "site": "json-explorer size", - "lang": "en", - "maximumFractionDigits": 1 + "site": "search-bar count", + "lang": "en" }, "output": "-1,234.5" }, { "input": 0, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "0,00" + "output": "0" }, { "input": -0.5, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "-0,50" + "output": "-0,5" }, { "input": 1.25, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "1,25" + "output": "1,3" }, { "input": 12.345, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "12,345" + "output": "12,3" }, { "input": 999.95, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "999,95" + "output": "1 000" }, { "input": 1234567.891, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "1 234 567,891" + "output": "1 234 567,9" }, { "input": -1234.5, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "fr", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "-1 234,50" + "output": "-1 234,5" }, { "input": 0, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "0.00" + "output": "0" }, { "input": -0.5, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "-0.50" + "output": "-0.5" }, { "input": 1.25, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "1.25" + "output": "1.3" }, { "input": 12.345, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "12.345" + "output": "12.3" }, { "input": 999.95, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "999.95" + "output": "1,000" }, { "input": 1234567.891, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "1,234,567.891" + "output": "1,234,567.9" }, { "input": -1234.5, "options": { - "site": "settings-page hint", + "site": "json-explorer size", "lang": "en", - "minimumFractionDigits": 2 + "maximumFractionDigits": 1 }, - "output": "-1,234.50" + "output": "-1,234.5" }, { "input": 0, @@ -2211,314 +1653,6 @@ }, "output": "-1,234.5" }, - { - "input": 0, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "-0,5" - }, - { - "input": 1.25, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+1,25" - }, - { - "input": 12.345, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+12,35" - }, - { - "input": 999.95, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+999,95" - }, - { - "input": 1234567.891, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+1 234 567,89" - }, - { - "input": -1234.5, - "options": { - "site": "calc-format signed", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "-1 234,5" - }, - { - "input": 0, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "-0.5" - }, - { - "input": 1.25, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+1.25" - }, - { - "input": 12.345, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+12.35" - }, - { - "input": 999.95, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+999.95" - }, - { - "input": 1234567.891, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "+1,234,567.89" - }, - { - "input": -1234.5, - "options": { - "site": "calc-format signed", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "signDisplay": "exceptZero" - }, - "output": "-1,234.5" - }, - { - "input": 0, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "-0,5" - }, - { - "input": 1.25, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "1,25" - }, - { - "input": 12.345, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "12,35" - }, - { - "input": 999.95, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "999,95" - }, - { - "input": 1234567.891, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "1234567,89" - }, - { - "input": -1234.5, - "options": { - "site": "calc-format ungrouped", - "lang": "fr", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "-1234,5" - }, - { - "input": 0, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "0" - }, - { - "input": -0.5, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "-0.5" - }, - { - "input": 1.25, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "1.25" - }, - { - "input": 12.345, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "12.35" - }, - { - "input": 999.95, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "999.95" - }, - { - "input": 1234567.891, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "1234567.89" - }, - { - "input": -1234.5, - "options": { - "site": "calc-format ungrouped", - "lang": "en", - "minimumFractionDigits": 0, - "maximumFractionDigits": 2, - "useGrouping": false - }, - "output": "-1234.5" - }, { "input": [ "un", diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 46a017c03..000000000 --- a/package-lock.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "devnotes", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "devnotes", - "license": "GPL-3.0-only", - "dependencies": { - "prettier": "3.9.10" - } - }, - "node_modules/prettier": { - "version": "3.9.10", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", - "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", - "license": "MIT", - "bin": { - "prettier": "bin/prettier.cjs" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/prettier/prettier?sponsor=1" - } - } - } -} diff --git a/package.json b/package.json deleted file mode 100644 index e4aad995f..000000000 --- a/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "devnotes", - "description": "Build tools of DevNotes: Prettier and the release scripts", - "license": "GPL-3.0-only", - "repository": { - "type": "git", - "url": "git+https://github.com/vmillet-dev/devnotes-rs.git" - }, - "private": true, - "scripts": { - "test:scripts": "node --test scripts/release-notes.test.mjs scripts/release-preview.test.mjs scripts/version.test.mjs scripts/latest-json.test.mjs", - "lint": "prettier --check .", - "format": "prettier --write .", - "prettier": "node scripts/prettier.mjs" - }, - "dependencies": { - "prettier": "3.9.10" - } -} diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..2c7e9fb33 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +max_width = 110 +use_small_heuristics = "Max" +chain_width = 80 diff --git a/scripts/prettier.mjs b/scripts/prettier.mjs index 8fbf29b95..0bdcaea58 100644 --- a/scripts/prettier.mjs +++ b/scripts/prettier.mjs @@ -1,9 +1,11 @@ -// Copies Prettier, as `package.json` pins it, into crates/text/prettier: the formatter the -// application runs in QuickJS (`text::format`, plan D1). `npm run prettier` after a bump. -import { copyFileSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +// Copies Prettier into crates/text/prettier: the formatter the application runs in QuickJS +// (`text::format`, plan D1). `node scripts/prettier.mjs` after raising the version here. +import { execSync } from 'node:child_process'; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { join } from 'node:path'; -const FROM = join('node_modules', 'prettier'); +const VERSION = '3.9.10'; const TO = join('crates', 'text', 'prettier'); const PLUGINS = [ 'angular', @@ -17,11 +19,18 @@ const PLUGINS = [ 'yaml', ]; +// npm checks the archive against the registry's digest; nothing of it is run. +const folder = mkdtempSync(join(tmpdir(), 'prettier-')); +const run = (command) => execSync(command, { cwd: folder, encoding: 'utf8' }); +const archive = run(`npm pack prettier@${VERSION} --silent`).trim(); +run(`tar -xzf ${archive}`); + +const FROM = join(folder, 'package'); rmSync(TO, { recursive: true, force: true }); mkdirSync(TO, { recursive: true }); copyFileSync(join(FROM, 'standalone.js'), join(TO, 'standalone.js')); for (const plugin of PLUGINS) copyFileSync(join(FROM, 'plugins', `${plugin}.js`), join(TO, `${plugin}.js`)); copyFileSync(join(FROM, 'LICENSE'), join(TO, 'LICENSE')); +rmSync(folder, { recursive: true, force: true }); -const { version } = JSON.parse(readFileSync(join(FROM, 'package.json'), 'utf8')); -console.log(`Prettier ${version}: standalone and ${PLUGINS.length} plugins`); +console.log(`Prettier ${VERSION}: standalone and ${PLUGINS.length} plugins`); diff --git a/scripts/release-notes.mjs b/scripts/release-notes.mjs index 8b942a8a4..15cf1e8b3 100644 --- a/scripts/release-notes.mjs +++ b/scripts/release-notes.mjs @@ -292,8 +292,7 @@ export function splice(markdown, version, release) { const first = lines.findIndex((line) => line.startsWith('## ')); const head = (first === -1 ? lines : lines.slice(0, first)).join('\n').trimEnd(); const tail = first === -1 ? '' : lines.slice(first).join('\n').trimEnd(); - // The blank lines are this function's to place, and a file ending on two newlines is - // one Prettier would rewrite on the next lint. + // The blank lines are this function's to place, and a file ends on one newline. const body = release.trimEnd(); return `${head}\n\n${body}\n${tail ? `\n${tail}\n` : ''}`; } diff --git a/scripts/release-notes.test.mjs b/scripts/release-notes.test.mjs index 98b0535cf..6d1503e53 100644 --- a/scripts/release-notes.test.mjs +++ b/scripts/release-notes.test.mjs @@ -208,7 +208,7 @@ describe('groupEntries', () => { }); describe('renderSections', () => { - it('emits the exact bytes Prettier leaves alone', () => { + it('puts a blank line around each heading and ends on one newline', () => { const rendered = renderSections([ { heading: '✨ Added', items: ['a', 'b'] }, { heading: '🐛 Fixed', items: ['c'] }, diff --git a/.nvmrc b/website/.nvmrc similarity index 100% rename from .nvmrc rename to website/.nvmrc

Voir zqcopie et là