diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2e060c8..0f286c9 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -31,7 +31,7 @@ Ideally as a diff against one of the sample apps (`samples/compose-app`, `sample - DevConsole module(s) and version(s) affected (e.g. `devconsole:0.1.0-SNAPSHOT`, `devconsole-network-okhttp:0.1.0-SNAPSHOT`): -- Integration path: Maven Central coordinates, or built from source +- Integration path: JitPack coordinates, or built from source (`./gradlew publishToMavenLocal`)? - Android Gradle Plugin / Kotlin versions in the consuming project: - Device/emulator API level and manufacturer: diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml deleted file mode 100644 index 14ed89b..0000000 --- a/.github/workflows/dependency-review.yml +++ /dev/null @@ -1,16 +0,0 @@ -name: Dependency Review - -on: - pull_request: - -permissions: - contents: read - -jobs: - dependency-review: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/dependency-review-action@v5 - with: - fail-on-severity: high diff --git a/.github/workflows/publish-plugin.yml b/.github/workflows/publish-plugin.yml new file mode 100644 index 0000000..80c7092 --- /dev/null +++ b/.github/workflows/publish-plugin.yml @@ -0,0 +1,48 @@ +name: Publish Gradle plugin + +# A pushed `v*` tag is the release decision, so publishing follows it automatically. The guards +# below cover what a tag does not assert: that the version is the intended one and the suite passes. +on: + workflow_dispatch: + push: + tags: ['v*'] + +permissions: + contents: read + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '17' + # Pinned: this workflow holds the Portal credentials, so a moved tag upstream would run + # unreviewed code next to them. Bump deliberately. + - uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 + + # A tag that disagrees with the plugin's own version would publish the wrong coordinate, + # and the Portal will not let it be corrected afterwards. + - name: Tag matches the plugin version + if: startsWith(github.ref, 'refs/tags/') + run: | + tag_version="${GITHUB_REF_NAME#v}" + declared="$(sed -n 's/^version = "\(.*\)"$/\1/p' gradle-plugin/build.gradle.kts)" + if [ "$tag_version" != "$declared" ]; then + echo "Tag $GITHUB_REF_NAME implies $tag_version but gradle-plugin declares $declared." >&2 + exit 1 + fi + echo "Publishing io.github.devconsole-android $declared" + + - run: ./gradlew -p gradle-plugin test --stacktrace + + - name: Publish to the Gradle Plugin Portal + run: > + ./gradlew -p gradle-plugin publishPlugins --stacktrace + -Pgradle.publish.key="$GRADLE_PUBLISH_KEY" + -Pgradle.publish.secret="$GRADLE_PUBLISH_SECRET" + env: + GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} + GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 7b3a180..0000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,31 +0,0 @@ -name: Publish to Maven Central - -# Deliberately workflow_dispatch only: publishing to Central is effectively irreversible for a -# given coordinate + version, so it must be a conscious action, never a side effect of tagging a -# release or pushing to main. -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v7 - - uses: actions/setup-java@v5 - with: - distribution: temurin - java-version: '17' - - uses: gradle/actions/setup-gradle@v6 - - run: ./gradlew testDebugUnitTest test --stacktrace - # Uploads a validated deployment to the Central Portal but does NOT release it — the final - # "Publish" click happens in the central.sonatype.com UI so a human reviews the deployment. - - run: ./gradlew publishToMavenCentral --no-configuration-cache --stacktrace - env: - ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} - ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} - ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_IN_MEMORY_KEY }} - ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_IN_MEMORY_KEY_ID }} - ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_IN_MEMORY_KEY_PASSWORD }} diff --git a/CHANGELOG.md b/CHANGELOG.md index b25d59b..5e4e96b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,41 @@ before it can reach a release. (There was briefly a separate `sdk:plugin-api` mo third-party plugin framework; it was removed before ever shipping — see Removed, below — so it never joined this list.) +## 1.2.2 — 2026-08-17 + +### Added + +- **Search inside a capture got scoping, stepping, and a full-screen reader.** Every detail screen + already filtered and highlighted as you typed; network captures now add arrows that step through + hits one at a time with a running `3/17` counter, a **Search in** chip that picks which sections + to match (defaulting to the request and response bodies), and a choice of matching field names, + values, or both. Any body can be expanded full-screen with a Formatted/Raw switch, a line count, + and a copy button. Note that matching *names* only works where the body has names — JSON does, a + raw or XML body does not — which is why the default matches both. All of this is `internal`; no + public API was added. + +### Fixed + +- **Simple mode never actually hid the dashboard's metric strips.** The rule was written against + `.metrics-strip` while the markup has always emitted `.metric-strip`, so the selector matched + nothing and Simple mode showed the full metric row regardless. + +### Changed + +- **JitPack is now the only distribution channel for the library artifacts.** Maven Central + publishing is removed: no `publishToMavenCentral`, no GPG signing, and no "Publish to Maven + Central" workflow. Consumers add `maven { url = uri("https://jitpack.io") }` to + `dependencyResolutionManagement` and switch the group from `io.github.devconsole-android` to + **`com.github.devconsole-android.DevConsole`**, and prefix the version with `v` (`v1.2.2`) — + JitPack serves a build under its git ref name and releases are tagged `v*`, so the bare version + does not resolve. Artifact IDs are unchanged. + Releasing is now just pushing a tag — JitPack builds the ref on first request. +- **The Gradle plugin still comes from the Gradle Plugin Portal** as `io.github.devconsole-android`, + because the `plugins { }` DSL cannot resolve a plugin marker from JitPack. Its variant-policy + check now recognises both the JitPack group and the old Central group, so an existing host that + still names `io.github.devconsole-android:devconsole` keeps its release-build protection; the + coordinate the plugin auto-wires is the JitPack one. + ## 1.2.1 — 2026-08-17 Three default changes, aimed at the same complaint: a fresh integration showed a `127.0.0.1` URL @@ -171,7 +206,7 @@ signing key — including JitPack, which this release adds as a channel. - **JitPack as a secondary channel, for unreleased code.** Maven Central remains the supported one; JitPack covers trying a branch or an unmerged fix. Artifacts resolve under the group `com.github.devconsole-android.DevConsole` with the same artifact ids - (`com.github.devconsole-android.DevConsole:devconsole:1.1.1`), and any branch resolves as + (`com.github.devconsole-android.DevConsole:devconsole:v1.1.1` — the version is the git ref, so the `v` is part of it), and any branch resolves as `-SNAPSHOT` (a `/` in the branch name is written `~`). Two limits worth knowing: the Gradle plugin is **not** served there — it lives in an `includeBuild` and JitPack lists only the 31 library modules, so JitPack consumers name coordinates directly and give up the plugin's diff --git a/README.md b/README.md index 40e3f75..0b6389f 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ **An in-app debugger for Android, with a browser dashboard for when you want a bigger screen.** -[![Maven Central](https://img.shields.io/maven-central/v/io.github.devconsole-android/devconsole)](https://central.sonatype.com/artifact/io.github.devconsole-android/devconsole) +[![JitPack](https://jitpack.io/v/devconsole-android/DevConsole.svg)](https://jitpack.io/#devconsole-android/DevConsole) [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) [![minSdk 23](https://img.shields.io/badge/minSdk-23-3DDC84?logo=android&logoColor=white)](#compatibility) [![CI](https://github.com/devconsole-android/DevConsole/actions/workflows/verify.yml/badge.svg)](https://github.com/devconsole-android/DevConsole/actions/workflows/verify.yml) @@ -33,21 +33,34 @@ links no server code, and the Gradle plugin fails the build if the real runtime ## Quick start -**1. Add the plugin and two dependencies** to your app's `build.gradle.kts`: +**1. Add the JitPack repository** to your `settings.gradle.kts` — DevConsole is distributed through +[JitPack](https://jitpack.io/#devconsole-android/DevConsole): + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +**2. Add the plugin and two dependencies** to your app's `build.gradle.kts`: ```kotlin plugins { id("com.android.application") - id("io.github.devconsole-android") version "1.2.1" + id("io.github.devconsole-android") version "1.2.2" } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:1.2.1") - releaseImplementation("io.github.devconsole-android:devconsole-noop:1.2.1") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v1.2.2") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2") } ``` -**2. Open the inspector on the device.** The SDK auto-initializes on debuggable builds, so this +**3. Open the inspector on the device.** The SDK auto-initializes on debuggable builds, so this works right away from any button in your debug UI: ```kotlin @@ -70,7 +83,7 @@ SharedPreferences, SQLite, and files. Add one line to your HTTP client (see [Wire up your network stack](#wire-up-your-network-stack)) and network, WebSocket, and MQTT traffic show up too. -**3. Want a bigger screen? Start the browser dashboard.** Tap **Start server** on the inspector's +**4. Want a bigger screen? Start the browser dashboard.** Tap **Start server** on the inspector's **More** screen and it hands you a connect URL and a QR code. You can also do it from code. Either way your manifest needs `INTERNET`, which most apps already declare: @@ -88,7 +101,7 @@ If it fell back — or if you passed `BindingMode.LOOPBACK` to keep it off the n forward the port first: ```bash -adb forward tcp:8080 tcp:8080 # use the port from the DevConsole log line +adb forward tcp:8080 tcp:8080 # use the port from the loopback start's log line ``` Then open the **whole URL**. The `#code=` fragment is the credential, so a bare `http://host:port/` @@ -105,6 +118,7 @@ gets you nothing. |---|---| | **In-app inspector** | `DevConsole.open(context)` shows every inspector below as an on-device screen (included with `devconsole`), plus a QR code for pairing the browser. Opens by shake (adjustable intensity) or draggable floating button via the opt-in `DevConsoleConfig.openTriggers` flags. Its More screen can also start and stop the dashboard server. | | **Network inspector** | Every HTTP call with headers, bodies, and a DNS/TCP/TLS/send/wait/receive timing bar. Live-tails as traffic happens. | +| **Find in a capture** | Every detail screen has a find field that filters and highlights as you type. Network captures go further: step through hits with a counter and arrows, scope the search to the sections you choose, and match field names, values, or both. Any body can be expanded full-screen to read or copy. | | **WebSocket & MQTT inspectors** | Connection lifecycles and every frame, inbound and outbound. MQTT rides the Eclipse Paho adapter. | | **Mock rules** | Serve canned responses for matching requests (OkHttp), toggled from the dashboard, with deterministic priority matching. Wired by `installDevConsole` and editable out of the box. | | **Request composer** | Make the device issue ad-hoc HTTP requests from the dashboard. Off by default, host-allowlist confinable. | @@ -186,7 +200,9 @@ DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBind // Require the network — fails loudly instead of falling back, and surfaces the // ACCESS_LOCAL_NETWORK prompt on API 37+ devices: -DevConsoleConfig.default().withBrowserConfig(BrowserConfig(binding = BrowserBinding.LAN)) +DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LAN), +) ``` This is independent of the `bindingMode` you pass to `startBrowser` yourself; set both if you start @@ -308,14 +324,37 @@ you can replay it, clone it into the composer, or flag it into a bug report:

Network inspector in the browser dashboard, showing a captured request and response side by side

+### Search inside a capture + +Every detail screen — a call, a frame, a push, a log line, a crash — has a find field at the top. +Type, and it filters the sections down to what matched and highlights the hits in place, with a +count so you know whether the thing you're looking for is here at all. + +On **network captures** it goes further, because that's where you usually arrive with a specific +token in hand. Arrows step you through the hits one at a time with a running `3/17` counter, the +same motion as find-in-page, so you can hold an ID in your head and walk every place it appears. + +Those captures also let you aim the search. Tap the **Search in** chip and you can pick which +sections to look at — it starts on the request and response bodies, since that's where most real +questions live — and choose whether to match field names, values, or both. + +One thing worth knowing, because it's the kind of thing that costs an afternoon: matching *names* +only works where the body has names to match. JSON has them. A raw or XML body doesn't — it's +text all the way down — so a names-only search skips it entirely and quietly reports nothing. +That's why the default matches both, and why the sheet spells out what each mode will and won't +find. + +Body too dense to read in a card? Expand it full-screen. You get the whole viewport, a +Formatted/Raw switch, a line count, and a copy button that puts the body on the clipboard. + ### Set up Remote Config Add the adapter — it is not part of the `devconsole` umbrella, so that Firebase never lands on the classpath of an app that doesn't use it: ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:1.2.1") -releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:1.2.1") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:v1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:v1.2.2") ``` > These two artifacts first ship in `1.2.0`; earlier versions do not have them. @@ -365,8 +404,8 @@ anything sensitive in Remote Config. ## Artifacts -Group `io.github.devconsole-android`, one version for everything. There is deliberately no BOM, and -two coordinates cover a normal integration: +Group `com.github.devconsole-android.DevConsole`, one version for everything. There is deliberately +no BOM, and two coordinates cover a normal integration: | Coordinate | Scope | What it is | |---|---|---| @@ -385,41 +424,22 @@ Opt-in add-ons (each `-noop` twin is the matching `releaseImplementation`): | `devconsole-remote-config-firebase` | `devconsole-remote-config-firebase-noop` | Firebase Remote Config adapter (reflection-based; see [Remote Config](docs/REMOTE_CONFIG.md)) | Everything else (`devconsole-core`, `devconsole-storage-room`, and the rest) arrives transitively. -You never name those. Every module publishes sources, javadoc, and a signed POM. - -### JitPack (for unreleased code) - -Maven Central is the supported channel: signed, versioned, and what the Gradle plugin resolves. -[JitPack](https://jitpack.io/#devconsole-android/DevConsole) sits alongside it for one job, which is -trying a branch or an unreleased fix before it ships. Add the repository to your **settings** file, -not the module: - -```kotlin -dependencyResolutionManagement { - repositories { - mavenCentral() - maven { url = uri("https://jitpack.io") } - } -} -``` - -```kotlin -dependencies { - // Group is com.github.devconsole-android.DevConsole; artifact ids match the tables above. - debugImplementation("com.github.devconsole-android.DevConsole:devconsole:1.2.1") - releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:1.2.1") -} -``` - -A release tag works as the bare tag, as above. Any branch works as `-SNAPSHOT`, with `/` -written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT`. JitPack support starts at -**1.1.1**; earlier tags do not build there. Three things to know before you rely on it: - -- **The Gradle plugin is not on JitPack.** Only the 34 library artifacts are, so the - `plugins { id("io.github.devconsole-android") … }` block above does not apply. Name the - `debugImplementation` and `releaseImplementation` coordinates yourself. You also give up the - plugin's variant-policy check, which is the thing that keeps the full SDK out of release builds. -- **JitPack artifacts are unsigned.** Central's are signed; these are built on demand from a commit. +You never name those. Every module publishes sources, javadoc, and a POM. + +### Versions and unreleased code + +All 34 library artifacts come from [JitPack](https://jitpack.io/#devconsole-android/DevConsole), +which builds a ref on demand — so **the version is a git ref, spelled exactly as the ref is**. +Releases are tagged `v*`, which is why the coordinates above read `v1.2.2` and not `1.2.2`; the +bare form is a different ref and does not resolve. Any branch works as `-SNAPSHOT`, with +`/` written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT` — that is how you try an +unreleased fix before it ships. JitPack support starts at **v1.1.1**; earlier tags do not build +there. Two things to know: + +- **The Gradle plugin comes from the Gradle Plugin Portal, not JitPack**, because the `plugins { }` + DSL cannot resolve a plugin marker from JitPack. That is why the quick start adds JitPack for + dependencies only; `plugins { id("io.github.devconsole-android") version "…" }` resolves from the + Portal with no extra repository configuration. - **Snapshots move.** `-SNAPSHOT` follows the branch, so a build that worked can change under you. Pin a tag for anything you keep. diff --git a/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt b/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt index 9e1212c..8383315 100644 --- a/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt +++ b/build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt @@ -13,15 +13,10 @@ import org.gradle.kotlin.dsl.configure /** * Applies to every publishable SDK module. Wires the Vanniktech Maven Publish plugin, which picks * the right publication shape (`KotlinJvm` vs `AndroidSingleVariantLibrary`) from the plugins the - * module already applies, attaches sources plus a Dokka-generated javadoc jar, and targets the - * Sonatype Central Portal. + * module already applies and attaches sources plus a Dokka-generated javadoc jar. * - * `publishToMavenLocal` works with no credentials. A real `publishToMavenCentral` additionally - * needs the Central Portal user token (`mavenCentralUsername`/`mavenCentralPassword`) and the - * signing key (`signingInMemoryKey`/`signingInMemoryKeyId`/`signingInMemoryKeyPassword`) — via - * `ORG_GRADLE_PROJECT_`-prefixed env vars or `~/.gradle/gradle.properties`, never committed. - * Signing no-ops locally when no key is configured. See docs/MAVEN_PUBLISHING.md for the full - * release runbook. + * Distribution is JitPack, which builds a ref on demand and runs `publishToMavenLocal` — so no + * remote repository, credentials, or signing is configured here. See docs/PUBLISHING.md. */ class PublishingConventionPlugin : Plugin { override fun apply(target: Project) { @@ -48,10 +43,6 @@ class PublishingConventionPlugin : Plugin { // AndroidLibraryConventionPlugin on Android ones), so the javadoc jar packs that // module's own generated HTML instead of shipping empty. configureBasedOnAppliedPlugins(JavadocJar.Dokka("dokkaGeneratePublicationHtml")) - publishToMavenCentral() - // Unconditional signing fails with "no configured signatory" on any build without - // the key -- contributors and CI included. - if (hasSigningKey()) signAllPublications() pom { name.set("DevConsole ${target.name}") description.set("DevConsole SDK module: ${target.name}") @@ -79,12 +70,11 @@ class PublishingConventionPlugin : Plugin { } } - /** The key itself, not the id/password a machine may keep between releases. */ - private fun Project.hasSigningKey(): Boolean = !(findProperty("signingInMemoryKey") as? String).isNullOrBlank() - private companion object { + // The POM group. JitPack rewrites it to com.github.devconsole-android.DevConsole when it + // serves a build, so consumers name that group, not this one. const val MAVEN_GROUP = "io.github.devconsole-android" - const val SDK_VERSION = "1.2.1" + const val SDK_VERSION = "1.2.2" const val PROJECT_URL = "https://github.com/devconsole-android/DevConsole" } } diff --git a/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt b/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt index 0b35dfb..a48b702 100644 --- a/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt +++ b/build-logic/convention-quality/src/main/kotlin/io/devconsole/buildlogic/QualityConventionPlugin.kt @@ -26,6 +26,9 @@ class QualityConventionPlugin : Plugin { extensions.configure { buildUponDefaultConfig = true autoCorrect = false + // Supplements the defaults: exempts @Composable from the two size rules that + // Compose cannot satisfy without hurting the code. See the file for the reasoning. + config.setFrom(rootProject.file("config/detekt/detekt.yml")) // Modules had ~3000 pre-existing findings from before detekt was turned on. // The baseline freezes those as accepted debt so detekt only fails builds on // NEW findings introduced from here on; regenerate a module's baseline via diff --git a/build.gradle.kts b/build.gradle.kts index 68ea6c0..1c8ed85 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -4,9 +4,7 @@ plugins { alias(libs.plugins.kotlin.jvm) apply false alias(libs.plugins.binary.compatibility.validator) alias(libs.plugins.dokka) - // Loaded (not applied) here so every sdk module shares one classloader copy of the plugin — - // its MavenCentralBuildService is a shared build service, and per-module loading puts the - // service class in sibling classloaders that cannot exchange it. + // Loaded (not applied) here so every sdk module shares one classloader copy of the plugin. alias(libs.plugins.vanniktech.maven.publish) apply false } diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml new file mode 100644 index 0000000..8a43222 --- /dev/null +++ b/config/detekt/detekt.yml @@ -0,0 +1,15 @@ +complexity: + LongParameterList: + # A composable receives its state and callbacks as parameters; bundling them into a + # parameter object costs recomposition stability, so this threshold does not fit Compose. + ignoreAnnotated: ['Composable'] + LongMethod: + # A composable body is a layout tree. Splitting one purely to hit a line count + # fragments the UI description without making it clearer. + ignoreAnnotated: ['Composable'] + +style: + UnusedPrivateMember: + # @Preview functions are entry points for the IDE preview renderer; nothing in the source + # calls them, so the rule reports every one as dead. + ignoreAnnotated: ['Preview'] diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 4d02fa3..4f346eb 100644 --- a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md +++ b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md @@ -37,7 +37,7 @@ devConsole { protectedDependencyPaths.set(setOf(":sdk:full")) // default; override for a differently-pathed module failBuildOnUnsafeVariant.set(true) // default; false downgrades to a warning autoWireDependencies.set(true) // default; false to declare coordinates yourself - sdkVersion.set("1.2.1") // default; the plugin's own version + sdkVersion.set("v1.2.2") // default; the JitPack tag to resolve } ``` @@ -48,7 +48,7 @@ patterns with `.*` (as `(?i).*release` above does) so they match regardless of w prefixes onto the build type. **A variant that already names a DevConsole dependency is left alone.** Auto-wiring only fills a -gap, so an explicit `debugImplementation("io.github.devconsole-android:devconsole:...")` — or a +gap, so an explicit `debugImplementation("com.github.devconsole-android.DevConsole:devconsole:...")` — or a `project(":sdk:full")` dependency inside this repository — wins over anything the plugin would have added. @@ -140,11 +140,10 @@ only `INTERNET` (the sample's own) and the auto-generated dynamic-receiver permi ## Publication status -The artifacts are `io.github.devconsole-android:devconsole` (the full runtime, from `:sdk:full`) and -`io.github.devconsole-android:devconsole-noop` (from `:sdk:noop`); there is no BOM and never was a -`-full` coordinate. The publishing pipeline is wired — every publishable module produces a POM with -license/developer/SCM metadata, a sources jar, a javadoc jar, and a signature when a key is provided -— but nothing is on Maven Central yet: the version is a pre-1.0 `-SNAPSHOT`, and a release still -needs a signing key and a Central account (see [RELEASE_CHECKLIST.md](RELEASE_CHECKLIST.md)). Within -this repository the samples depend on the SDK from source via `project(":sdk:full")` / +The artifacts are `com.github.devconsole-android.DevConsole:devconsole` (the full runtime, from `:sdk:full`) and +`com.github.devconsole-android.DevConsole:devconsole-noop` (from `:sdk:noop`); there is no BOM and +never was a `-full` coordinate. They are served by [JitPack](https://jitpack.io/#devconsole-android/DevConsole), +which builds a ref on demand — every publishable module produces a POM with license/developer/SCM +metadata, a sources jar, and a javadoc jar (see [PUBLISHING.md](PUBLISHING.md)). Within this +repository the samples depend on the SDK from source via `project(":sdk:full")` / `project(":sdk:noop")`. diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index e652d62..abaea70 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -3,7 +3,20 @@ About five minutes, most of it waiting for Gradle. By the end you'll have the inspector opening on your device and the dashboard reachable from a browser. -1. Apply the production-safety plugin and split the dependency by variant. +1. Add the JitPack repository to `settings.gradle.kts` — that is where the library artifacts live + (the Gradle plugin comes from the Gradle Plugin Portal and needs nothing extra). + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { @@ -11,9 +24,9 @@ plugins { } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") - debugImplementation("io.github.devconsole-android:devconsole-ui-compose:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-compose:v") // optional, only for the launcher panel } devConsole { @@ -22,6 +35,10 @@ devConsole { } ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. @@ -31,7 +48,7 @@ release no-op counterpart and merges `DevConsoleActivity` into your manifest, so into your release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge +3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded server fails with an opaque socket error instead of a clear permission message: @@ -39,9 +56,9 @@ cover this module today; it is your responsibility to scope it to `debugImplemen ``` -3. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so +4. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so state/timeline/capture are ready without any `Application.onCreate` boilerplate. The browser - server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 4) and read + server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 5) and read the connect URL from the returned `StartResult.Started.access` (or the device's More screen — the logged URL deliberately omits the credential fragment). Initialize explicitly when you need to pass configuration (state providers, flags, open triggers): @@ -56,7 +73,7 @@ DevConsole.initialize( ) ``` -4. Drop in the optional Compose launcher panel, or build your own with `DevConsole.state()`. +5. Drop in the optional Compose launcher panel, or build your own with `DevConsole.state()`. `DevConsoleState.Running` carries no payload, so capture the endpoint from `onStart`'s own `StartResult` and pass it to the panel if you want the running address displayed: @@ -86,7 +103,7 @@ setContent { } ``` -5. Tap Start. The panel shows the bound address, something like `DevConsole server is running at +6. Tap Start. The panel shows the bound address, something like `DevConsole server is running at 192.168.0.15:8080`. Open that address in a browser, or use the connect URL from `StartResult.Started.access.connectUrl`. If the device isn't local, run `adb forward tcp:8080 tcp:8080` first. diff --git a/docs/GETTING_STARTED_XML_JAVA.md b/docs/GETTING_STARTED_XML_JAVA.md index a951bc7..a884021 100644 --- a/docs/GETTING_STARTED_XML_JAVA.md +++ b/docs/GETTING_STARTED_XML_JAVA.md @@ -4,10 +4,11 @@ DevConsole's public facade is a Kotlin `object`, but every method carries `@JvmS variants carry `@JvmOverloads`. From Java it reads like an ordinary utility class, and you never touch a coroutine: the `...Async` variants take a callback instead. -1. Apply the production-safety plugin and split the dependency by variant (same `build.gradle.kts` - shape as the Kotlin guide — see [GETTING_STARTED_XML_KOTLIN.md](GETTING_STARTED_XML_KOTLIN.md) - step 1). The two coordinates are `io.github.devconsole-android:devconsole` for debug and - `io.github.devconsole-android:devconsole-noop` for release; there is no BOM. +1. Add the JitPack repository, then apply the production-safety plugin and split the dependency by + variant (same `settings.gradle.kts` / `build.gradle.kts` shape as the Kotlin guide — see + [GETTING_STARTED_XML_KOTLIN.md](GETTING_STARTED_XML_KOTLIN.md) steps 1–2). + The two coordinates are `com.github.devconsole-android.DevConsole:devconsole` for debug and + `com.github.devconsole-android.DevConsole:devconsole-noop` for release; there is no BOM. 2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index 52d31b9..da1b083 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -3,7 +3,20 @@ No Compose required. The inspector ships as an Activity, and the launcher panel is a plain `View`, so a Views-based host gets exactly what a Compose one does. -1. Apply the production-safety plugin and split the dependency by variant. +1. Add the JitPack repository to `settings.gradle.kts` — that is where the library artifacts live + (the Gradle plugin comes from the Gradle Plugin Portal and needs nothing extra). + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Apply the production-safety plugin and split the dependency by variant. ```kotlin plugins { @@ -11,9 +24,9 @@ plugins { } dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") - debugImplementation("io.github.devconsole-android:devconsole-ui-views:") // optional, only for the launcher panel + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") + debugImplementation("com.github.devconsole-android.DevConsole:devconsole-ui-views:v") // optional, only for the launcher panel } devConsole { @@ -22,6 +35,10 @@ devConsole { } ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + There is no BOM. `devconsole` (the debug runtime) and `devconsole-noop` are the only two coordinates a normal integration names; everything else is `devconsole-`. @@ -30,7 +47,7 @@ release no-op counterpart, so a plain `implementation` dependency ships the laun release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge +3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded server fails with an opaque socket error instead of a clear permission message: @@ -38,7 +55,7 @@ module today; it is your responsibility to scope it to `debugImplementation` you ``` -3. Add the optional launcher view to a debug-only layout: +4. Add the optional launcher view to a debug-only layout: ```xml ``` -4. Initialize and bind the panel. On a debuggable build the SDK has already auto-initialized by +5. Initialize and bind the panel. On a debuggable build the SDK has already auto-initialized by this point, so `initialize` is only needed when you have configuration to pass (state providers, flags, open triggers). The panel starts out showing "not running" either way -- the browser server is never auto-started, so `onStart` below is what actually opens it. `DevConsoleState.Running` carries no @@ -78,7 +95,7 @@ panel.bind( ) ``` -5. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`) +6. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`) — then open that address (or the connect URL with its `#code=` fragment) in a browser on the same machine (or `adb forward tcp:8080 tcp:8080` first if the device isn't local). diff --git a/docs/MAVEN_PUBLISHING.md b/docs/MAVEN_PUBLISHING.md deleted file mode 100644 index f9695af..0000000 --- a/docs/MAVEN_PUBLISHING.md +++ /dev/null @@ -1,122 +0,0 @@ -# Publishing to Maven Central - -All 34 modules under `sdk/` are wired with the -[Vanniktech Maven Publish plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) -(via the `devconsole.publishing` convention), targeting the Sonatype **Central Portal** under the -group `io.github.devconsole-android`. Artifact IDs follow the mapping in -`PublishingConventionPlugin`: `:sdk:full` → `devconsole`, `:sdk:noop` → `devconsole-noop`, -everything else → `devconsole-`. Each publication carries sources, a Dokka-generated -javadoc jar, and a signed POM. - -`./gradlew publishToMavenLocal` verifies the whole pipeline locally with no credentials — signing -no-ops when no key is configured. A real publish needs the three things below. - -## 1. Verify the namespace (browser, one-time) - -`io.github.devconsole-android` is a GitHub-verified namespace tied to the `devconsole-android` -GitHub **organization** — no domain or DNS needed: - -1. Go to [central.sonatype.com](https://central.sonatype.com), sign in, and under **Namespaces** - add `io.github.devconsole-android`. The portal shows a short **verification key**. -2. Create a public repository named exactly that key under the org - (`github.com/devconsole-android/`), click **Verify Namespace**, then delete the - temporary repository. -3. Under your account icon → **View Account** → **Generate User Token**. The token is a - username/password pair — this is `mavenCentralUsername` / `mavenCentralPassword`. It is *not* - your Sonatype login password. - -## 2. Generate a signing key (terminal, one-time) - -Central requires every artifact to be GPG-signed. - -```bash -gpg --full-generate-key # RSA 4096, no expiration is fine for a personal signing key -gpg --list-secret-keys --keyid-format LONG # note the key ID (the part after rsa4096/) -gpg --keyserver keyserver.ubuntu.com --send-keys # publish so Central can verify it -gpg --export-secret-keys --armor > private-key.asc -``` - -- `signingInMemoryKey` = the full contents of `private-key.asc` (ASCII armor, newlines and all) -- `signingInMemoryKeyId` = the **last 8 hex characters** of the key ID -- `signingInMemoryKeyPassword` = the passphrase you set (blank if none) - -**Never commit `private-key.asc`** or paste it anywhere other than a GitHub Actions secret or -your local `~/.gradle/gradle.properties`. - -## 3. Bump the version and publish - -Central's release path does **not** accept `-SNAPSHOT` versions. Before the first real publish, -change `SDK_VERSION` in -`build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt` -(and `version` in `gradle-plugin/build.gradle.kts`) to a real version, e.g. `1.2.1`. - -**Locally:** - -```bash -ORG_GRADLE_PROJECT_mavenCentralUsername=... \ -ORG_GRADLE_PROJECT_mavenCentralPassword=... \ -ORG_GRADLE_PROJECT_signingInMemoryKey="$(cat private-key.asc)" \ -ORG_GRADLE_PROJECT_signingInMemoryKeyId=... \ -ORG_GRADLE_PROJECT_signingInMemoryKeyPassword=... \ -./gradlew publishToMavenCentral --no-configuration-cache -``` - -**Or via CI:** add the five values as repo secrets (Settings → Secrets and variables → Actions): -`MAVEN_CENTRAL_USERNAME`, `MAVEN_CENTRAL_PASSWORD`, `SIGNING_IN_MEMORY_KEY`, -`SIGNING_IN_MEMORY_KEY_ID`, `SIGNING_IN_MEMORY_KEY_PASSWORD` — then run the **Publish to Maven -Central** workflow from the Actions tab (`workflow_dispatch` only; it never fires automatically). - -Either way, `publishToMavenCentral` **uploads and validates** a deployment but does not release -it. Go to central.sonatype.com → **Deployments**, wait for validation to pass, review the -contents, and press **Publish**. That last click is the irreversible step: a released -coordinate + version can never be replaced or deleted. (To skip the manual click on future -releases, use `./gradlew publishAndReleaseToMavenCentral` instead.) - -Artifacts appear on `repo1.maven.org` within roughly 15–30 minutes of release, and on -search.maven.org within a few hours. - -## The Gradle plugin is published separately - -`io.github.devconsole-android` lives in the `gradle-plugin` included build and goes to the -**Gradle Plugin Portal**, not Central. One-time: create an account at -[plugins.gradle.org](https://plugins.gradle.org), generate an API key, and put -`gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`. Then: - -```bash -./gradlew -p gradle-plugin publishPlugins -``` - -First-time publication of a new plugin ID may sit in a short manual approval queue on the -Portal side. - -## Consuming a published release - -```kotlin -plugins { - id("io.github.devconsole-android") version "" -} -dependencies { - debugImplementation("io.github.devconsole-android:devconsole:") - releaseImplementation("io.github.devconsole-android:devconsole-noop:") -} -``` - -See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) for what -the plugin enforces about that split. - -## JitPack - -Nothing to run: JitPack builds a ref on first request and serves the result under the group -`com.github.devconsole-android.DevConsole`. `jitpack.yml` pins the JDK to 17 and otherwise leaves -JitPack's default command alone — that default already passes `-xtest -xlint --xsignMavenPublication`, so overriding it with an `install:` block would silently start running the -full unit suite on every consumer-triggered build. - -Because JitPack skips the signing *task* but Gradle still validates the publication, a publication -that registers `.asc` artifacts fails there with "artifact file does not exist". That is why -`PublishingConventionPlugin` calls `signAllPublications()` only when a key is configured — the same -condition that lets a contributor run `publishToMavenLocal` without one. - -Only the 34 library modules are served; `gradle-plugin` is an `includeBuild` and is not among them, -so JitPack consumers use plain coordinates rather than the plugin. Check a build at -`https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index a549117..1d9c22c 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -9,6 +9,39 @@ Validate each debug and release variant with `verifyDevConsoleProtectedArtifacts` before rollout. +## Upgrading from 1.2.1 + +**The library artifacts moved from Maven Central to JitPack.** No API changed; the coordinates did. + +1. Add JitPack to `settings.gradle.kts`: + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +2. Change the group on every DevConsole dependency from `io.github.devconsole-android` to + `com.github.devconsole-android.DevConsole`, and prefix the version with `v` — JitPack serves a + build under its git ref name, and releases are tagged `v*`. Artifact IDs are unchanged: + +```kotlin +debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v1.2.2") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2") +``` + +If you rely on the plugin's `autoWireDependencies` (the default), step 2 is done for you — you only +need step 1, because the coordinate the plugin declares now resolves from JitPack. + +The Gradle plugin itself is unaffected: it still comes from the Gradle Plugin Portal as +`io.github.devconsole-android`, and its variant-policy check still recognises the old +`io.github.devconsole-android` library group, so a module you have not migrated yet keeps its +release-build protection. + ## Upgrading from 1.2.0 Three defaults changed. No API was removed and nothing has to be rewritten — but two of these change diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md new file mode 100644 index 0000000..5ef1303 --- /dev/null +++ b/docs/PUBLISHING.md @@ -0,0 +1,106 @@ +# Publishing + +DevConsole is distributed through **[JitPack](https://jitpack.io/#devconsole-android/DevConsole)**. +The Gradle plugin is the one exception: it lives in the `gradle-plugin` included build and goes to +the **Gradle Plugin Portal**, because the `plugins { }` DSL cannot resolve a plugin marker from +JitPack. + +## The 34 library modules → JitPack + +All 34 modules under `sdk/` are wired with the +[Vanniktech Maven Publish plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) +(via the `devconsole.publishing` convention). Artifact IDs follow the mapping in +`PublishingConventionPlugin`: `:sdk:full` → `devconsole`, `:sdk:noop` → `devconsole-noop`, +everything else → `devconsole-`. Each publication carries sources, a Dokka-generated +javadoc jar, and a POM with license/developer/SCM metadata. + +**There is nothing to run to release.** JitPack builds a ref the first time someone asks for it and +serves the result under the group `com.github.devconsole-android.DevConsole`. Cutting a release is +just pushing a tag; the first consumer request triggers the build. + +`jitpack.yml` pins the JDK to 17 and otherwise leaves JitPack's default command alone — that +default already passes `-xtest -xlint -xsignMavenPublication`, so overriding it with an `install:` +block would silently start running the full unit suite on every consumer-triggered build. + +To verify the whole pipeline locally before tagging: + +```bash +./gradlew publishToMavenLocal +``` + +That produces the same artifacts JitPack does, with one difference that matters for a smoke test: +the POM group stays `io.github.devconsole-android`, because JitPack rewrites the group to +`com.github.devconsole-android.DevConsole` when it serves a build. So a local consumer test against +`mavenLocal()` must name `io.github.devconsole-android:devconsole:` — the +`com.github.…` coordinates in this document only resolve from jitpack.io. + +Check a real JitPack build at +`https://jitpack.io/api/builds/com.github.devconsole-android/DevConsole`. + +### Bumping the version + +`SDK_VERSION` in +`build-logic/convention-publishing/src/main/kotlin/io/devconsole/buildlogic/PublishingConventionPlugin.kt` +and `version` in `gradle-plugin/build.gradle.kts` are kept in step. JitPack derives the consumer- +facing version from the tag or branch rather than from `SDK_VERSION`, but the two should match so +`publishToMavenLocal` output and the tag agree. + +## The Gradle plugin → Gradle Plugin Portal + +One-time: create an account at [plugins.gradle.org](https://plugins.gradle.org) and generate an API +key. Then either publish from CI (preferred) or locally. + +**From CI.** The **Publish Gradle plugin** workflow runs on a `v*` tag and on `workflow_dispatch`. +Pushing the tag *is* the release decision, so it publishes without further confirmation. Before it +does, it checks the tag agrees with `gradle-plugin`'s declared `version` and runs the plugin's test +suite — a tag asserts the intent to release, not that the version string is right. + +One-time setup: add the repo secrets `GRADLE_PUBLISH_KEY` and `GRADLE_PUBLISH_SECRET` (Settings → +Secrets and variables → Actions). + +Because the publish is irreversible, two things are worth knowing: the version guard fails the run +rather than publishing a mismatched coordinate, and re-pushing an already-published version is +rejected by the Portal, so a deleted-and-recreated tag will fail rather than overwrite. + +**Locally.** Put `gradle.publish.key` / `gradle.publish.secret` in `~/.gradle/gradle.properties`: + +```bash +./gradlew -p gradle-plugin publishPlugins +``` + +First-time publication of a new plugin ID may sit in a short manual approval queue on the Portal +side. + +## Consuming a release + +Add JitPack to the **settings** file, not the module: + +```kotlin +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} +``` + +```kotlin +plugins { + id("io.github.devconsole-android") version "" +} +dependencies { + debugImplementation("com.github.devconsole-android.DevConsole:devconsole:v") + releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-noop:v") +} +``` + +`` is the git ref verbatim, so for a release it is the **`v`-prefixed tag** (`v1.2.2`) — +JitPack does not strip the prefix, and the bare form 404s. Any branch works as +`-SNAPSHOT`, with `/` written as `~`, so a `feature/x` branch is `feature~x-SNAPSHOT`. +Note the Gradle plugin is the exception: it comes from the Portal, where its version is the bare +`1.2.2`. JitPack support starts at **v1.1.1**; earlier +tags do not build there. + +See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) for what the +plugin enforces about the debug/release split. diff --git a/docs/README.md b/docs/README.md index 94c7a7d..a3dc393 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,4 +55,4 @@ read one page here, make it the threat model, especially before you put the dash **Contributing / releasing** - [Migration guide](MIGRATION.md) - [Release checklist](RELEASE_CHECKLIST.md) -- [Publishing to Maven Central](MAVEN_PUBLISHING.md) +- [Publishing](PUBLISHING.md) diff --git a/docs/RELEASE_CHECKLIST.md b/docs/RELEASE_CHECKLIST.md index 36c94c6..048f775 100644 --- a/docs/RELEASE_CHECKLIST.md +++ b/docs/RELEASE_CHECKLIST.md @@ -3,8 +3,9 @@ - [ ] Version, changelog, and public API change assessment are complete. - [ ] Unit, server-contract, sample debug/release, and protected-artifact checks pass. - [ ] Security suites cover redaction, CSRF/origin, session-code exchange throttling, and authorization. -- [ ] Dependency lock/SBOM and provenance are attached to the signed release artifacts. +- [ ] Dependency lock/SBOM and provenance are attached to the release artifacts. - [ ] No critical or high unresolved vulnerability remains. - [ ] Documentation and samples are validated from a clean checkout. -- [ ] Maven Central publish (see [MAVEN_PUBLISHING.md](MAVEN_PUBLISHING.md)), consumer smoke test, - signed tag, and release notes are complete. +- [ ] `./gradlew publishToMavenLocal` passes from a clean checkout (this is what JitPack runs). +- [ ] Signed tag pushed, JitPack build green for that tag (see [PUBLISHING.md](PUBLISHING.md)), + consumer smoke test and release notes are complete. diff --git a/docs/REMOTE_CONFIG.md b/docs/REMOTE_CONFIG.md index 72e3fe2..fec36b8 100644 --- a/docs/REMOTE_CONFIG.md +++ b/docs/REMOTE_CONFIG.md @@ -25,10 +25,14 @@ Cloud Messaging. Add the adapter coordinate yourself; it is deliberately not re- `devconsole` umbrella. ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-remote-config-firebase:") -releaseImplementation("io.github.devconsole-android:devconsole-remote-config-firebase-noop:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase:v") +releaseImplementation("com.github.devconsole-android.DevConsole:devconsole-remote-config-firebase-noop:v") ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + A provider constructed later — through DI, or after a first fetch completes — can register itself: ```kotlin diff --git a/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md new file mode 100644 index 0000000..022d02e --- /dev/null +++ b/docs/superpowers/plans/2026-08-17-default-lan-and-mocks-plan.md @@ -0,0 +1,399 @@ +# Default LAN and Mock Behavior Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make LAN the default for both existing server-start APIs, preserve explicit loopback opt-out behavior, and lock the full/noop mock defaults with regression tests. + +**Architecture:** Change the defaults at the existing public constructor boundaries rather than adding a new policy field. The full runtime already constructs its `MockEngine` enabled and the noop runtime constructs it disabled; tests will make those contracts explicit. Runtime permission checks, capture-category gating, and explicit binding branches remain unchanged. + +**Tech Stack:** Kotlin/JVM and Kotlin Android libraries, JUnit 4, Robolectric, Gradle, Markdown documentation. + +--- + +### Task 1: Lock the public and lower-level LAN defaults with failing tests + +**Files:** +- Modify: `sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt` +- Modify: `sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt` +- Create: `sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt` + +- [ ] **Step 1: Change the focused API default assertion** + +In `FocusedConfigurationTest`, rename the test to `focused policies use persistent sessions and LAN defaults` and change the binding assertion to: + +```kotlin +assertEquals(BrowserBinding.LAN, browser.binding) +``` + +- [ ] **Step 2: Add the public `StartRequest` default assertion** + +In `DevConsoleContractTest`, add this test next to the existing `StartRequest` validation test: + +```kotlin +@Test +fun `default start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) +} +``` + +The file already lives in `io.devconsole.api`, so no new imports are needed. + +- [ ] **Step 3: Add the server-api default assertion** + +Create `StartRequestDefaultsTest.kt` with: + +```kotlin +package io.devconsole.server.api + +import org.junit.Assert.assertEquals +import org.junit.Test + +class StartRequestDefaultsTest { + @Test + fun `default server start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) + } +} +``` + +- [ ] **Step 4: Run the focused tests and verify they fail for the old defaults** + +Run: + +```bash +./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest +./gradlew :sdk:server-api:testDebugUnitTest --tests io.devconsole.server.api.StartRequestDefaultsTest +``` + +Expected: the new/changed assertions fail because the current defaults are `LOOPBACK`. + +- [ ] **Step 5: Commit the failing contract tests** + +```bash +git add sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt \ + sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt \ + sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt +git commit -m "test: define LAN binding defaults" +``` + +### Task 2: Lock full-runtime, noop, and mock-engine behavior with failing tests + +**Files:** +- Modify: `sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt` +- Modify: `sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt` +- Modify: `sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt` +- Modify: `sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt` + +- [ ] **Step 1: Add the direct mock-engine default test** + +In `MockEngineTest`, add: + +```kotlin +@Test +fun `mock engine is enabled by default`() { + assertTrue(MockEngine(emptyList()).isEnabled()) +} +``` + +Use the file’s existing `assertTrue` import. + +- [ ] **Step 2: Update the full facade’s default-start expectation and assert the full mock default** + +In `FullFacadeTest`’s `FR-BUILD-002 full facade initializes the enabled runtime` test, keep the existing `StartRequest()` call, change: + +```kotlin +assertEquals(BindingMode.LAN, started.endpoint.bindingMode) +``` + +and add this assertion after initialization, before starting the server: + +```kotlin +assertTrue(provider.mockEngine().isEnabled()) +``` + +- [ ] **Step 3: Change the More-screen default test into a LAN assertion and add an explicit loopback test** + +In `PlatformFacadeProviderMoreScreenBindingTest`: + +1. Update the class KDoc so it says the default config binds LAN and loopback is the explicit secondary choice. +2. Rename `More screen start still binds loopback under the default config` to `More screen start binds LAN under the default config` and change its assertion to: + +```kotlin +assertEquals(BindingMode.LAN, provider.startFromMoreScreen().bindingMode) +``` + +3. Add this explicit opt-out test: + +```kotlin +@Test +fun `More screen start binds loopback when the host explicitly configures loopback`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK, portRange = 8640..8659), + ), + ) + + assertEquals(BindingMode.LOOPBACK, provider.startFromMoreScreen().bindingMode) + + provider.stop(StopReason.UserRequested) + } +``` + +- [ ] **Step 4: Assert noop mocks remain disabled** + +In `NoopFacadeTest`, add to the existing disabled-facade test or create a separate test with the same initialization setup: + +```kotlin +assertTrue(!DevConsole.mockEngine().isEnabled()) +``` + +- [ ] **Step 5: Run the focused runtime tests and verify they fail only on the changed default expectations** + +Run: + +```bash +./gradlew :sdk:mocks:test --tests io.devconsole.mocks.MockEngineTest \ + :sdk:full:testDebugUnitTest --tests io.devconsole.FullFacadeTest --tests io.devconsole.PlatformFacadeProviderMoreScreenBindingTest \ + :sdk:noop:testDebugUnitTest --tests io.devconsole.NoopFacadeTest +``` + +Expected: the full/default LAN assertions and the noop/mock assertions identify the old behavior; existing explicit loopback/LAN tests continue to pass. + +- [ ] **Step 6: Commit the runtime contract tests** + +```bash +git add sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt \ + sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt \ + sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt \ + sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt +git commit -m "test: cover full and noop default behavior" +``` + +### Task 3: Implement LAN defaults and update runtime KDoc + +**Files:** +- Modify: `sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt` +- Modify: `sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt` +- Modify: `sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt` +- Modify: `sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt` +- Modify: `sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt` + +- [ ] **Step 1: Make `BrowserConfig` default to LAN** + +In `FocusedPolicies.kt`, change: + +```kotlin +val binding: BrowserBinding = BrowserBinding.LOOPBACK, +``` + +to: + +```kotlin +val binding: BrowserBinding = BrowserBinding.LAN, +``` + +Rewrite the surrounding KDoc so it says LAN is the default for the More-screen start and loopback is the explicit safer choice; retain the warning that the dashboard uses plaintext HTTP and cite `docs/THREAT_MODEL.md`. + +- [ ] **Step 2: Make public `StartRequest` default to LAN** + +In `sdk/api/.../StartRequest.kt`, change: + +```kotlin +val bindingMode: BindingMode = BindingMode.LOOPBACK, +``` + +to: + +```kotlin +val bindingMode: BindingMode = BindingMode.LAN, +``` + +Update the enum and data-class KDoc to say programmatic starts default to LAN, while callers can explicitly pass `BindingMode.LOOPBACK`; remove claims that loopback is the default. + +- [ ] **Step 3: Align `sdk:server-api`’s lower-level default** + +In `sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt`, change the lower-level `StartRequest` constructor default to: + +```kotlin +val bindingMode: BindingMode = BindingMode.LAN, +``` + +Do not change `SessionCodeAuthority`’s placeholder `lastEndpoint`, which is an internal pre-start URL fallback rather than a server-start binding default. + +- [ ] **Step 4: Update facade and provider KDoc** + +In `sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt`, change the `startBrowser` documentation to describe `StartRequest()` as LAN by default, and show explicit `BindingMode.LOOPBACK` as the safer choice for trusted USB/ADB-only use. + +In `sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt`, update `configuredStartRequest()`’s comment so it no longer says the default remains loopback. Keep the mapping of explicit `BrowserBinding.LOOPBACK` and `BrowserBinding.LAN` unchanged. + +- [ ] **Step 5: Run the focused tests and compile the changed modules** + +Run: + +```bash +./gradlew :sdk:api:test --tests io.devconsole.api.FocusedConfigurationTest --tests io.devconsole.api.DevConsoleContractTest \ + :sdk:server-api:testDebugUnitTest --tests io.devconsole.server.api.StartRequestDefaultsTest \ + :sdk:mocks:test --tests io.devconsole.mocks.MockEngineTest \ + :sdk:full:testDebugUnitTest --tests io.devconsole.FullFacadeTest --tests io.devconsole.PlatformFacadeProviderMoreScreenBindingTest \ + :sdk:noop:testDebugUnitTest --tests io.devconsole.NoopFacadeTest +``` + +Expected: all focused tests pass, including the explicit loopback and noop-disabled assertions. + +- [ ] **Step 6: Commit the implementation and KDoc changes** + +```bash +git add sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt \ + sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt \ + sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt \ + sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt \ + sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +git commit -m "feat: default dashboard binding to LAN" +``` + +### Task 4: Refresh user-facing LAN guidance + +**Files:** +- Modify: `README.md` +- Modify: `docs/THREAT_MODEL.md` +- Modify: `docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md` + +- [ ] **Step 1: Update README setup examples** + +Replace the quick-start programmatic example with the default call and an explicit loopback alternative: + +```kotlin +val result = DevConsole.startBrowser() // LAN by default +// For USB/ADB-only access instead: +val loopbackResult = DevConsole.startBrowser( + StartRequest(bindingMode = BindingMode.LOOPBACK), +) +``` + +Replace the More-screen paragraph and sample with: + +```markdown +That button binds **LAN** by default, so its QR code is reachable from another device on the same +network. For the safer USB/ADB-only mode, configure loopback explicitly; the button issues no +`StartRequest` of its own: +``` + +```kotlin +DevConsoleConfig.default().withBrowserConfig( + BrowserConfig(binding = BrowserBinding.LOOPBACK), +) +``` + +Update the regular code sample to call `DevConsole.startBrowser(StartRequest())`, annotate it as +the LAN default, and retain the existing explicit `StartRequest(bindingMode = BindingMode.LOOPBACK)` +snippet as the loopback opt-out. + +Change the connect-method bullets to identify LAN as the default and loopback as the explicit secondary option. Keep the existing warning that LAN is plaintext and never silently falls back to loopback. + +Use: + +```markdown +- **LAN (default):** open the URL from another device on the same network. Read + [the threat model](docs/THREAT_MODEL.md) first because the dashboard speaks plaintext HTTP. +- **Loopback (explicit):** run `adb forward tcp: tcp:`, then open the connect URL. +``` + +- [ ] **Step 2: Update README security language** + +Replace the security-model introduction and first network bullet with: + +```markdown +DevConsole deliberately exposes your app's internals to a browser. LAN is the default to make +cross-device debugging work immediately, while loopback remains the safer explicit choice on +untrusted or shared networks. + +- **The dashboard speaks plaintext HTTP.** There is no TLS. In LAN mode, anyone who can watch your + network packets can read everything it shows: headers, tokens, bodies, exports. Use + `BindingMode.LOOPBACK` with `adb forward` when the network is not trusted. +``` + +- [ ] **Step 3: Update the threat model** + +In the Safe defaults section, explain: + +```kotlin +DevConsole.startBrowser(StartRequest()) // LAN default +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) // explicit safer mode +``` + +Precede the examples with: “LAN is the primary default for both existing start entry points so +cross-device debugging works without extra configuration. Use the explicit loopback form on an +untrusted/shared network.” Change the More-screen explanation to say `BrowserConfig()` defaults to +LAN and that `BrowserConfig(binding = BrowserBinding.LOOPBACK)` is the explicit secondary choice. +Preserve all threat warnings, permission behavior, and the statement that the two entry points +remain independently configurable. + +- [ ] **Step 4: Update LAN troubleshooting wording** + +Rename the loopback section’s posture from “safer default” to “explicit loopback / ADB mode” and leave its command and `adb forward` instructions intact. + +- [ ] **Step 5: Search for stale default claims and commit documentation** + +Run: + +```bash +rg -n "loopback.*default|default.*loopback|LAN mode is always an explicit opt-in|LAN.*explicit opt-in|BrowserBinding\.LOOPBACK.*default|StartRequest\(\).*loopback" README.md docs sdk -g '*.md' -g '*.kt' +``` + +The remaining matches must be explicit loopback examples, fallback/error guidance, or the internal session-code placeholder—not claims about the public server-start defaults. + +Then commit: + +```bash +git add README.md docs/THREAT_MODEL.md docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +git commit -m "docs: describe LAN as the default binding" +``` + +### Task 5: Run the complete verification set and review the final diff + +**Files:** +- Test: `sdk/api`, `sdk/server-api`, `sdk/mocks`, `sdk/full`, `sdk/noop` +- Review: all files changed by Tasks 1–4 + +- [ ] **Step 1: Run all affected unit tests** + +```bash +./gradlew :sdk:api:test :sdk:server-api:test :sdk:mocks:test \ + :sdk:full:testDebugUnitTest :sdk:noop:testDebugUnitTest +``` + +Expected: every task completes successfully with no failed tests. + +- [ ] **Step 2: Compile the public/full/noop artifacts** + +```bash +./gradlew :sdk:api:compileKotlin :sdk:server-api:compileDebugKotlin \ + :sdk:full:compileDebugKotlin :sdk:noop:compileDebugKotlin +``` + +Expected: all compile tasks pass without API or Kotlin errors. + +- [ ] **Step 3: Check formatting and inspect the diff** + +```bash +git diff --check HEAD~4..HEAD +git status --short +git log --oneline -6 +``` + +Review that only the approved design spec, default values, tests, KDoc, and LAN guidance changed; verify noop construction remains `MockEngine(emptyList(), enabled = false)` and no permission/fallback logic was altered. + +- [ ] **Step 4: Run the repository check task** + +```bash +./gradlew check +``` + +Expected: the repository-wide quality and test checks pass. If the check task reports only an expected API-dump or documentation artifact difference, inspect it and include the generated tracked artifact only if the build explicitly requires it. + +- [ ] **Step 5: Report completion with evidence** + +Summarize the public defaults, explicit loopback override, preserved noop safety, documentation updates, and the exact Gradle commands that passed. Link the key changed files and mention any environment-specific test limitation rather than claiming unverified success. diff --git a/docs/superpowers/plans/2026-08-17-network-detail-search.md b/docs/superpowers/plans/2026-08-17-network-detail-search.md new file mode 100644 index 0000000..ce21c1b --- /dev/null +++ b/docs/superpowers/plans/2026-08-17-network-detail-search.md @@ -0,0 +1,262 @@ +# Network Detail Search Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Add scoped, multi-select request/response search to the Android Compose Network detail screen with key/value modes, exact highlighting, match navigation, and preserved formatted bodies. + +**Architecture:** Keep query, scope, mode, and current-match state in `InspectorObserveDetailScreen`. Add a pure candidate/match model for deterministic matching and document ordering. Pass matches as rendering metadata so existing `Formattable`, JSON-tree, raw, code, and key/value body types remain intact. + +**Tech Stack:** Kotlin, Jetpack Compose Material 3, existing DevConsole Compose primitives, JUnit4. + +--- + +### Task 1: Add the pure search model and red tests + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt` +- Create: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt` + +- [ ] **Step 1: Define the search API and tests first** + +Create `InspectorSearchField`, `InspectorSearchMode`, `InspectorDetailSearchSection`, `InspectorSearchCandidate`, and `InspectorDetailSearchMatch`. The matcher API must accept candidates, a query, a selected-section key set, and a mode, then return ordered matches with zero-based `ordinal`, `start`, and exclusive `end` offsets. + +Write tests covering: + +```kotlin +@Test +fun `keys mode matches keys but not values and keeps exact ranges`() { + val candidates = listOf( + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.KEY, "Content-Type"), + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.VALUE, "application/json"), + ) + + val matches = searchInspectorCandidates(candidates, "content", setOf("reqh"), InspectorSearchMode.KEYS) + + assertEquals(1, matches.size) + assertEquals(0, matches.single().start) + assertEquals(7, matches.single().endExclusive) +} + +@Test +fun `multi section matching follows candidate order and values mode`() { + val candidates = listOf( + InspectorSearchCandidate("req", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("general", "row:0", InspectorSearchField.VALUE, "userId: 1"), + ) + + val matches = searchInspectorCandidates( + candidates, + "userid", + setOf("req", "res"), + InspectorSearchMode.VALUES, + ) + + assertEquals(listOf("req", "res"), matches.map { it.sectionKey }) + assertEquals(listOf(0, 1), matches.map { it.ordinal }) +} + +@Test +fun `previous and next navigation wrap around`() { + assertEquals(0, nextInspectorMatchIndex(current = 2, total = 3)) + assertEquals(2, previousInspectorMatchIndex(current = 0, total = 3)) +} +``` + +- [ ] **Step 2: Run the focused test and verify it fails for the missing API** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +Expected: compilation/test failure because the matcher and navigation helpers do not exist yet. + +- [ ] **Step 3: Implement the minimal pure matcher** + +Implement case-insensitive, non-overlapping substring ranges using `regionMatches`, filter by selected section and field mode, assign ordinals after filtering, and return an empty list for blank queries. Add wrap-around helpers that return `0` for next/`total - 1` for previous when the list is non-empty. + +- [ ] **Step 4: Re-run the focused test and verify it passes** + +Run the same Gradle command. Expected: all focused tests pass. + +- [ ] **Step 5: Commit the pure search model** + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +git commit -m "feat: add network detail search matcher" +``` + +### Task 2: Build candidates from detail bodies and integrate Network-only search state + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt` +- Modify: `sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt` + +- [ ] **Step 1: Add failing candidate-extraction tests** + +Test that headers produce `row:` key/value candidates, code/raw lines produce `line:` value candidates, and nested JSON produces a key candidate for an object property plus a scalar-value candidate with the property path and ancestor paths. Test that a formatted body remains an `InspectorDetailSectionBody.Formattable` body after search resolution. + +- [ ] **Step 2: Run the focused test and verify the new extraction assertions fail** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +- [ ] **Step 3: Implement body candidate extraction** + +Traverse `KeyValues`, `Code`, and `Formattable` bodies in display order. For JSON, emit quoted object keys and rendered scalar values while retaining each row path and ancestor paths. Treat XML/plain raw lines as value candidates. Add the four network scope options and a `searchOptions` field to `ObserveDetailContent`; set it only in `netDetailContent` with all four sections selected and `KEYS` as the default mode. + +- [ ] **Step 4: Split Network search resolution from legacy non-Network resolution** + +Keep existing search behavior for other capture detail kinds. For Network detail, resolve only configured sections, keep all original rows/lines, attach ordered `InspectorDetailSearchMatch` lists, auto-expand matching sections, and never replace `Formattable` with `Code`. Excluded sections must retain their normal display and must not show `no match` metadata. + +- [ ] **Step 5: Wire saveable state and navigation** + +Add saveable selected-section keys, match mode, current-match index, and bottom-sheet visibility to `InspectorObserveDetailScreen` when `content.searchOptions` is present. Reset the current index when query, scope, or mode changes. Use `nextInspectorMatchIndex` and `previousInspectorMatchIndex` for wrap-around navigation. Keep the existing legacy query path for content without Network search options. + +- [ ] **Step 6: Re-run tests and commit the state/resolution integration** + +Run the focused test command and then: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit the verified integration: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt +git commit -m "feat: scope network detail search" +``` + +### Task 3: Add the options bottom sheet and search navigation controls + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` + +- [ ] **Step 1: Add the bottom-sheet composable** + +Use `ModalBottomSheet` with a draft `Set` and draft `InspectorSearchMode`. Render four 48dp-minimum checkbox rows, Select all/Clear all actions, three mutually exclusive mode chips, and Cancel/Apply actions. Disable Apply when no section is selected. Apply must return both draft values; Cancel must only dismiss. + +- [ ] **Step 2: Add search-field controls** + +Keep the existing search input. For Network detail, add 48dp previous and next icon buttons, disabled when no matches, plus a scope filter chip that opens the bottom sheet. Show `current/total`, `0/0` for no matches, and a scope summary such as `All request + response`, `Response body`, or `2 sections`. Use rotated existing chevron glyphs for arrows so no icon dependency is added. + +- [ ] **Step 3: Render and connect the sheet** + +Open the sheet from the scope chip, pass the current active configuration, and on Apply update the saveable state, reset the current match, and dismiss the sheet. Add accessible labels/content descriptions for scope, previous, next, checkboxes, modes, Cancel, and Apply. + +- [ ] **Step 4: Build and run the existing unit suite** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit the verified controls: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +git commit -m "feat: add network search controls" +``` + +### Task 4: Add exact highlighting and preserve formatted bodies + +**Files:** +- Create: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt` + +- [ ] **Step 1: Add failing rendering-model tests** + +Test that search metadata for a formatted JSON response remains `InspectorDetailSectionBody.Formattable`, that a key match targets the JSON row key text, and that a value match targets the scalar text with exact offsets. + +- [ ] **Step 2: Run the focused test and verify it fails against the current flat-search behavior** + +Run: + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --tests io.devconsole.ui.compose.InspectorDetailSearchTest --no-daemon +``` + +- [ ] **Step 3: Implement reusable exact-range highlighting** + +Add `InspectorSearchHighlight(start, endExclusive, active)` and a monospace `AnnotatedString` renderer that applies a signal-soft background to inactive matches and a stronger signal background to the active match. Clamp invalid ranges and leave text unchanged when there are no highlights. + +- [ ] **Step 4: Apply highlights without changing body shape** + +Pass match metadata and current ordinal into key/value, code, and formattable renderers. Highlight key and value spans separately. Extend `JsonTreeRow` with key/value search highlight ranges, preserve existing mock-diff row highlighting, and apply search highlights to JSON tree key/value text. Search-driven matches must not set the old row-only `highlighted` flag or replace a Formattable body with Code. + +- [ ] **Step 5: Keep raw/XML/JSON views usable** + +For XML and raw lines, decorate the existing code lines. For JSON formatted mode, decorate the existing tree rows. Keep the Raw/Formatted toggle and its selected state intact while the query is active; the response must never collapse to a one-line or flat representation as a side effect of searching. + +- [ ] **Step 6: Re-run the full unit suite and commit the rendering fix** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest --no-daemon +``` + +Commit after the output reports success: + +```bash +git add sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +git commit -m "fix: preserve formatted network search results" +``` + +### Task 5: Bring the active match into view and verify the Android UI + +**Files:** +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt` +- Modify: `sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailPreviews.kt` + +- [ ] **Step 1: Add target scrolling** + +Use `LazyListState` for code and formatted body lists. When the active ordinal changes, locate its `line:` or JSON path target and animate that row into view. Use `BringIntoViewRequester` for key/value rows in the outer detail scroll. Force-expand JSON ancestor paths for selected matches while retaining user expansion overrides otherwise. + +- [ ] **Step 2: Add realistic preview data** + +Update the detail preview with nested request/response JSON and repeated matches so the formatted tree, exact highlights, active match, and navigation controls are visible in previews. + +- [ ] **Step 3: Run targeted unit/build verification** + +```bash +./gradlew :sdk:ui-compose:testDebugUnitTest :samples:compose-app:assembleDebug --no-daemon +``` + +Expected: BUILD SUCCESSFUL and zero failed tests. + +- [ ] **Step 4: Install and verify the sample on the running emulator** + +Install the debug APK, open the Network tab and a transaction detail, then verify: + +- default scope is all four request/response sections; +- bottom sheet supports selecting multiple sections and cancelling without changes; +- Keys is selected by default and Values/Keys + values change matches; +- previous/next update the current match and scroll to it; +- exact text is highlighted; +- General/Timing/Redactions never contribute matches; +- formatted JSON remains a tree after searching. + +- [ ] **Step 5: Inspect the final diff and commit verification-safe changes** + +```bash +git status --short +git diff --check +git diff --stat +``` + +Commit any final source/preview fixes only after the targeted build and tests pass. diff --git a/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md b/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md new file mode 100644 index 0000000..a20e5d5 --- /dev/null +++ b/docs/superpowers/specs/2026-08-17-default-lan-and-mocks-design.md @@ -0,0 +1,33 @@ +# Default LAN and Mock Behavior + +## Summary + +Make LAN the primary server-binding default across the library while retaining loopback as an explicit secondary choice. Preserve the full/debug runtime's enabled mock engine by default and keep the noop/release artifact's mock engine disabled for production safety. + +## Behavior and interfaces + +- `BrowserConfig()` defaults to `BrowserBinding.LAN`, affecting the in-app inspector More-screen Start action. +- `StartRequest()` defaults to `BindingMode.LAN`, affecting programmatic `DevConsole.startBrowser()` calls. +- The lower-level `sdk:server-api` `StartRequest()` default is aligned to LAN so its published abstraction has no conflicting default. +- Hosts can explicitly select `BrowserBinding.LOOPBACK` or `BindingMode.LOOPBACK`; all existing LAN permission and eligible-interface checks remain unchanged. +- The full/debug `MockEngine` remains enabled by default. The noop/release `MockEngine` remains disabled, and explicit capture-category gating still takes precedence. + +## Implementation and documentation + +- Change the existing constructor defaults and stale KDoc/comments in `sdk:api` and `sdk:server-api`. +- Update README, setup, and threat-model guidance to describe LAN as the default and loopback as the explicit safer override. +- Do not add a new configuration field or alter permission handling, capture-category semantics, mock kill-switch behavior, or UI loading-state defaults. + +## Tests and acceptance + +- API tests assert LAN defaults for `BrowserConfig()` and public `StartRequest()`. +- Server-API tests assert the aligned lower-level `StartRequest()` default. +- Full-runtime tests assert default More-screen LAN binding, explicit loopback binding, and enabled full-runtime mocks. +- Noop tests assert mocks remain disabled. +- Run affected API, server, mocks, and full unit tests plus compilation/API checks; confirm no documentation or comments still claim loopback is the default. + +## Assumptions + +- “Default mock enabled” means the real/debug library runtime only; the noop artifact is intentionally excluded. +- “Default LAN enabled” applies to both existing start entry points, not just the in-app More screen. +- Loopback remains available and is never selected automatically as a fallback when LAN was requested. diff --git a/docs/superpowers/specs/2026-08-17-network-search-design.md b/docs/superpowers/specs/2026-08-17-network-search-design.md new file mode 100644 index 0000000..1036f5e --- /dev/null +++ b/docs/superpowers/specs/2026-08-17-network-search-design.md @@ -0,0 +1,103 @@ +# Network Detail Search Design + +**Date:** 2026-08-17 +**Scope:** Android Compose Network detail search + +## Goal + +Make Network detail search useful for inspecting request and response data without flattening formatted response bodies. Search must support multi-section scope selection, key/value selection, exact highlighting, and next/previous match navigation. + +## User behavior + +The detail search field searches only the selected network sections: + +- Request headers +- Request body +- Response headers +- Response body + +All four sections are selected by default. General metadata, timing, and redaction sections are never included in this search. + +The search options control opens as a modal bottom sheet. It contains: + +- A multi-select list for the four request/response sections. +- Select all and clear all actions. +- A match mode choice: Keys, Values, or Keys + values. +- Apply and Cancel actions. + +At least one section must be selected before Apply is enabled. The search toolbar summarizes the current scope, for example `All request + response`, `Response body`, or `2 sections`. + +Keys is the default match mode. Matching is case-insensitive substring matching. Applying a changed scope or match mode rebuilds the match index and selects the first result. Clearing the query removes search highlighting and restores the normal detail rendering. + +Matches are ordered by document order: request headers, request body, response headers, response body, with unselected sections omitted. Next and previous controls cycle through this ordered list. The current match is visually stronger than the other matches and is brought into view; its section and any required structured-data ancestors are expanded. + +## Rendering requirements + +Search must preserve the existing representation of each body: + +- Formatted JSON remains a JSON tree while searching. +- Formatted XML remains formatted while searching. +- Raw mode remains raw. +- Header key/value rows remain key/value rows. + +Highlighting is applied to exact matched character ranges with `AnnotatedString` spans. A row-level background alone is insufficient. Structured JSON matches retain their node/path identity so a key match can highlight a property name and a value match can highlight the scalar value. + +Raw or otherwise unstructured content has no semantic key field; it is searched as value text without changing its presentation. + +## Architecture + +Keep this feature in the Compose presentation layer. The detail screen owns query, selected sections, match mode, and current match index with saveable local state. No capture-state or repository changes are needed. + +Introduce a pure Kotlin search model/helper that: + +1. Accepts the network detail sections and search configuration. +2. Produces ordered matches containing section identity, item/path identity, field type, and exact text range. +3. Produces section-level match counts and target metadata for scrolling/expansion. + +The existing detail resolver should enrich sections with match metadata while preserving `Formattable`, `KeyValues`, and `Code` body types. It must not convert a `Formattable` body to a flat `Code` body merely because a query is active. + +The search options bottom sheet edits a draft selection and only changes active search state after Apply. Cancel leaves the current search configuration untouched. + +## Accessibility and interaction + +- Every scope checkbox, match mode option, and navigation button has a meaningful content description or visible label. +- Navigation buttons use at least 48dp touch targets and are disabled when there are no matches. +- The match label communicates `current / total`; no-match state is explicit. +- The bottom sheet has a clear title and an obvious Apply action. + +## Testing + +Add pure unit coverage for: + +- Default all-section scope. +- Excluding general/timing/redaction sections. +- Each multi-select combination. +- Keys, Values, and Keys + values behavior for headers and structured bodies. +- Case-insensitive substring matching and exact ranges. +- Stable document ordering and next/previous wrap-around. +- Nested JSON match identity and ancestor expansion metadata. + +Add Compose/UI coverage for: + +- Opening the options sheet, changing multiple sections, applying, and cancelling. +- Navigation button enabled/disabled states and match count. +- Formatted response bodies remaining formatted while a query is active. + +Verify the feature on the Android emulator in light and dark themes, including a response with nested JSON and multiple matches. + +## Out of scope + +- Regex or query-language search. +- Changes to the traffic-list filter. +- Visual identity/token cleanup unrelated to search. +- Persistence of search options across different network requests or app restarts. + +## Acceptance criteria + +- Search never reports or highlights matches from General, Timing, or Redactions. +- Users can select any combination of the four request/response sections. +- Keys is the default match mode and Values/Keys + values work correctly. +- Next and previous navigate through all selected matches and bring the current match into view. +- Matched text is highlighted precisely. +- Searching a formatted response never converts it into a single-line or flat representation. +- Targeted unit/UI tests and the relevant Android build pass. diff --git a/gradle-plugin/build.gradle.kts b/gradle-plugin/build.gradle.kts index 4442241..733241b 100644 --- a/gradle-plugin/build.gradle.kts +++ b/gradle-plugin/build.gradle.kts @@ -9,7 +9,7 @@ plugins { // Must share a top-level namespace with the plugin ID (a Plugin Portal requirement) and match // the SDK's Maven group. group = "io.github.devconsole-android" -version = "1.2.1" +version = "1.2.2" // Targets Java 17: this plugin JAR runs inside the Gradle daemon (AGP 8.13.0 // requires JDK 17) and compiles against com.android.tools.build:gradle:8.13.0, diff --git a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt index 64be54e..8a113c1 100644 --- a/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt +++ b/gradle-plugin/src/main/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPlugin.kt @@ -151,7 +151,7 @@ abstract class VerifyDevConsoleProtectedArtifactsTask : DefaultTask() { /** Enabled runtime/adapters that must never reach a protected variant. */ val FULL_RUNTIME_COORDINATE = Regex( - "^io\\.github\\.devconsole-android:" + + "^(?:com\\.github\\.devconsole-android\\.DevConsole|io\\.github\\.devconsole-android):" + "(?:devconsole|devconsole-network-okhttp|devconsole-mocks-okhttp|" + "devconsole-socket-okhttp|devconsole-socket-paho|devconsole-push-firebase|" + "devconsole-remote-config-firebase):.+", @@ -397,8 +397,15 @@ abstract class VerifyDevConsolePackagedArtifactTask : DefaultTask() { } } -private const val DEFAULT_SDK_VERSION = "1.2.1" -private const val DEVCONSOLE_GROUP = "io.github.devconsole-android" +// JitPack serves a build under its git ref name, and this repo tags `v*` -- a bare "1.2.2" +// does not resolve. Keep the `v`. +private const val DEFAULT_SDK_VERSION = "v1.2.2" + +/** JitPack's group for this repo — what auto-wiring declares. */ +private const val DEVCONSOLE_GROUP = "com.github.devconsole-android.DevConsole" + +/** Recognised on a host's classpath: the JitPack group, plus the Maven Central group used up to 1.2.1. */ +private val DEVCONSOLE_GROUPS = setOf(DEVCONSOLE_GROUP, "io.github.devconsole-android") /** * Core runtime coordinate names whose presence means a host already declared the DevConsole runtime, @@ -661,7 +668,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { // Only the core runtime coordinates count as "already declared" for the purpose of skipping // core auto-wire. Declaring only an add-on (devconsole-ui-compose / devconsole-ui-views / // devconsole-network-ktor) in the same group must NOT suppress wiring the core runtime. - else -> group == DEVCONSOLE_GROUP && name in CORE_RUNTIME_COORDINATE_NAMES + else -> group in DEVCONSOLE_GROUPS && name in CORE_RUNTIME_COORDINATE_NAMES } private fun Project.registerProtectedVerifier( @@ -682,7 +689,7 @@ class DevConsoleVariantPolicyPlugin : Plugin { val path = dep.projectPathCompat() if (path in protectedPaths) "$variant -> $path" else null } - dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group == DEVCONSOLE_GROUP && dep.name == "devconsole" -> "$variant -> ${dep.group}:${dep.name}" + dep is org.gradle.api.artifacts.ExternalModuleDependency && dep.group in DEVCONSOLE_GROUPS && dep.name == "devconsole" -> "$variant -> ${dep.group}:${dep.name}" else -> null } } diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt index 328f8d9..a311c56 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/DevConsoleVariantPolicyPluginFunctionalTest.kt @@ -19,6 +19,31 @@ class DevConsoleVariantPolicyPluginFunctionalTest { System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") ?: error("Set ANDROID_HOME or ANDROID_SDK_ROOT to run this functional test.") + /** + * Plants an empty jar + POM for [group]:[artifact]:[version] in a local repo the fixture reads, + * so a coordinate-matching test never depends on the real artifact existing remotely. + */ + private fun addStubCoordinate( + group: String, + artifact: String, + version: String, + ) { + val dir = File(projectDir.root, "stub-repo/${group.replace('.', '/')}/$artifact/$version") + dir.mkdirs() + File(dir, "$artifact-$version.jar").writeBytes(EMPTY_JAR_BYTES) + File(dir, "$artifact-$version.pom").writeText( + """ + + 4.0.0 + $group + $artifact + $version + jar + + """.trimIndent(), + ) + } + private fun writeFixture( devConsoleBlock: String, extraBuildScript: String = "", @@ -34,13 +59,21 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) { File(projectDir.root, "local.properties") .writeText("sdk.dir=${androidSdkDir().replace("\\", "\\\\")}\n") + File(projectDir.root, "gradle.properties").writeText("android.useAndroidX=true\n") File(projectDir.root, "settings.gradle.kts").writeText( """ pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } dependencyResolutionManagement { - repositories { google(); mavenCentral() } + // jitpack.io serves the auto-wired devconsole coordinates, so any fixture that + // resolves a runtime classpath needs it -- same as a real consumer. + repositories { + maven { url = uri("${'$'}{rootDir}/stub-repo") } + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } } rootProject.name = "fixture" """.trimIndent(), @@ -683,7 +716,7 @@ class DevConsoleVariantPolicyPluginFunctionalTest { assertTrue(result.output, result.output.contains("BUILD SUCCESSFUL")) assertTrue(result.output, result.output.contains(":stub-full")) - assertTrue(result.output, !result.output.contains("io.github.devconsole-android:devconsole")) + assertTrue(result.output, !result.output.contains("com.github.devconsole-android.DevConsole:devconsole")) } @Test @@ -837,12 +870,12 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) // release is PROTECTED by default, so auto-wire adds the noop core coordinate. The published - // coordinate is 1.2.1 -- the DEFAULT_SDK_VERSION must not point at a 1.2.1-SNAPSHOT that was + // coordinate is 1.2.2 -- the DEFAULT_SDK_VERSION must not point at a 1.2.2-SNAPSHOT that was // never published, which would make every zero-config release build fail to resolve. val result = runner("dependencies", "--configuration", "releaseImplementation").build() - assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-noop:1.2.1")) - assertTrue(result.output, !result.output.contains("1.2.1-SNAPSHOT")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole-noop:v1.2.2")) + assertTrue(result.output, !result.output.contains("1.2.2-SNAPSHOT")) } @Test @@ -863,6 +896,56 @@ class DevConsoleVariantPolicyPluginFunctionalTest { ) } + @Test + fun `a legacy Maven Central coordinate still trips the declared-dependency check`() { + addStubCoordinate("io.github.devconsole-android", "devconsole", "1.2.1") + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + extraBuildScript = + """ + dependencies { + add("releaseImplementation", "io.github.devconsole-android:devconsole:1.2.1") + } + """.trimIndent(), + ) + + val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() + + // The pre-JitPack group must keep failing a protected variant: hosts that have not migrated + // their coordinates still depend on this check to keep the full runtime out of release. + assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + // The declared-dependency entry carries no version and no "(resolved)" suffix -- asserting it + // specifically keeps the transitive-regex path from satisfying this test on its own. + assertTrue( + result.output, + Regex("release -> io\\.github\\.devconsole-android:devconsole(,|\\s*$)", RegexOption.MULTILINE) + .containsMatchIn(result.output), + ) + } + + @Test + fun `the JitPack coordinate trips the declared-dependency check`() { + addStubCoordinate("com.github.devconsole-android.DevConsole", "devconsole", "v1.2.2") + writeFixture( + devConsoleBlock = "autoWireDependencies.set(false)", + extraBuildScript = + """ + dependencies { + add("releaseImplementation", "com.github.devconsole-android.DevConsole:devconsole:v1.2.2") + } + """.trimIndent(), + ) + + val result = runner("verifyDevConsoleProtectedArtifacts").buildAndFail() + + assertTrue(result.output, result.output.contains("Protected variants contain the full DevConsole runtime")) + assertTrue( + result.output, + Regex("release -> com\\.github\\.devconsole-android\\.DevConsole:devconsole(,|\\s*$)", RegexOption.MULTILINE) + .containsMatchIn(result.output), + ) + } + @Test fun `declaring only an add-on coordinate still auto-wires the core runtime`() { writeFixture( @@ -873,8 +956,9 @@ class DevConsoleVariantPolicyPluginFunctionalTest { applicationId = "io.devconsole.fixture" versionCode = 1 """.trimIndent(), - // An add-on coordinate in the DevConsole group but NOT the core runtime. It must not be + // An add-on coordinate in a DevConsole group but NOT the core runtime. It must not be // mistaken for "the core runtime is already declared" and suppress core auto-wire. + // Deliberately the pre-JitPack group, which also covers that it is still recognised. extraBuildScript = """ dependencies { @@ -887,7 +971,14 @@ class DevConsoleVariantPolicyPluginFunctionalTest { // debug is ENABLED, so the core runtime ("devconsole") must still be auto-wired alongside the // host's add-on declaration -- the add-on alone does not count as declaring the core runtime. - assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole:1.2.1")) + assertTrue(result.output, result.output.contains("com.github.devconsole-android.DevConsole:devconsole:v1.2.2")) assertTrue(result.output, result.output.contains("io.github.devconsole-android:devconsole-ui-compose")) } + + private companion object { + /** A valid, empty zip -- enough for Gradle to accept the stub as a jar artifact. */ + val EMPTY_JAR_BYTES = + byteArrayOf(0x50, 0x4B, 0x05, 0x06) + ByteArray(18) + } + } diff --git a/samples/compose-app/build.gradle.kts b/samples/compose-app/build.gradle.kts index 20c858b..599ba2a 100644 --- a/samples/compose-app/build.gradle.kts +++ b/samples/compose-app/build.gradle.kts @@ -12,7 +12,7 @@ android { defaultConfig { applicationId = "io.devconsole.sample.compose" versionCode = 1 - versionName = "1.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/samples/foundation-app/build.gradle.kts b/samples/foundation-app/build.gradle.kts index d25e673..b450fa0 100644 --- a/samples/foundation-app/build.gradle.kts +++ b/samples/foundation-app/build.gradle.kts @@ -31,6 +31,6 @@ android { defaultConfig { applicationId = "io.devconsole.sample" versionCode = 1 - versionName = "1.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/samples/views-java-app/build.gradle.kts b/samples/views-java-app/build.gradle.kts index d6ca3fe..b4e93a8 100644 --- a/samples/views-java-app/build.gradle.kts +++ b/samples/views-java-app/build.gradle.kts @@ -9,7 +9,7 @@ android { defaultConfig { applicationId = "io.devconsole.sample.viewsjava" versionCode = 1 - versionName = "1.2.1-SNAPSHOT" + versionName = "1.2.2-SNAPSHOT" } } diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index 84beae7..0fc5305 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -109,12 +109,13 @@ object DevConsole { * [StartRequest.bindingMode] decides loopback-vs-LAN for *this call*, and no [DevConsoleConfig] * value provides a default for it: `DevConsoleConfig.browserConfig.binding` governs only the * starts this method is not making -- the in-app inspector's More-screen Start button -- so a - * host that wants LAN from both surfaces sets both. See the KDoc on - * [io.devconsole.api.BindingMode] and [io.devconsole.api.BrowserBinding]. The default - * `StartRequest()` binds loopback, which is the safe choice -- see `docs/THREAT_MODEL.md` at - * the repository root before ever passing `bindingMode = BindingMode.LAN`. + * host can configure each surface independently. See the KDoc on [io.devconsole.api.BindingMode] + * and [io.devconsole.api.BrowserBinding]. The default `StartRequest()` binds + * [io.devconsole.api.BindingMode.AUTO], which prefers the device's network address and degrades + * to loopback rather than failing; pass `bindingMode = BindingMode.LOOPBACK` explicitly for the + * safer ADB-only choice on an untrusted network. See `docs/THREAT_MODEL.md` at the repository root. * - * @param request binding mode and port range for this start attempt. Defaults to loopback on + * @param request binding mode and port range for this start attempt. Defaults to AUTO on * `8080..8099`. * @return a [StartResult] -- [StartResult.Started] carries the bound [io.devconsole.api.BrowserEndpoint] * and the session [io.devconsole.api.AccessInfo] (the connect URL/code); every other variant is a diff --git a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt index 6ddbcd0..8c80cd0 100644 --- a/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt +++ b/sdk/mocks/src/test/kotlin/io/devconsole/mocks/MockEngineTest.kt @@ -5,6 +5,11 @@ import org.junit.Assert.assertTrue import org.junit.Test class MockEngineTest { + @Test + fun `mock engine is enabled by default`() { + assertTrue(MockEngine(emptyList()).isEnabled()) + } + @Test fun `chooses exact-path rule over wildcard at equal priority`() { val engine = MockEngine(listOf(MockRule("wild", 1, path = "/.*"), MockRule("exact", 1, path = "/orders"))) assertEquals( diff --git a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt index 7a6384f..57093d2 100644 --- a/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt +++ b/sdk/noop/src/test/kotlin/io/devconsole/NoopFacadeTest.kt @@ -20,6 +20,7 @@ class NoopFacadeTest { assertEquals(InitResult.Disabled, DevConsole.initialize(Application(), DevConsoleConfig.default())) assertEquals(DevConsoleState.DisabledForBuild, DevConsole.state().value) assertEquals(StartResult.DisabledForBuild, DevConsole.startBrowser()) + assertTrue(!DevConsole.mockEngine().isEnabled()) } @Test diff --git a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt index e679e0a..5194df5 100644 --- a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt +++ b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt @@ -23,7 +23,7 @@ data class SessionPolicy( } data class StartRequest( - val bindingMode: BindingMode = BindingMode.LOOPBACK, + val bindingMode: BindingMode = BindingMode.LAN, val portRange: IntRange = 8080..8099, val sessionCodeTtlMs: Long = SessionCodeAuthority.DEFAULT_SESSION_CODE_TTL_MS, ) @@ -383,7 +383,7 @@ class SessionCodeAuthority( /** * The endpoint/TTL from the most recent [issueCode] call -- reused by a caller that re-issues * with no arguments (e.g. [currentInfo]'s auto re-mint) so a fresh code still points at the - * real bind address instead of falling back to the loopback default. + * real bind address instead of falling back to the initial placeholder endpoint. */ private var lastEndpoint: Endpoint = Endpoint(DEFAULT_LOOPBACK_HOST, DEFAULT_LOOPBACK_PORT, BindingMode.LOOPBACK) private var lastTtlMs: Long = codeTtlMs diff --git a/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt new file mode 100644 index 0000000..92a6740 --- /dev/null +++ b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt @@ -0,0 +1,11 @@ +package io.devconsole.server.api + +import org.junit.Assert.assertEquals +import org.junit.Test + +class StartRequestDefaultsTest { + @Test + fun `default server start request uses LAN binding`() { + assertEquals(BindingMode.LAN, StartRequest().bindingMode) + } +} diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css index 8a416e8..d0f8af7 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1430,7 +1430,7 @@ kbd { Trims are CSS-first: the underlying control/state is untouched, only its rail/toolbar/detail affordance is hidden in Simple mode, so switching back to Advanced never loses anything. ============================================================ */ -body.mode-simple .metrics-strip { display: none; } +body.mode-simple .metric-strip { display: none; } body.mode-simple #networkMethodGroup, body.mode-simple #networkHostDrop, body.mode-simple #networkToggleHost, diff --git a/sdk/storage-room/README.md b/sdk/storage-room/README.md index c2dcd9f..54c9ec5 100644 --- a/sdk/storage-room/README.md +++ b/sdk/storage-room/README.md @@ -6,9 +6,13 @@ 1. Add dependency to your build file: ```kotlin -debugImplementation("io.github.devconsole-android:devconsole-storage-room:") +debugImplementation("com.github.devconsole-android.DevConsole:devconsole-storage-room:v") ``` +`v` is a JitPack version, which is the git tag verbatim — releases are tagged `v*`, so +`v1.2.2`, not `1.2.2`. The plugin is the exception: it comes from the Gradle Plugin Portal, where +its version is bare. + `sdk:full` wires this module in automatically for durable timeline storage — no additional registration is required. Scope it to `debugImplementation` (never plain `implementation`) yourself if you depend on it directly: it is not in the Gradle plugin's protected-artifact denylist, so diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index b10cd69..8cd66f7 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -1,7 +1,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$CollapsibleSectionKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$CollapsibleSectionKt; public fun ()V - public final fun getLambda$-1132852660$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$-231784725$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/ComposableSingletons$DevConsoleActivityKt { @@ -65,7 +65,7 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDesign public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailHeaderKt; public fun ()V - public final fun getLambda$844457626$ui_compose_release ()Lkotlin/jvm/functions/Function2; + public final fun getLambda$520449243$ui_compose_release ()Lkotlin/jvm/functions/Function2; } public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailPreviewsKt { @@ -80,6 +80,14 @@ public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetail public final fun getLambda$916258535$ui_compose_release ()Lkotlin/jvm/functions/Function2; } +public final class io/devconsole/ui/compose/ComposableSingletons$InspectorDetailSearchOptionsSheetKt { + public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorDetailSearchOptionsSheetKt; + public fun ()V + public final fun getLambda$-592466661$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$1722714866$ui_compose_release ()Lkotlin/jvm/functions/Function3; + public final fun getLambda$481453717$ui_compose_release ()Lkotlin/jvm/functions/Function3; +} + public final class io/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt { public static final field INSTANCE Lio/devconsole/ui/compose/ComposableSingletons$InspectorFilesSectionKt; public fun ()V diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt index 6b7b5f7..c1e2168 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorBodyFormat.kt @@ -190,6 +190,8 @@ internal data class JsonTreeRow( val content: JsonTreeRowContent, val trailingComma: Boolean, val highlighted: Boolean = false, + val searchKeyHighlights: List = emptyList(), + val searchValueHighlights: List = emptyList(), ) /** diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt index 52fd0bb..08e7f7a 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeBlock.kt @@ -3,6 +3,7 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -16,10 +17,15 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -60,11 +66,29 @@ internal val InlineCodeBlockMaxHeight = 420.dp internal fun InspectorCodeBlock( lines: List, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, onExpandFullScreen: (() -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - Box(modifier = modifier.fillMaxWidth()) { + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } + val listState = rememberLazyListState() + val bringIntoViewRequester = remember { BringIntoViewRequester() } + val activeLineIndex = activeInspectorLineIndex(sectionMatches, currentMatchOrdinal) + LaunchedEffect(activeLineIndex, currentMatchOrdinal) { + activeLineIndex?.let { index -> + if (lines.isNotEmpty()) listState.animateScrollToItem(index.coerceIn(0, lines.lastIndex)) + } + if (activeLineIndex != null) bringIntoViewRequester.bringIntoView() + } + Box(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { LazyColumn( + state = listState, modifier = Modifier .fillMaxWidth() @@ -84,7 +108,14 @@ internal fun InspectorCodeBlock( .horizontalScroll(rememberScrollState()) .padding(horizontal = 16.dp, vertical = 12.dp), ) { - itemsIndexed(lines, key = { index, _ -> index }) { _, line -> CodeLineRow(line) } + itemsIndexed(lines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + keyHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), + valueHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), + ) + } } if (onExpandFullScreen != null) { InspectorCodeBlockExpandButton(onExpandFullScreen) @@ -119,13 +150,15 @@ internal fun CodeLineRow( line: InspectorCodeLine, fontSize: TextUnit = 13.sp, lineHeight: TextUnit = 22.1.sp, + keyHighlights: List = emptyList(), + valueHighlights: List = emptyList(), ) { val colors = DevConsoleTheme.colors val rowBg = if (line.highlighted) colors.signalSoft else Color.Transparent Row(modifier = Modifier.background(rowBg)) { CodeSpan(line.indent, colors.text3, fontSize, lineHeight) - CodeSpan(line.key, colors.jsonKey, fontSize, lineHeight) - CodeSpan(line.value, line.valueColor, fontSize, lineHeight) + CodeSpan(line.key, colors.jsonKey, fontSize, lineHeight, keyHighlights) + CodeSpan(line.value, line.valueColor, fontSize, lineHeight, valueHighlights) } } @@ -135,6 +168,13 @@ private fun CodeSpan( color: Color, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { - Text(text, color = color, fontFamily = FontFamily.Monospace, fontSize = fontSize, lineHeight = lineHeight) + Text( + inspectorHighlightedText(text, highlights, DevConsoleTheme.colors), + color = color, + fontFamily = FontFamily.Monospace, + fontSize = fontSize, + lineHeight = lineHeight, + ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt index 75eb5e6..5fa8bb8 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorCodeFullScreenOverlay.kt @@ -11,12 +11,14 @@ import androidx.compose.animation.core.Animatable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.material3.Surface import androidx.compose.material3.Text @@ -32,7 +34,9 @@ import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp +import java.util.Locale /** * Full-screen overlay for a single [InspectorCodeBlock]'s content: @@ -43,20 +47,60 @@ import androidx.compose.ui.unit.sp * Convenience overload of the [content]-taking overload below, for the common case of one flat * [InspectorCodeLine] list; [InspectorFormattableBody] uses the general one to add a JSON tree. */ +@Suppress("LongParameterList") // Search/highlight inputs plus the section's own copy action. @Composable internal fun InspectorCodeFullScreenOverlay( title: String, lines: List, onDismiss: () -> Unit, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", ) { - InspectorCodeFullScreenOverlay(title = title, onDismiss = onDismiss, modifier = modifier) { - itemsIndexed(lines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize = 14.sp, lineHeight = 23.8.sp) + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } + InspectorCodeFullScreenOverlay( + title = title, + onDismiss = onDismiss, + modifier = modifier, + targetIndex = activeInspectorLineIndex(sectionMatches, currentMatchOrdinal), + onCopy = onCopy, + copyContentDescription = copyContentDescription, + meta = inspectorLineCountMeta(lines.size), + ) { + itemsIndexed(lines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = 14.sp, + lineHeight = 23.8.sp, + keyHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), + valueHighlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), + ) } } } +/** "1 line" / "N lines" -- the same count the collapsed section card shows in its meta slot. */ +internal fun inspectorLineCountMeta(count: Int): String? = + if (count <= 0) null else "$count line${if (count == 1) "" else "s"}" + +internal fun activeInspectorLineIndex( + matches: List, + currentMatchOrdinal: Int?, +): Int? = + matches + .firstOrNull { it.ordinal == currentMatchOrdinal } + ?.itemId + ?.substringAfter("line:", "") + ?.toIntOrNull() + /** * General form: header + a both-axes-scrollable [LazyColumn] body. Unlike the inline * [InspectorCodeBlock], this owns the whole remaining viewport (via `weight(1f)` in a `fillMaxSize` @@ -64,12 +108,18 @@ internal fun InspectorCodeFullScreenOverlay( * thousands-of-lines body only composes the rows actually scrolled into view. [headerTrailing] is an * optional control (the Raw/Formatted toggle) rendered at the header's trailing edge. */ +@Suppress("LongParameterList") // Header slots (trailing control, copy action) plus scroll target. @Composable internal fun InspectorCodeFullScreenOverlay( title: String, onDismiss: () -> Unit, modifier: Modifier = Modifier, headerTrailing: (@Composable () -> Unit)? = null, + targetIndex: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", + /** Right-aligned readout under the title -- what is on screen, e.g. "6 lines". */ + meta: String? = null, content: LazyListScope.() -> Unit, ) { BackHandler(onBack = onDismiss) @@ -79,7 +129,11 @@ internal fun InspectorCodeFullScreenOverlay( // same way, and driven from one Animatable so the whole entrance runs in the draw phase. val entranceSpec = feedbackSpec(InspectorMotion.OVERLAY_MS) val entrance = remember { Animatable(0f) } + val listState = rememberLazyListState(initialFirstVisibleItemIndex = targetIndex ?: 0) LaunchedEffect(Unit) { entrance.animateTo(1f, entranceSpec) } + LaunchedEffect(targetIndex) { + targetIndex?.let { index -> listState.scrollToItem(index.coerceAtLeast(0)) } + } Surface( modifier = modifier.fillMaxSize().graphicsLayer { @@ -92,8 +146,9 @@ internal fun InspectorCodeFullScreenOverlay( color = colors.ground, ) { Column(modifier = Modifier.fillMaxSize()) { - CodeFullScreenHeader(title, onDismiss, headerTrailing) + CodeFullScreenHeader(title, onDismiss, onCopy, copyContentDescription, meta, headerTrailing) LazyColumn( + state = listState, modifier = Modifier .weight(1f) @@ -106,14 +161,23 @@ internal fun InspectorCodeFullScreenOverlay( } } +/** + * Two bands, mirroring [InspectorDetailHeader]'s own structure so the overlay reads as a sibling of + * the detail screen rather than a bolted-on modal: the identity row (back, section name, copy) owns + * the full width so a long name is never truncated by a control sitting beside it, and the controls + * row underneath carries the view switch against a right-aligned mono readout of what is on screen. + */ @Composable private fun CodeFullScreenHeader( title: String, onDismiss: () -> Unit, + onCopy: (() -> Unit)?, + copyContentDescription: String, + meta: String?, trailing: (@Composable () -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - Row( + Column( modifier = Modifier .fillMaxWidth() @@ -123,33 +187,70 @@ private fun CodeFullScreenHeader( val strokeWidth = 1.dp.toPx() val y = size.height - strokeWidth / 2 drawLine(colors.line, Offset(0f, y), Offset(size.width, y), strokeWidth) - }.padding(vertical = 8.dp, horizontal = 8.dp), - verticalAlignment = Alignment.CenterVertically, + }, ) { - InspectorRoundIconButton( - contentDescription = "Close full screen", - onClick = onDismiss, - icon = { - InspectorGlyphIcon( - InspectorGlyph.ChevronDown, - contentDescription = null, - tint = colors.ink, - size = 20.dp, - rotationDegrees = 90f, + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InspectorRoundIconButton( + contentDescription = "Close full screen", + onClick = onDismiss, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = colors.ink, + size = 20.dp, + rotationDegrees = 90f, + ) + }, + ) + // UI stack, not mono: this is the section's name, not captured data. Mono here would + // claim "Response body" came off the wire. + Text( + title, + modifier = Modifier.weight(1f).padding(start = 4.dp), + color = colors.ink, + fontWeight = FontWeight.SemiBold, + fontSize = 16.sp, + letterSpacing = (-0.01).em, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + if (onCopy != null) { + InspectorRoundIconButton( + contentDescription = copyContentDescription, + onClick = onCopy, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.Copy, + contentDescription = null, + tint = colors.muted, + size = 17.dp, + ) + }, ) - }, - ) - Text( - title, - modifier = Modifier.weight(1f).padding(start = 4.dp), - color = colors.ink, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.SemiBold, - fontSize = 14.sp, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - trailing?.invoke() + } + } + if (trailing != null || meta != null) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + trailing?.invoke() + Spacer(Modifier.weight(1f)) + if (meta != null) { + Text( + meta.uppercase(Locale.US), + color = colors.text3, + fontFamily = FontFamily.Monospace, + style = DevConsoleType.groupLabel, + ) + } + } + } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt new file mode 100644 index 0000000..5231a20 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearch.kt @@ -0,0 +1,231 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +/** Whether a search candidate represents a field name or its associated content. */ +internal enum class InspectorSearchField { + KEY, + VALUE, +} + +/** Which side of a formattable body's Raw/Formatted toggle is currently rendered. */ +internal enum class InspectorBodySearchRepresentation { + RAW, + FORMATTED, +} + +/** Search fields enabled by the Network detail search options sheet. */ +internal enum class InspectorSearchMode( + val label: String, + /** What this mode will and won't match, shown under the chips in the search options sheet. */ + val hint: String, +) { + KEYS("Keys", "Header names and JSON field names. Raw and XML bodies have none, so they never match."), + VALUES("Values", "Header values, JSON values, and raw or XML body text."), + KEYS_AND_VALUES("Keys + values", "Names and values together."), +} + +/** One searchable piece of rendered detail content. */ +internal data class InspectorSearchCandidate( + val sectionKey: String, + val itemId: String, + val field: InspectorSearchField, + val text: String, + val path: String? = null, + val ancestorPaths: List = emptyList(), +) + +/** One exact query occurrence in a searchable candidate. */ +internal data class InspectorDetailSearchMatch( + val ordinal: Int, + val sectionKey: String, + val itemId: String, + val field: InspectorSearchField, + val start: Int, + val endExclusive: Int, + val path: String? = null, + val ancestorPaths: List = emptyList(), +) + +internal data class InspectorDetailSearchSection( + val key: String, + val label: String, +) + +/** Callback-free section input suitable for use as a remembered candidate-cache key. */ +internal data class InspectorSearchSectionBody( + val sectionKey: String, + val body: InspectorDetailSectionBody, +) + +internal data class InspectorDetailSearchOptions( + val sections: List, + val defaultSectionKeys: Set, + /** + * Keys-only would silently miss raw and XML bodies, which carry no names to match, so a first + * search finds everything the query appears in and the sheet narrows from there. + */ + val defaultMode: InspectorSearchMode = InspectorSearchMode.KEYS_AND_VALUES, +) + +/** + * The four detail slots every captured-exchange kind lays out, in render order. [key] is the stable + * id an [InspectorDetailSectionSpec] carries; the labels here are the network wording, and other + * kinds reuse the same slots under their own names (a socket frame's [PRIMARY_BODY] is "Payload"). + */ +internal enum class InspectorExchangeSection( + val key: String, + val networkLabel: String, +) { + PRIMARY_HEADERS("reqh", "Request headers"), + PRIMARY_BODY("req", "Request body"), + SECONDARY_HEADERS("resh", "Response headers"), + SECONDARY_BODY("res", "Response body"), + ; + + internal companion object { + /** The slots a first search covers: bodies carry the payload, headers are the noisy half. */ + val defaultSearchScope = setOf(PRIMARY_BODY, SECONDARY_BODY) + + fun keysOf(sections: Set): Set = sections.mapTo(mutableSetOf()) { it.key } + } +} + +internal val NetworkDetailSearchOptions = + InspectorDetailSearchOptions( + sections = + InspectorExchangeSection.entries.map { section -> + InspectorDetailSearchSection(section.key, section.networkLabel) + }, + defaultSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope), + ) + +internal fun inspectorSearchSectionBodies( + sections: List, + searchableSectionKeys: Set, +): List = + sections.mapNotNull { spec -> + if (spec.key in searchableSectionKeys) InspectorSearchSectionBody(spec.key, spec.body) else null + } + +internal fun inspectorSearchScopeSummary( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, +): String { + val selected = options.sections.filter { it.key in selectedSectionKeys } + return when { + selected.size == options.sections.size -> "All sections" + selected.size == 1 -> selected.single().label + selected.isEmpty() -> "Nothing selected" + else -> "${selected.size} sections" + } +} + +/** Returns all non-overlapping, case-insensitive occurrences of [query] in [text]. */ +private fun findInspectorQueryRanges( + text: String, + query: String, +): List { + if (query.isEmpty() || query.length > text.length) return emptyList() + val ranges = mutableListOf() + var start = 0 + while (start <= text.length - query.length) { + val matchAt = text.indexOf(query, start, ignoreCase = true) + if (matchAt < 0) break + ranges += matchAt until (matchAt + query.length) + start = matchAt + query.length + } + return ranges +} + +private fun InspectorSearchMode.includes(field: InspectorSearchField): Boolean = + when (this) { + InspectorSearchMode.KEYS -> field == InspectorSearchField.KEY + InspectorSearchMode.VALUES -> field == InspectorSearchField.VALUE + InspectorSearchMode.KEYS_AND_VALUES -> true + } + +/** Matches selected candidates in their supplied document order. */ +internal fun searchInspectorCandidates( + candidates: List, + query: String, + selectedSectionKeys: Set, + mode: InspectorSearchMode, +): List { + val trimmedQuery = query.trim() + if (trimmedQuery.isEmpty()) return emptyList() + + return buildList { + candidates.forEach { candidate -> + if (candidate.sectionKey !in selectedSectionKeys || !mode.includes(candidate.field)) return@forEach + findInspectorQueryRanges(candidate.text, trimmedQuery).forEach { range -> + add( + InspectorDetailSearchMatch( + ordinal = size, + sectionKey = candidate.sectionKey, + itemId = candidate.itemId, + field = candidate.field, + start = range.first, + endExclusive = range.last + 1, + path = candidate.path, + ancestorPaths = candidate.ancestorPaths, + ), + ) + } + } + } +} + +internal fun nextInspectorMatchIndex( + current: Int, + total: Int, +): Int = if (total <= 0) 0 else (current.coerceIn(0, total - 1) + 1) % total + +internal fun previousInspectorMatchIndex( + current: Int, + total: Int, +): Int = if (total <= 0) 0 else (current.coerceIn(0, total - 1) - 1 + total) % total + +/** Extracts candidates in the same order that a detail body presents them. */ +internal fun searchInspectorBodyCandidates( + sectionKey: String, + body: InspectorDetailSectionBody, + representation: InspectorBodySearchRepresentation = InspectorBodySearchRepresentation.FORMATTED, +): List = + when (body) { + is InspectorDetailSectionBody.KeyValues -> + buildList { + body.entries.forEachIndexed { index, entry -> + add(InspectorSearchCandidate(sectionKey, "row:$index", InspectorSearchField.KEY, entry.key)) + add(InspectorSearchCandidate(sectionKey, "row:$index", InspectorSearchField.VALUE, entry.value)) + } + } + is InspectorDetailSectionBody.Code -> + buildList { + body.lines.forEachIndexed { index, line -> + if (line.key.isNotEmpty()) { + add(InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.KEY, line.key)) + } + if (line.value.isNotEmpty()) { + add(InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value)) + } + } + } + is InspectorDetailSectionBody.Formattable -> + if (representation == InspectorBodySearchRepresentation.RAW || body.formatted == null) { + body.rawLines.mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line.value) + } + } else { + when (val formatted = requireNotNull(body.formatted)) { + is FormattedBody.Json -> jsonSearchCandidates(sectionKey, formatted.root) + is FormattedBody.Xml -> + formatted.text.lines().mapIndexed { index, line -> + InspectorSearchCandidate(sectionKey, "line:$index", InspectorSearchField.VALUE, line) + } + } + } + is InspectorDetailSectionBody.Bars, is InspectorDetailSectionBody.Empty -> emptyList() + } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt index 47f4d2f..29745b5 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchField.kt @@ -9,6 +9,7 @@ package io.devconsole.ui.compose import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height @@ -35,41 +36,91 @@ internal fun InspectorDetailSearchField( onQueryChange: (String) -> Unit, matchLabel: String, modifier: Modifier = Modifier, + onPrevious: (() -> Unit)? = null, + onNext: (() -> Unit)? = null, + navigationEnabled: Boolean = false, + onOpenOptions: (() -> Unit)? = null, + scopeLabel: String? = null, placeholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, matchColor: Color = DevConsoleTheme.colors.muted, ) { - Row( + Column( modifier = modifier.fillMaxWidth().padding(start = 8.dp, end = 8.dp, bottom = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), ) { - Box(modifier = Modifier.weight(1f)) { - Row( - modifier = - Modifier - .fillMaxWidth() - .height(48.dp) - .clip(RoundedCornerShape(50)) - .background(DevConsoleTheme.colors.surface2) - .padding(start = 40.dp, end = 16.dp), - verticalAlignment = Alignment.CenterVertically, - ) { - InspectorPlainTextField( - value = query, - onValueChange = onQueryChange, - placeholder = placeholder, - textColor = DevConsoleTheme.colors.ink, - placeholderColor = DevConsoleTheme.colors.muted, + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + Box(modifier = Modifier.weight(1f)) { + Row( + modifier = + Modifier + .fillMaxWidth() + .height(48.dp) + .clip(RoundedCornerShape(50)) + .background(DevConsoleTheme.colors.surface2) + .padding(start = 40.dp, end = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + InspectorPlainTextField( + value = query, + onValueChange = onQueryChange, + placeholder = placeholder, + textColor = DevConsoleTheme.colors.ink, + placeholderColor = DevConsoleTheme.colors.muted, + ) + } + InspectorGlyphIcon( + InspectorGlyph.Search, + contentDescription = null, + tint = DevConsoleTheme.colors.muted, + size = 17.dp, + modifier = Modifier.align(Alignment.CenterStart).padding(start = 14.dp), ) } - InspectorGlyphIcon( - InspectorGlyph.Search, - contentDescription = null, - tint = DevConsoleTheme.colors.muted, - size = 17.dp, - modifier = Modifier.align(Alignment.CenterStart).padding(start = 14.dp), + Text(matchLabel, color = matchColor, fontFamily = FontFamily.Monospace, fontSize = 12.sp, maxLines = 1) + if (onPrevious != null) { + InspectorRoundIconButton( + contentDescription = "Previous match", + onClick = onPrevious, + enabled = navigationEnabled, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = if (navigationEnabled) DevConsoleTheme.colors.ink else DevConsoleTheme.colors.text3, + size = 16.dp, + rotationDegrees = 90f, + ) + }, + ) + } + if (onNext != null) { + InspectorRoundIconButton( + contentDescription = "Next match", + onClick = onNext, + enabled = navigationEnabled, + size = 44.dp, + icon = { + InspectorGlyphIcon( + InspectorGlyph.ChevronDown, + contentDescription = null, + tint = if (navigationEnabled) DevConsoleTheme.colors.ink else DevConsoleTheme.colors.text3, + size = 16.dp, + rotationDegrees = -90f, + ) + }, + ) + } + } + if (onOpenOptions != null && scopeLabel != null) { + FilterChipRow( + chips = listOf(InspectorFilterChip("search-scope", "Search in: $scopeLabel", selected = true)), + onChipClick = { onOpenOptions() }, + modifier = Modifier.padding(top = 0.dp), ) } - Text(matchLabel, color = matchColor, fontFamily = FontFamily.Monospace, fontSize = 12.sp, maxLines = 1) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt new file mode 100644 index 0000000..5f8286e --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDetailSearchOptionsSheet.kt @@ -0,0 +1,256 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +@file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.material3.ExperimentalMaterial3Api::class) + +package io.devconsole.ui.compose + +import android.content.res.Configuration +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.offset +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Checkbox +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.em +import androidx.compose.ui.unit.sp +import java.util.Locale + +@Composable +internal fun InspectorDetailSearchOptionsSheet( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, +) { + ModalBottomSheet( + onDismissRequest = onDismiss, + containerColor = DevConsoleTheme.colors.panel, + // A half-height first view would cut the section list and hide the mode chips entirely. + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + ) { + InspectorDetailSearchOptionsSheetContent( + options = options, + selectedSectionKeys = selectedSectionKeys, + mode = mode, + onDismiss = onDismiss, + onApply = onApply, + ) + } +} + +@Composable +@Suppress("LongParameterList") // Mirrors the sheet's own signature, plus the conventional modifier. +private fun InspectorDetailSearchOptionsSheetContent( + options: InspectorDetailSearchOptions, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, + modifier: Modifier = Modifier, +) { + var draftSectionKeys by remember(selectedSectionKeys) { mutableStateOf(selectedSectionKeys) } + var draftMode by remember(mode) { mutableStateOf(mode) } + val colors = DevConsoleTheme.colors + + Column( + modifier = + modifier + .fillMaxWidth() + .navigationBarsPadding(), + ) { + SearchOptionsHeader( + applyEnabled = draftSectionKeys.isNotEmpty(), + onDismiss = onDismiss, + onApply = { onApply(draftSectionKeys, draftMode) }, + ) + HorizontalDivider(color = colors.line) + // No weight: the sheet sizes to its content, and this column only starts scrolling once the + // sections outgrow the height the sheet is allowed (short lists get a short sheet). + Column( + modifier = + Modifier + .verticalScroll(rememberScrollState()) + .padding(horizontal = 20.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + SearchSectionPicker( + sections = options.sections, + selectedKeys = draftSectionKeys, + onSelectionChange = { draftSectionKeys = it }, + ) + SearchOptionsGroupLabel("Match on") + FilterChipRow( + chips = + InspectorSearchMode.entries.map { candidate -> + InspectorFilterChip(candidate.name, candidate.label, selected = candidate == draftMode) + }, + onChipClick = { chip -> draftMode = InspectorSearchMode.valueOf(chip.id) }, + contentPadding = PaddingValues(vertical = 8.dp), + ) + Text(draftMode.hint, color = colors.text3, style = MaterialTheme.typography.bodySmall) + } + } +} + +@Composable +private fun SearchOptionsHeader( + applyEnabled: Boolean, + onDismiss: () -> Unit, + onApply: () -> Unit, +) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + "Search options", + color = DevConsoleTheme.colors.ink, + fontSize = 20.sp, + fontWeight = FontWeight.SemiBold, + letterSpacing = (-0.01).em, + modifier = Modifier.weight(1f), + ) + TextButton(onClick = onDismiss) { Text("Cancel") } + InspectorPillButton( + label = "Apply", + onClick = onApply, + enabled = applyEnabled, + modifier = Modifier.padding(start = 8.dp), + ) + } +} + +@Composable +private fun SearchSectionPicker( + sections: List, + selectedKeys: Set, + onSelectionChange: (Set) -> Unit, +) { + SearchOptionsGroupLabel("Search in") + Row( + // Cancels TextButtonHorizontalPadding so the labels sit on the column's own 20dp margin. + modifier = Modifier.fillMaxWidth().offset(x = (-12).dp), + ) { + TextButton(onClick = { onSelectionChange(sections.map { it.key }.toSet()) }) { Text("Select all") } + TextButton(onClick = { onSelectionChange(emptySet()) }) { Text("Clear all") } + } + sections.forEach { section -> + SearchSectionCheckboxRow( + label = section.label, + checked = section.key in selectedKeys, + onCheckedChange = { isChecked -> + onSelectionChange(if (isChecked) selectedKeys + section.key else selectedKeys - section.key) + }, + ) + } + if (selectedKeys.isEmpty()) { + Text( + "Pick at least one section before applying.", + color = DevConsoleTheme.colors.warn, + style = MaterialTheme.typography.bodySmall, + modifier = Modifier.padding(top = 4.dp), + ) + } +} + +/** The design system's Label voice: uppercase, tracked, tertiary -- the sheet's only wayfinding. */ +@Composable +private fun SearchOptionsGroupLabel(text: String) { + Text( + text.uppercase(Locale.US), + color = DevConsoleTheme.colors.text3, + style = DevConsoleType.groupLabel, + modifier = Modifier.padding(top = 16.dp), + ) +} + +/** + * One searchable section. The whole row is the toggle: [Checkbox] is passed a null callback so the + * row's `toggleable` owns both the click and the checked state TalkBack announces. + */ +@Composable +private fun SearchSectionCheckboxRow( + label: String, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, +) { + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .toggleable(value = checked, role = Role.Checkbox, onValueChange = onCheckedChange), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Checkbox(checked = checked, onCheckedChange = null) + Text(label, color = DevConsoleTheme.colors.ink, style = MaterialTheme.typography.bodyLarge) + } +} + +@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true, backgroundColor = 0xFFF3F6EE) +@Preview(name = "Large font", fontScale = 1.5f, showBackground = true, backgroundColor = 0xFF0B0E0D) +@Composable +private fun InspectorDetailSearchOptionsSheetPreview() { + SearchOptionsSheetPreviewScaffold( + selectedSectionKeys = NetworkDetailSearchOptions.defaultSectionKeys, + ) +} + +/** The state that disables Apply: no section selected, so the warning and the gated action show. */ +@Preview( + name = "Nothing selected", + uiMode = Configuration.UI_MODE_NIGHT_YES, + showBackground = true, + backgroundColor = 0xFF0B0E0D, +) +@Composable +private fun InspectorDetailSearchOptionsSheetEmptyPreview() { + SearchOptionsSheetPreviewScaffold(selectedSectionKeys = emptySet()) +} + +@Composable +private fun SearchOptionsSheetPreviewScaffold(selectedSectionKeys: Set) { + DevConsoleTheme(darkTheme = isSystemInDarkTheme()) { + Surface(color = DevConsoleTheme.colors.panel) { + InspectorDetailSearchOptionsSheetContent( + options = NetworkDetailSearchOptions, + selectedSectionKeys = selectedSectionKeys, + mode = NetworkDetailSearchOptions.defaultMode, + onDismiss = {}, + onApply = { _, _ -> }, + ) + } + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt index e2082fa..a8f5a15 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorFormattableBody.kt @@ -3,6 +3,7 @@ * @since 05/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -22,10 +23,14 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateMapOf @@ -54,16 +59,43 @@ import androidx.compose.ui.unit.sp internal fun InspectorFormattableBody( body: InspectorDetailSectionBody.Formattable, modifier: Modifier = Modifier, + showRaw: Boolean? = null, + onShowRawChange: ((Boolean) -> Unit)? = null, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, onExpandFullScreen: (() -> Unit)? = null, ) { val colors = DevConsoleTheme.colors - var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } - val precomputed = rememberFormattableContent(body, showRaw) - Column(modifier = modifier.fillMaxWidth()) { + var localShowRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + val renderedShowRaw = showRaw ?: localShowRaw + val updateShowRaw: (Boolean) -> Unit = { value -> + if (showRaw == null) localShowRaw = value else onShowRawChange?.invoke(value) + } + val precomputed = + rememberFormattableContent( + body = body, + showRaw = renderedShowRaw, + sectionKey = sectionKey, + searchMatches = searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) + val listState = rememberLazyListState() + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val bringIntoViewRequester = remember { BringIntoViewRequester() } + LaunchedEffect(precomputed.targetIndex, currentMatchOrdinal) { + precomputed.targetIndex?.let { index -> + listState.animateScrollToItem(index.coerceAtLeast(0)) + } + if (sectionMatches.any { it.ordinal == currentMatchOrdinal }) { + bringIntoViewRequester.bringIntoView() + } + } + Column(modifier = modifier.fillMaxWidth().bringIntoViewRequester(bringIntoViewRequester)) { if (body.formatted != null) { RawFormattedToggle( - showRaw = showRaw, - onToggle = { showRaw = it }, + showRaw = renderedShowRaw, + onToggle = updateShowRaw, // Matches the 16dp horizontal inset InspectorKeyValueList/InspectorProgressBars/ // InspectorDetailEmptyText each apply themselves for a CollapsibleSection's content -- // FilterChipRow carries no inset of its own (its other callers sit inside a parent @@ -86,6 +118,7 @@ internal fun InspectorFormattableBody( } Box(modifier = Modifier.fillMaxWidth()) { LazyColumn( + state = listState, modifier = Modifier .fillMaxWidth() @@ -98,7 +131,7 @@ internal fun InspectorFormattableBody( // only visible for tall bodies with progressively wider lines, not a bug. .horizontalScroll(rememberScrollState()) .padding(horizontal = 16.dp, vertical = 12.dp), - content = precomputed, + content = precomputed.content, ) if (onExpandFullScreen != null) { InspectorCodeBlockExpandButton(onExpandFullScreen) @@ -114,20 +147,44 @@ internal fun InspectorFormattableFullScreenOverlay( body: InspectorDetailSectionBody.Formattable, onDismiss: () -> Unit, modifier: Modifier = Modifier, + showRaw: Boolean? = null, + onShowRawChange: ((Boolean) -> Unit)? = null, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, + onCopy: (() -> Unit)? = null, + copyContentDescription: String = "Copy $title", ) { - var showRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } - val precomputed = rememberFormattableContent(body, showRaw, fontSize = 14.sp, lineHeight = 23.8.sp) + var localShowRaw by rememberSaveable(body.rawText) { mutableStateOf(body.formatted == null) } + val renderedShowRaw = showRaw ?: localShowRaw + val updateShowRaw: (Boolean) -> Unit = { value -> + if (showRaw == null) localShowRaw = value else onShowRawChange?.invoke(value) + } + val precomputed = + rememberFormattableContent( + body = body, + showRaw = renderedShowRaw, + fontSize = 14.sp, + lineHeight = 23.8.sp, + sectionKey = sectionKey, + searchMatches = searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) InspectorCodeFullScreenOverlay( title = title, onDismiss = onDismiss, modifier = modifier, headerTrailing = if (body.formatted != null) { - { RawFormattedToggle(showRaw = showRaw, onToggle = { showRaw = it }, compact = true) } + { RawFormattedToggle(showRaw = renderedShowRaw, onToggle = updateShowRaw, compact = true) } } else { null }, - content = precomputed, + targetIndex = precomputed.targetIndex, + onCopy = onCopy, + copyContentDescription = copyContentDescription, + meta = inspectorLineCountMeta(body.rawLines.size), + content = precomputed.content, ) } @@ -138,14 +195,27 @@ internal fun InspectorFormattableFullScreenOverlay( * `content: LazyListScope.() -> Unit` lambda itself -- that lambda type isn't `@Composable`, so * `remember`/[rememberJsonTreeRows] can't be called from inside it directly. */ +private data class FormattableRenderContent( + val content: LazyListScope.() -> Unit, + val targetIndex: Int?, +) + @Composable private fun rememberFormattableContent( body: InspectorDetailSectionBody.Formattable, showRaw: Boolean, fontSize: TextUnit = 13.sp, lineHeight: TextUnit = 22.1.sp, -): LazyListScope.() -> Unit { + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, +): FormattableRenderContent { val colors = DevConsoleTheme.colors + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } val formatted = body.formatted val useRaw = showRaw || formatted == null @@ -157,27 +227,69 @@ private fun rememberFormattableContent( } val jsonTree: Pair, (String) -> Unit>? = if (!useRaw && formatted is FormattedBody.Json) { - rememberJsonTreeRows(formatted.root, body.jsonHighlightPaths) + rememberJsonTreeRows( + root = formatted.root, + highlightedPaths = body.jsonHighlightPaths, + searchMatches = sectionMatches, + currentMatchOrdinal = currentMatchOrdinal, + forcedExpandedPaths = sectionMatches.flatMap { it.ancestorPaths }.toSet(), + ) } else { null } - return { - when { - xmlLines != null -> - itemsIndexed(xmlLines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize, lineHeight) + val activeMatch = sectionMatches.firstOrNull { it.ordinal == currentMatchOrdinal } + val targetIndex = + if (jsonTree != null) { + val rows = jsonTree.first + activeMatch?.path?.let { path -> rows.indexOfFirst { row -> row.path == path }.takeIf { it >= 0 } } + } else { + activeMatch + ?.itemId + ?.substringAfter("line:", "") + ?.toIntOrNull() + } + return FormattableRenderContent( + content = { + when { + xmlLines != null -> + itemsIndexed(xmlLines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = fontSize, + lineHeight = lineHeight, + valueHighlights = + highlightIndex.highlightsFor( + itemId, + InspectorSearchField.VALUE, + ), + ) + } + jsonTree != null -> { + val (rows, onToggle) = jsonTree + items(rows, key = { it.lazyKey() }) { row -> + JsonTreeRowView(row, onToggle, fontSize, lineHeight) + } } - jsonTree != null -> { - val (rows, onToggle) = jsonTree - items(rows, key = { it.lazyKey() }) { row -> JsonTreeRowView(row, onToggle, fontSize, lineHeight) } + else -> + itemsIndexed(body.rawLines, key = { index, _ -> index }) { index, line -> + val itemId = "line:$index" + CodeLineRow( + line = line, + fontSize = fontSize, + lineHeight = lineHeight, + valueHighlights = + highlightIndex.highlightsFor( + itemId, + InspectorSearchField.VALUE, + ), + ) + } } - else -> - itemsIndexed(body.rawLines, key = { index, _ -> index }) { _, line -> - CodeLineRow(line, fontSize, lineHeight) - } - } - } + }, + targetIndex = targetIndex, + ) } /** @@ -191,19 +303,35 @@ private fun rememberFormattableContent( private fun rememberJsonTreeRows( root: JsonValue, highlightedPaths: Set, + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, + forcedExpandedPaths: Set = emptySet(), ): Pair, (String) -> Unit> { val expandedOverrides = remember(root) { mutableStateMapOf() } - val rows by remember(root, highlightedPaths) { + val rows by remember(root, highlightedPaths, forcedExpandedPaths) { derivedStateOf { flattenJsonTree( root, - isExpanded = { path -> expandedOverrides[path] ?: true }, + isExpanded = { path -> path in forcedExpandedPaths || expandedOverrides[path] ?: true }, highlightedPaths = highlightedPaths, ) } } + val highlightIndex = + remember(searchMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(searchMatches, currentMatchOrdinal) + } + val searchRows = + remember(rows, highlightIndex) { + rows.map { row -> + row.copy( + searchKeyHighlights = highlightIndex.highlightsFor(row.path, InspectorSearchField.KEY), + searchValueHighlights = highlightIndex.highlightsFor(row.path, InspectorSearchField.VALUE), + ) + } + } val onToggle: (String) -> Unit = { path -> expandedOverrides[path] = !(expandedOverrides[path] ?: true) } - return rows to onToggle + return searchRows to onToggle } /** A two-chip Raw/Formatted switcher, built from the same [FilterChipRow] every other filter row uses. */ @@ -214,14 +342,13 @@ private fun RawFormattedToggle( modifier: Modifier = Modifier, compact: Boolean = false, ) { - FilterChipRow( - chips = - listOf( - InspectorFilterChip("formatted", "Formatted", !showRaw), - InspectorFilterChip("raw", "Raw", showRaw), - ), - onChipClick = { chip -> onToggle(chip.id == "raw") }, - modifier = if (compact) modifier.padding(end = 4.dp) else modifier, + // A segmented control, not chips: Formatted/Raw are two views of one body, not two filters over + // a set. See DESIGN.md's Components section. + InspectorSegmentedControl( + options = listOf("Formatted", "Raw"), + selectedIndex = if (showRaw) 1 else 0, + onSelect = { index -> onToggle(index == 1) }, + modifier = if (compact) modifier else modifier.padding(horizontal = 16.dp, vertical = 8.dp), ) } @@ -276,8 +403,23 @@ private fun JsonTreeRowView( } else { Spacer(Modifier.width(JsonTreeChevronSlot)) } - row.keyLabel?.let { key -> JsonTreeMono("${key.jsonQuoted()}: ", colors.jsonKey, fontSize, lineHeight) } - JsonTreeValueSpan(row.content, row.depth, colors, fontSize, lineHeight) + row.keyLabel?.let { key -> + JsonTreeMono( + text = "${key.jsonQuoted()}: ", + color = colors.jsonKey, + fontSize = fontSize, + lineHeight = lineHeight, + highlights = row.searchKeyHighlights, + ) + } + JsonTreeValueSpan( + content = row.content, + depth = row.depth, + colors = colors, + fontSize = fontSize, + lineHeight = lineHeight, + highlights = row.searchValueHighlights, + ) if (row.trailingComma) JsonTreeMono(",", colors.text3, fontSize, lineHeight) } } @@ -289,10 +431,11 @@ private fun JsonTreeValueSpan( colors: DevConsoleColors, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { when (content) { is JsonTreeRowContent.Scalar -> - JsonTreeMono(content.text, content.type.color(colors), fontSize, lineHeight) + JsonTreeMono(content.text, content.type.color(colors), fontSize, lineHeight, highlights) is JsonTreeRowContent.ContainerStart -> JsonTreeMono(if (content.isArray) "[" else "{", colors.jsonBraceAt(depth), fontSize, lineHeight) is JsonTreeRowContent.ContainerEnd -> @@ -327,6 +470,13 @@ private fun JsonTreeMono( color: Color, fontSize: TextUnit, lineHeight: TextUnit, + highlights: List = emptyList(), ) { - Text(text, color = color, fontFamily = FontFamily.Monospace, fontSize = fontSize, lineHeight = lineHeight) + Text( + inspectorHighlightedText(text, highlights, DevConsoleTheme.colors), + color = color, + fontFamily = FontFamily.Monospace, + fontSize = fontSize, + lineHeight = lineHeight, + ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt index ebc495b..ce48adb 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorGlyphs.kt @@ -24,6 +24,7 @@ import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.geometry.Offset @@ -52,6 +53,8 @@ import androidx.compose.ui.unit.sp */ internal enum class InspectorGlyph { Search, ChevronDown, Check, Alert, Flag, Copy, Expand } +/** DESIGN.md's disabled treatment: the whole control at half opacity, container and content alike. */ +private const val DISABLED_PILL_ALPHA = 0.5f private const val GLYPH_VIEWBOX = 16f private const val GLYPH_STROKE_WIDTH = 1.4f @@ -172,6 +175,7 @@ internal fun InspectorRoundIconButton( onClick: () -> Unit, modifier: Modifier = Modifier, size: Dp = 48.dp, + enabled: Boolean = true, containerColor: Color = Color.Transparent, icon: @Composable () -> Unit, ) { @@ -180,9 +184,10 @@ internal fun InspectorRoundIconButton( modifier .minimumInteractiveComponentSize() .size(size) + .alpha(if (enabled) 1f else DISABLED_PILL_ALPHA) .clip(CircleShape) .background(containerColor) - .clickable(onClick = onClick, role = Role.Button) + .clickable(enabled = enabled, onClick = onClick, role = Role.Button) .semantics { this.contentDescription = contentDescription }, contentAlignment = Alignment.Center, ) { icon() } @@ -193,9 +198,8 @@ internal fun InspectorRoundIconButton( * [outlined] swaps the filled [containerColor] for a hairline border on transparent -- the "demoted, * can never succeed" affordance (e.g. the push detail's Replay button) that * still reads as a button but no longer competes visually with a real primary action. [enabled] - * disables the click target too; a caller that passes `enabled = false` is expected to also dim - * [contentColor]/the icon's own tint itself, since this composable never overrides a caller-chosen - * color. + * disables the click target and dims the whole pill to the design system's 0.5 disabled opacity, so + * a gated action never looks like it will still work. */ @Suppress("LongParameterList") // Colors/icon vary per call site (hero CTA vs. footer actions). @Composable @@ -218,6 +222,7 @@ internal fun InspectorPillButton( modifier = modifier .heightIn(min = 48.dp) + .alpha(if (enabled) 1f else DISABLED_PILL_ALPHA) .clip(RoundedCornerShape(50)) .then(outlineModifier) .background(resolvedContainer) diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt new file mode 100644 index 0000000..8d46311 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonSearchCandidates.kt @@ -0,0 +1,72 @@ +/** + * @author Shakib + * @since 18/08/26 + */ +package io.devconsole.ui.compose + +internal fun jsonSearchCandidates( + sectionKey: String, + root: JsonValue, +): List = + buildList { + appendJsonSearchCandidates(this, sectionKey, root, path = "$") + } + +private fun appendJsonSearchCandidates( + candidates: MutableList, + sectionKey: String, + value: JsonValue, + path: String, +) { + when (value) { + is JsonValue.Obj -> + value.entries.forEachIndexed { index, (key, child) -> + val childPath = "$path/$index:$key" + candidates += + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = childPath, + field = InspectorSearchField.KEY, + text = key.jsonQuoted(), + path = childPath, + ancestorPaths = jsonAncestorPaths(childPath), + ) + appendJsonSearchCandidates(candidates, sectionKey, child, childPath) + } + is JsonValue.Arr -> + value.items.forEachIndexed { index, child -> + appendJsonSearchCandidates(candidates, sectionKey, child, "$path[$index]") + } + is JsonValue.Str -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.value.jsonQuoted()) + is JsonValue.Num -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.raw) + is JsonValue.Bool -> candidates += jsonLeafSearchCandidate(sectionKey, path, value.value.toString()) + JsonValue.Null -> candidates += jsonLeafSearchCandidate(sectionKey, path, "null") + } +} + +/** Builds a VALUE candidate for a JSON scalar leaf at [path]. */ +private fun jsonLeafSearchCandidate( + sectionKey: String, + path: String, + text: String, +): InspectorSearchCandidate = + InspectorSearchCandidate( + sectionKey = sectionKey, + itemId = path, + field = InspectorSearchField.VALUE, + text = text, + path = path, + ancestorPaths = jsonAncestorPaths(path), + ) + +private fun jsonAncestorPaths(path: String): List { + if (path == "$") return emptyList() + val ancestors = mutableListOf() + var cursor = path + while (cursor != "$") { + val separator = maxOf(cursor.lastIndexOf('/'), cursor.lastIndexOf('[')) + cursor = if (separator <= 0) "$" else cursor.substring(0, separator) + ancestors += cursor + } + return ancestors.asReversed() +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt index d25749e..37c07df 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorKeyValueList.kt @@ -3,6 +3,7 @@ * @since 04/08/26 */ @file:Suppress("FunctionNaming", "MagicNumber", "MatchingDeclarationName") +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) package io.devconsole.ui.compose @@ -10,8 +11,12 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.geometry.Offset @@ -35,25 +40,53 @@ internal data class InspectorKeyValue( internal fun InspectorKeyValueList( entries: List, modifier: Modifier = Modifier, + sectionKey: String = "", + searchMatches: List = emptyList(), + currentMatchOrdinal: Int? = null, ) { val colors = DevConsoleTheme.colors val lineColor = colors.line + val sectionMatches = searchMatches.filter { it.sectionKey == sectionKey || sectionKey.isEmpty() } + val highlightIndex = + remember(sectionMatches, currentMatchOrdinal) { + indexInspectorSearchHighlights(sectionMatches, currentMatchOrdinal) + } // No top inset on this padding, so the first divider sits flush under the section header // instead of 8dp below it. Column(modifier = modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 8.dp)) { - entries.forEach { entry -> + entries.forEachIndexed { index, entry -> + val itemId = "row:$index" + val bringIntoViewRequester = remember { BringIntoViewRequester() } + val isActive = sectionMatches.any { it.ordinal == currentMatchOrdinal && it.itemId == itemId } + LaunchedEffect(isActive, currentMatchOrdinal) { + if (isActive) bringIntoViewRequester.bringIntoView() + } Column( modifier = Modifier .fillMaxWidth() + .bringIntoViewRequester(bringIntoViewRequester) .drawBehind { drawLine(lineColor, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) }.padding(vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text(entry.key, color = colors.jsonKey, fontFamily = FontFamily.Monospace, fontSize = 12.sp) Text( - entry.value, + inspectorHighlightedText( + text = entry.key, + highlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.KEY), + colors = colors, + ), + color = colors.jsonKey, + fontFamily = FontFamily.Monospace, + fontSize = 12.sp, + ) + Text( + inspectorHighlightedText( + text = entry.value, + highlights = highlightIndex.highlightsFor(itemId, InspectorSearchField.VALUE), + colors = colors, + ), color = entry.valueColor ?: colors.ink, fontFamily = FontFamily.Monospace, fontSize = 13.5.sp, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt index 7572511..cf99b64 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorListComponents.kt @@ -9,19 +9,27 @@ package io.devconsole.ui.compose import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.MaterialTheme @@ -33,6 +41,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -250,13 +259,17 @@ internal fun FilterChipRow( chips: List, onChipClick: (InspectorFilterChip) -> Unit, modifier: Modifier = Modifier, + /** Overridable so a caller that already pads its column can align chips to its own margin. */ + contentPadding: PaddingValues = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + /** False for a caller that places the chips beside other controls and must not have the row eat the width. */ + fillWidth: Boolean = true, ) { Row( modifier = modifier - .fillMaxWidth() + .then(if (fillWidth) Modifier.fillMaxWidth() else Modifier) .horizontalScroll(rememberScrollState()) - .padding(horizontal = 16.dp, vertical = 8.dp), + .padding(contentPadding), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { chips.forEach { chip -> InspectorChip(chip, onClick = { onChipClick(chip) }) } @@ -299,3 +312,55 @@ private fun InspectorChip( ), ) } + +/** + * The design system's segmented control (DESIGN.md §Components): one joined 32dp group, 8dp on the + * outer corners and square inside, mono labels, active segment filled with signal. Use it for a + * view switch over 2-3 mutually exclusive representations of the *same* content -- a filter chip + * row says "narrow this set", a segment says "show me this side of it". + */ +@Composable +internal fun InspectorSegmentedControl( + options: List, + selectedIndex: Int, + onSelect: (Int) -> Unit, + modifier: Modifier = Modifier, +) { + val colors = DevConsoleTheme.colors + val shape = RoundedCornerShape(8.dp) + Row( + modifier = + modifier + .height(32.dp) + .clip(shape) + .border(1.dp, colors.line, shape) + .semantics { role = Role.RadioButton }, + verticalAlignment = Alignment.CenterVertically, + ) { + options.forEachIndexed { index, option -> + val selected = index == selectedIndex + if (index > 0) { + Box(Modifier.fillMaxHeight().width(1.dp).background(colors.line)) + } + Box( + modifier = + Modifier + .fillMaxHeight() + .widthIn(min = 42.dp) + .background(if (selected) colors.signal else Color.Transparent) + .selectable(selected = selected, role = Role.RadioButton) { onSelect(index) } + .padding(horizontal = 12.dp), + contentAlignment = Alignment.Center, + ) { + Text( + option, + color = if (selected) colors.signalInk else colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 11.5.sp, + fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium, + maxLines = 1, + ) + } + } + } +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt index 875f55b..8a4eeaf 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt @@ -399,13 +399,13 @@ private fun ServerControlCard( fontWeight = FontWeight.SemiBold, ) Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + // No per-state color swaps: InspectorPillButton owns the disabled treatment now, and + // dimming an already-muted color twice pushed these below the contrast floor. InspectorPillButton( label = "Start server", onClick = { onSetServerRunning(true) }, modifier = Modifier.weight(1f), enabled = !running, - containerColor = if (running) colors.panel else colors.signal, - contentColor = if (running) colors.muted else colors.signalInk, ) InspectorPillButton( label = "Stop", @@ -413,7 +413,7 @@ private fun ServerControlCard( modifier = Modifier.weight(1f), enabled = running, outlined = true, - contentColor = if (running) colors.ink else colors.muted, + contentColor = colors.ink, ) } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt index 836ec04..74af394 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveDetail.kt @@ -11,6 +11,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateMapOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember @@ -93,6 +94,7 @@ private data class ResolvedDetailSection( val metaColor: Color, val body: InspectorDetailSectionBody?, val emptyMessage: String?, + val searchMatches: List = emptyList(), ) private fun matchesQuery( @@ -208,10 +210,269 @@ private fun resolveDetailSection( ) } +/** The per-section slice of the screen's search state that [resolveNetworkDetailSection] reads. */ +internal data class NetworkSectionSearch( + val query: String, + val matches: List, + val searchable: Boolean, +) { + val hasQuery: Boolean get() = query.trim().isNotEmpty() + + val showsMatchCount: Boolean get() = hasQuery && searchable +} + +internal fun networkSectionMeta( + search: NetworkSectionSearch, + expanded: Boolean, + total: Int, +): String = + when { + search.showsMatchCount && search.matches.isEmpty() -> "no match" + search.showsMatchCount -> "${search.matches.size} match${if (search.matches.size == 1) "" else "es"}" + total == 0 -> "" + expanded -> total.toString() + else -> "$total line${if (total == 1) "" else "s"}" + } + +/** Network detail resolver: preserves every original body shape and decorates it with match metadata. */ +private fun resolveNetworkDetailSection( + spec: InspectorDetailSectionSpec, + search: NetworkSectionSearch, + openState: Map, + colors: DevConsoleColors, +): ResolvedDetailSection { + val expanded = if (search.hasQuery && search.matches.isNotEmpty()) true else openState[spec.key] == true + val emptyMessage = if (expanded) (spec.body as? InspectorDetailSectionBody.Empty)?.text else null + return ResolvedDetailSection( + expanded = expanded, + hits = search.matches.size, + meta = networkSectionMeta(search, expanded, detailBodyItemCount(spec.body)), + metaColor = if (search.showsMatchCount && search.matches.isNotEmpty()) colors.signal else colors.text3, + body = if (expanded && emptyMessage == null) spec.body else null, + emptyMessage = emptyMessage, + searchMatches = search.matches, + ) +} + +/** Everything the detail screen derives from the active query, resolved once per recomposition. */ +private data class ObserveDetailSearch( + val matches: List, + val activeMatchOrdinal: Int, + val resolved: List>, + val totalHits: Int, +) + +@Composable +private fun rememberObserveDetailSearch( + sections: List, + searchableSectionBodies: List, + searchableSectionKeys: Set, + rawSectionKeys: Set, + selectedKeys: Set, + searchMode: InspectorSearchMode, + query: String, + searching: Boolean, + currentMatchOrdinal: Int, + openState: Map, + colors: DevConsoleColors, +): ObserveDetailSearch { + val hasQuery = searching && query.isNotBlank() + val candidates = + remember(searchableSectionBodies, rawSectionKeys, hasQuery) { + inspectorSearchCandidatesFor(searchableSectionBodies, hasQuery) { sectionKey -> + bodySearchRepresentation(sectionKey in rawSectionKeys) + } + } + val matches = + remember(candidates, query, selectedKeys, searchMode, hasQuery) { + if (hasQuery) searchInspectorCandidates(candidates, query, selectedKeys, searchMode) else emptyList() + } + val activeMatchOrdinal = if (matches.isEmpty()) 0 else currentMatchOrdinal.coerceIn(0, matches.lastIndex) + val resolved = + sections.map { spec -> + val resolvedSection = + if (searching) { + resolveNetworkDetailSection( + spec = spec, + search = + NetworkSectionSearch( + query = query, + matches = matches.filter { it.sectionKey == spec.key }, + searchable = spec.key in searchableSectionKeys, + ), + openState = openState, + colors = colors, + ) + } else { + resolveDetailSection(spec, query, openState, colors) + } + spec to resolvedSection + } + return ObserveDetailSearch( + matches = matches, + activeMatchOrdinal = activeMatchOrdinal, + resolved = resolved, + totalHits = if (searching) matches.size else resolved.sumOf { (_, section) -> section.hits }, + ) +} + +/** + * Collects the searchable bodies' candidates, short-circuiting before any body is walked when there + * is no query to match. + */ +internal fun inspectorSearchCandidatesFor( + sections: List, + hasQuery: Boolean, + representationForSection: (String) -> InspectorBodySearchRepresentation, +): List { + if (!hasQuery) return emptyList() + return sections.flatMap { section -> + searchInspectorBodyCandidates( + sectionKey = section.sectionKey, + body = section.body, + representation = representationForSection(section.sectionKey), + ) + } +} + +private fun bodySearchRepresentation(raw: Boolean): InspectorBodySearchRepresentation = + if (raw) InspectorBodySearchRepresentation.RAW else InspectorBodySearchRepresentation.FORMATTED + +/** The find field plus its match counter, stepping arrows, and scope chip. */ +@Composable +private fun ObserveDetailSearchBar( + query: String, + onQueryChange: (String) -> Unit, + searching: Boolean, + matchCount: Int, + activeMatchOrdinal: Int, + totalHits: Int, + onOrdinalChange: (Int) -> Unit, + onOpenOptions: () -> Unit, + scopeLabel: String?, + placeholder: String, + modifier: Modifier = Modifier, +) { + InspectorDetailSearchField( + query = query, + onQueryChange = onQueryChange, + matchLabel = detailSearchMatchLabel(query, searching, matchCount, activeMatchOrdinal, totalHits), + onPrevious = + if (searching) { + { onOrdinalChange(previousInspectorMatchIndex(activeMatchOrdinal, matchCount)) } + } else { + null + }, + onNext = + if (searching) { + { onOrdinalChange(nextInspectorMatchIndex(activeMatchOrdinal, matchCount)) } + } else { + null + }, + navigationEnabled = matchCount > 0, + onOpenOptions = if (searching) onOpenOptions else null, + scopeLabel = scopeLabel, + modifier = modifier, + placeholder = placeholder, + ) +} + +/** The Raw/Formatted toggle only exists on kinds that carry search options. */ +private fun formattableShowRaw( + spec: InspectorDetailSectionSpec, + searching: Boolean, + rawSectionKeys: Set, +): Boolean? = + (spec.body as? InspectorDetailSectionBody.Formattable) + ?.takeIf { searching } + ?.let { body -> body.formatted == null || spec.key in rawSectionKeys } + +/** The section keys a kind declares as searchable; empty for kinds with no search options. */ +private fun InspectorDetailSearchOptions?.searchableSectionKeys(): Set = + this?.sections?.mapTo(mutableSetOf()) { it.key }.orEmpty() + +private fun toggledRawSectionKeys( + current: List, + key: String, + showRaw: Boolean, +): List = if (showRaw) (current + key).distinct() else current.filterNot { it == key } + +/** Only these two body shapes have a full-screen reader. */ +private fun InspectorDetailSectionBody?.isFullScreenCapable(): Boolean = + this is InspectorDetailSectionBody.Code || this is InspectorDetailSectionBody.Formattable + +internal fun detailSearchMatchLabel( + query: String, + searching: Boolean, + matchCount: Int, + activeMatchOrdinal: Int, + totalHits: Int, +): String = + when { + query.isBlank() -> "" + searching -> "${if (matchCount == 0) 0 else activeMatchOrdinal + 1}/$totalHits" + else -> "$totalHits match${if (totalHits == 1) "" else "es"}" + } + +/** The full-screen reader for whichever section the user expanded, per its body shape. */ +@Composable +private fun ObserveDetailFullScreenOverlay( + spec: InspectorDetailSectionSpec, + section: ResolvedDetailSection, + showRaw: Boolean?, + onShowRawChange: ((Boolean) -> Unit)?, + activeMatchOrdinal: Int, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + val copyDescription = spec.copyDescription ?: "Copy ${spec.label}" + when (val body = section.body) { + is InspectorDetailSectionBody.Code -> + InspectorCodeFullScreenOverlay( + title = spec.label, + lines = body.lines, + onDismiss = onDismiss, + modifier = modifier, + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = copyDescription, + ) + is InspectorDetailSectionBody.Formattable -> + InspectorFormattableFullScreenOverlay( + title = spec.label, + body = body, + onDismiss = onDismiss, + showRaw = showRaw, + onShowRawChange = onShowRawChange, + modifier = modifier, + sectionKey = spec.key, + searchMatches = section.searchMatches, + currentMatchOrdinal = activeMatchOrdinal, + onCopy = spec.onCopy, + copyContentDescription = copyDescription, + ) + else -> Unit + } +} + +private fun detailBodyItemCount(body: InspectorDetailSectionBody): Int = + when (body) { + is InspectorDetailSectionBody.KeyValues -> body.entries.size + is InspectorDetailSectionBody.Code -> body.lines.size + is InspectorDetailSectionBody.Formattable -> body.rawLines.size + is InspectorDetailSectionBody.Bars -> body.stats.size + is InspectorDetailSectionBody.Empty -> 0 + } + @Composable private fun InspectorDetailSectionCard( spec: InspectorDetailSectionSpec, resolved: ResolvedDetailSection, + currentMatchOrdinal: Int?, + formattableShowRaw: Boolean?, + onFormattableShowRawChange: ((Boolean) -> Unit)?, onToggle: () -> Unit, onExpandCodeFullScreen: (String) -> Unit, ) { @@ -232,11 +493,31 @@ private fun InspectorDetailSectionCard( emptyMessage != null -> InspectorDetailEmptyText(emptyMessage) else -> when (val body = resolved.body) { - is InspectorDetailSectionBody.KeyValues -> InspectorKeyValueList(body.entries) + is InspectorDetailSectionBody.KeyValues -> + InspectorKeyValueList( + entries = body.entries, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + ) is InspectorDetailSectionBody.Code -> - InspectorCodeBlock(body.lines, onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }) + InspectorCodeBlock( + lines = body.lines, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }, + ) is InspectorDetailSectionBody.Formattable -> - InspectorFormattableBody(body, onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }) + InspectorFormattableBody( + body = body, + showRaw = formattableShowRaw, + onShowRawChange = onFormattableShowRawChange, + sectionKey = spec.key, + searchMatches = resolved.searchMatches, + currentMatchOrdinal = currentMatchOrdinal, + onExpandFullScreen = { onExpandCodeFullScreen(spec.key) }, + ) is InspectorDetailSectionBody.Bars -> InspectorProgressBars(body.stats) is InspectorDetailSectionBody.Empty, null -> InspectorDetailEmptyText("Nothing captured.") } @@ -250,10 +531,7 @@ private fun InspectorDetailSectionCard( * action bar. [resetKey] identifies which capture is open (e.g. a transaction id) so the find query * and each section's manual open/closed state reset when a different capture is opened. Both the * header's back button and the system back gesture close it via [onBack]. - * - * LongMethod: the full-screen code overlay branch pushed this a couple lines past the default budget. */ -@Suppress("LongParameterList", "LongMethod") @Composable internal fun InspectorObserveDetailScreen( resetKey: Any, @@ -264,15 +542,59 @@ internal fun InspectorObserveDetailScreen( onBack: () -> Unit, modifier: Modifier = Modifier, searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, + searchOptions: InspectorDetailSearchOptions? = null, ) { var query by rememberSaveable(resetKey) { mutableStateOf("") } + var selectedSectionKeys by + rememberSaveable(resetKey) { + mutableStateOf(searchOptions?.defaultSectionKeys?.toList().orEmpty()) + } + // Enums are Serializable, so the mode survives process death without a name round-trip. + var searchMode by + rememberSaveable(resetKey) { + mutableStateOf(searchOptions?.defaultMode ?: InspectorSearchMode.KEYS_AND_VALUES) + } + var currentMatchOrdinal by rememberSaveable(resetKey) { mutableIntStateOf(0) } + var rawFormattableSectionKeys by rememberSaveable(resetKey) { mutableStateOf(emptyList()) } + var searchOptionsVisible by remember(resetKey) { mutableStateOf(false) } val openState = remember(resetKey) { mutableStateMapOf().apply { initiallyOpenSectionKeys.forEach { key -> this[key] = true } } } val colors = DevConsoleTheme.colors - val resolved = sections.map { spec -> spec to resolveDetailSection(spec, query, openState, colors) } - val totalHits = resolved.sumOf { (_, section) -> section.hits } + val selectedKeys = remember(selectedSectionKeys) { selectedSectionKeys.toSet() } + val rawSectionKeys = remember(rawFormattableSectionKeys) { rawFormattableSectionKeys.toSet() } + val searchableSectionKeys = remember(searchOptions) { searchOptions.searchableSectionKeys() } + val searchableSectionBodies = inspectorSearchSectionBodies(sections, searchableSectionKeys) + val searching = searchOptions != null + // Formattable bodies only offer the raw/formatted toggle on the kinds that carry search options. + val onShowRawChange: ((String, Boolean) -> Unit)? = + if (searching) { + { key, showRaw -> + rawFormattableSectionKeys = toggledRawSectionKeys(rawFormattableSectionKeys, key, showRaw) + currentMatchOrdinal = 0 + } + } else { + null + } + val search = + rememberObserveDetailSearch( + sections = sections, + searchableSectionBodies = searchableSectionBodies, + searchableSectionKeys = searchableSectionKeys, + rawSectionKeys = rawSectionKeys, + selectedKeys = selectedKeys, + searchMode = searchMode, + query = query, + searching = searching, + currentMatchOrdinal = currentMatchOrdinal, + openState = openState, + colors = colors, + ) + val networkMatches = search.matches + val activeMatchOrdinal = search.activeMatchOrdinal + val resolved = search.resolved + val totalHits = search.totalHits // Which section's code block (if any) is showing full-screen. // Bundle-safe on its own (a String key), and the lines it needs are re-derived from `resolved` @@ -286,27 +608,18 @@ internal fun InspectorObserveDetailScreen( BackHandler(onBack = onBack) - if (fullScreenSection != null) { + if (fullScreenSection != null && fullScreenSection.second.body.isFullScreenCapable()) { val (spec, section) = fullScreenSection - val body = section.body - if (body is InspectorDetailSectionBody.Code) { - InspectorCodeFullScreenOverlay( - title = spec.label, - lines = body.lines, - onDismiss = { fullScreenSectionKey = null }, - modifier = modifier.fillMaxSize(), - ) - return - } - if (body is InspectorDetailSectionBody.Formattable) { - InspectorFormattableFullScreenOverlay( - title = spec.label, - body = body, - onDismiss = { fullScreenSectionKey = null }, - modifier = modifier.fillMaxSize(), - ) - return - } + ObserveDetailFullScreenOverlay( + spec = spec, + section = section, + showRaw = formattableShowRaw(spec, searching, rawSectionKeys), + onShowRawChange = onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, + activeMatchOrdinal = activeMatchOrdinal, + onDismiss = { fullScreenSectionKey = null }, + modifier = modifier.fillMaxSize(), + ) + return } InspectorDetailScaffold( @@ -324,12 +637,21 @@ internal fun InspectorObserveDetailScreen( onBack = onBack, actions = header.actions, ) - InspectorDetailSearchField( + ObserveDetailSearchBar( query = query, - onQueryChange = { query = it }, - matchLabel = if (query.isBlank()) "" else "$totalHits match${if (totalHits == 1) "" else "es"}", - modifier = Modifier.padding(top = 12.dp), + onQueryChange = { + query = it + currentMatchOrdinal = 0 + }, + searching = searching, + matchCount = networkMatches.size, + activeMatchOrdinal = activeMatchOrdinal, + totalHits = totalHits, + onOrdinalChange = { currentMatchOrdinal = it }, + onOpenOptions = { searchOptionsVisible = true }, + scopeLabel = searchOptions?.let { inspectorSearchScopeSummary(it, selectedKeys) }, placeholder = searchPlaceholder, + modifier = Modifier.padding(top = 12.dp), ) }, footer = { InspectorDetailFooterBar(footerActions) }, @@ -338,11 +660,46 @@ internal fun InspectorObserveDetailScreen( InspectorDetailSectionCard( spec = spec, resolved = section, + currentMatchOrdinal = if (searching) activeMatchOrdinal else null, + formattableShowRaw = formattableShowRaw(spec, searching, rawSectionKeys), + onFormattableShowRawChange = + onShowRawChange?.let { change -> { showRaw -> change(spec.key, showRaw) } }, onToggle = { openState[spec.key] = !section.expanded }, onExpandCodeFullScreen = { key -> fullScreenSectionKey = key }, ) } } + ObserveDetailSearchOptionsSheet( + options = searchOptions.takeIf { searchOptionsVisible }, + selectedSectionKeys = selectedKeys, + mode = searchMode, + onDismiss = { searchOptionsVisible = false }, + onApply = { newKeys, newMode -> + selectedSectionKeys = newKeys.toList() + searchMode = newMode + currentMatchOrdinal = 0 + searchOptionsVisible = false + }, + ) +} + +/** Renders the scope/mode sheet only while [options] is non-null, i.e. while the chip has it open. */ +@Composable +private fun ObserveDetailSearchOptionsSheet( + options: InspectorDetailSearchOptions?, + selectedSectionKeys: Set, + mode: InspectorSearchMode, + onDismiss: () -> Unit, + onApply: (Set, InspectorSearchMode) -> Unit, +) { + if (options == null) return + InspectorDetailSearchOptionsSheet( + options = options, + selectedSectionKeys = selectedSectionKeys, + mode = mode, + onDismiss = onDismiss, + onApply = onApply, + ) } /** Everything [InspectorObserveDetailScreen] needs for one capture, built by the per-kind `*DetailContent` builders. */ @@ -357,6 +714,7 @@ internal data class ObserveDetailContent( * one value, and offering to search its "headers" would be describing a screen that isn't there. */ val searchPlaceholder: String = DEFAULT_DETAIL_SEARCH_PLACEHOLDER, + val searchOptions: InspectorDetailSearchOptions? = null, ) /** Matches [InspectorDetailSearchField]'s own default; named here so callers can opt out of it. */ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt index 4dbe01e..78bced1 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveFrameDetail.kt @@ -83,7 +83,7 @@ private fun frameSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), textPreviewSection( - key = "req", + key = InspectorExchangeSection.PRIMARY_BODY.key, label = "Payload", preview = frame.preview, isBinaryPlaceholder = false, @@ -93,7 +93,7 @@ private fun frameSections( copyDescription = "Copy payload", ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Connection", InspectorDetailSectionBody.KeyValues(connectionEntries), copyDescription = "Copy connection info", @@ -177,7 +177,7 @@ internal fun frameDetailContent( ), ), sections = frameSections(socket, frame, colors, sizeLabel, copyText), - initiallyOpenSectionKeys = setOf("req"), + initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), footerActions = frameFooterActions(socket, frame, colors, copyText, shareText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt index ca4973c..7905a78 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveLogDetail.kt @@ -47,14 +47,14 @@ private fun logSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Context", contextBody, copyDescription = "Copy context", onCopy = contextCopy, ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Related transaction", InspectorDetailSectionBody.Empty("This event is not linked to a transaction."), ), diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt index 99a2019..c08a686 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveNetDetail.kt @@ -203,7 +203,7 @@ private fun netBodySections( } return listOf( textPreviewSection( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Request payload", transaction.requestPreview, requestBinary, @@ -213,7 +213,7 @@ private fun netBodySections( "Copy request payload", ), textPreviewSection( - "res", + InspectorExchangeSection.SECONDARY_BODY.key, "Response body", transaction.responsePreview, isBinaryPlaceholder = false, @@ -249,16 +249,16 @@ private fun netSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "reqh", - "Request headers", + InspectorExchangeSection.PRIMARY_HEADERS.key, + InspectorExchangeSection.PRIMARY_HEADERS.networkLabel, requestHeadersBody, copyDescription = "Copy request headers", onCopy = keyValuesCopyAction(requestHeadersBody.entries, copyText), ), requestSection, InspectorDetailSectionSpec( - "resh", - "Response headers", + InspectorExchangeSection.SECONDARY_HEADERS.key, + InspectorExchangeSection.SECONDARY_HEADERS.networkLabel, responseHeadersBody, copyDescription = "Copy response headers", onCopy = keyValuesCopyAction(responseHeadersBody.entries, copyText), @@ -380,7 +380,8 @@ internal fun netDetailContent( sections = netSections(transaction, colors, statusColor, copyText, mockDiff), // Request payload + Response body both open by default -- // an operator debugging a transaction usually needs to compare both sides at a glance. - initiallyOpenSectionKeys = setOf("req", "res"), + initiallyOpenSectionKeys = InspectorExchangeSection.keysOf(InspectorExchangeSection.defaultSearchScope), footerActions = netFooterActions(transaction, colors, onMockAction, copyText), + searchOptions = NetworkDetailSearchOptions, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt index 2215fbd..528cf20 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObservePushDetail.kt @@ -54,14 +54,14 @@ private fun pushSections( onCopy = { copyText(generalEntries.toCopyText()) }, ), InspectorDetailSectionSpec( - "req", + InspectorExchangeSection.PRIMARY_BODY.key, "Payload", payloadBody, copyDescription = "Copy payload", onCopy = keyValuesCopyAction(payloadEntries.orEmpty(), copyText), ), InspectorDetailSectionSpec( - "resh", + InspectorExchangeSection.SECONDARY_HEADERS.key, "Lifecycle", InspectorDetailSectionBody.KeyValues(lifecycleEntries), copyDescription = "Copy lifecycle info", @@ -143,7 +143,7 @@ internal fun pushDetailContent( ), ), sections = pushSections(push, colors, copyText), - initiallyOpenSectionKeys = setOf("req"), + initiallyOpenSectionKeys = setOf(InspectorExchangeSection.PRIMARY_BODY.key), footerActions = pushFooterActions(colors, payloadText, copyText), ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt index 0fce8aa..926e0b7 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorObserveScreen.kt @@ -828,6 +828,7 @@ private fun ObserveDetailFromContent( footerActions = content.footerActions, onBack = onBack, searchPlaceholder = content.searchPlaceholder, + searchOptions = content.searchOptions, ) } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt new file mode 100644 index 0000000..5ce470b --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorSearchHighlight.kt @@ -0,0 +1,69 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString + +internal data class InspectorSearchHighlight( + val start: Int, + val endExclusive: Int, + val active: Boolean, +) + +internal data class InspectorSearchHighlightTarget( + val itemId: String, + val field: InspectorSearchField, +) + +internal class InspectorSearchHighlightIndex internal constructor( + private val highlights: Map>, +) { + fun highlightsFor( + itemId: String, + field: InspectorSearchField, + ): List = highlights[InspectorSearchHighlightTarget(itemId, field)].orEmpty() +} + +/** Groups matches once so each rendered field can retrieve its spans in constant time. */ +internal fun indexInspectorSearchHighlights( + matches: List, + currentMatchOrdinal: Int?, +): InspectorSearchHighlightIndex { + val indexed = mutableMapOf>() + matches.forEach { match -> + val target = InspectorSearchHighlightTarget(match.itemId, match.field) + indexed.getOrPut(target, ::mutableListOf) += + InspectorSearchHighlight( + start = match.start, + endExclusive = match.endExclusive, + active = match.ordinal == currentMatchOrdinal, + ) + } + return InspectorSearchHighlightIndex(indexed) +} + +internal fun inspectorHighlightedText( + text: String, + highlights: List, + colors: DevConsoleColors, +): AnnotatedString = + buildAnnotatedString { + append(text) + highlights.forEach { highlight -> + val start = highlight.start.coerceIn(0, text.length) + val end = highlight.endExclusive.coerceIn(start, text.length) + if (start < end) { + addStyle( + SpanStyle( + background = if (highlight.active) colors.signal else colors.signalSoft, + ), + start, + end, + ) + } + } + } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt new file mode 100644 index 0000000..a7f396f --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorDetailSearchTest.kt @@ -0,0 +1,248 @@ +/** + * @author Shakib + * @since 17/08/26 + */ +package io.devconsole.ui.compose + +import androidx.compose.ui.graphics.Color +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class InspectorDetailSearchTest { + @Test + fun `keys mode matches keys but not values and keeps exact ranges`() { + val candidates = + listOf( + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.KEY, "Content-Type"), + InspectorSearchCandidate("reqh", "row:0", InspectorSearchField.VALUE, "application/json"), + ) + + val matches = + searchInspectorCandidates( + candidates, + "content", + setOf("reqh"), + InspectorSearchMode.KEYS, + ) + + assertEquals(1, matches.size) + assertEquals(0, matches.single().start) + assertEquals(7, matches.single().endExclusive) + } + + @Test + fun `multi section matching follows candidate order and values mode`() { + val candidates = + listOf( + InspectorSearchCandidate("req", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1"), + InspectorSearchCandidate("general", "row:0", InspectorSearchField.VALUE, "userId: 1"), + ) + + val matches = + searchInspectorCandidates( + candidates, + "userid", + setOf("req", "res"), + InspectorSearchMode.VALUES, + ) + + assertEquals(listOf("req", "res"), matches.map { it.sectionKey }) + assertEquals(listOf(0, 1), matches.map { it.ordinal }) + } + + @Test + fun `previous and next navigation wrap around`() { + assertEquals(0, nextInspectorMatchIndex(current = 2, total = 3)) + assertEquals(2, previousInspectorMatchIndex(current = 0, total = 3)) + assertEquals(0, nextInspectorMatchIndex(current = 0, total = 0)) + assertEquals(0, previousInspectorMatchIndex(current = 0, total = 0)) + } + + @Test + fun `blank query produces no matches`() { + val candidates = + listOf(InspectorSearchCandidate("res", "line:0", InspectorSearchField.VALUE, "userId: 1")) + + assertTrue( + searchInspectorCandidates( + candidates, + " ", + setOf("res"), + InspectorSearchMode.VALUES, + ).isEmpty(), + ) + } + + @Test + fun `key value bodies produce stable row candidates`() { + val body = + InspectorDetailSectionBody.KeyValues( + listOf(InspectorKeyValue("Content-Type", "application/json")), + ) + + val candidates = searchInspectorBodyCandidates("reqh", body) + + assertEquals(listOf(InspectorSearchField.KEY, InspectorSearchField.VALUE), candidates.map { it.field }) + assertEquals(listOf("row:0", "row:0"), candidates.map { it.itemId }) + } + + @Test + fun `nested json candidates retain property path and ancestor paths`() { + val root = MinimalJsonParser("""{"user":{"id":1}}""").parseDocument() + val body = + InspectorDetailSectionBody.Formattable( + rawText = """{"user":{"id":1}}""", + rawLines = listOf(InspectorCodeLine(value = "{\"user\":{\"id\":1}}", valueColor = Color.White)), + formatted = FormattedBody.Json(root), + ) + + val candidates = searchInspectorBodyCandidates("res", body) + val idValue = candidates.firstOrNull { it.path == "$/0:user/0:id" && it.field == InspectorSearchField.VALUE } + + assertNotNull(idValue) + assertEquals(listOf("$", "$/0:user"), idValue!!.ancestorPaths) + assertEquals("1", idValue.text) + } + + @Test + fun `json key and value modes select different fields`() { + val root = MinimalJsonParser("""{"userId":1}""").parseDocument() + val body = + InspectorDetailSectionBody.Formattable( + rawText = """{"userId":1}""", + rawLines = listOf(InspectorCodeLine(value = "{\"userId\":1}", valueColor = Color.White)), + formatted = FormattedBody.Json(root), + ) + val candidates = searchInspectorBodyCandidates("res", body) + + assertEquals( + 1, + searchInspectorCandidates(candidates, "userid", setOf("res"), InspectorSearchMode.KEYS).size, + ) + assertEquals( + 1, + searchInspectorCandidates(candidates, "1", setOf("res"), InspectorSearchMode.VALUES).size, + ) + } + + @Test + fun `raw representation indexes rendered raw lines instead of formatted json nodes`() { + val rawText = """{"userId":1}""" + val body = + InspectorDetailSectionBody.Formattable( + rawText = rawText, + rawLines = listOf(InspectorCodeLine(value = rawText, valueColor = Color.White)), + formatted = FormattedBody.Json(MinimalJsonParser(rawText).parseDocument()), + ) + + val rawCandidates = + searchInspectorBodyCandidates( + sectionKey = "res", + body = body, + representation = InspectorBodySearchRepresentation.RAW, + ) + + assertEquals(listOf("line:0"), rawCandidates.map { it.itemId }) + assertEquals(listOf(InspectorSearchField.VALUE), rawCandidates.map { it.field }) + assertEquals(listOf(rawText), rawCandidates.map { it.text }) + assertTrue(rawCandidates.all { it.path == null }) + } + + @Test + fun `blank section query skips body candidate generation`() { + val body = + InspectorDetailSectionBody.Formattable( + rawText = "{}", + rawLines = listOf(InspectorCodeLine(value = "{}", valueColor = Color.White)), + formatted = FormattedBody.Json(MinimalJsonParser("{}").parseDocument()), + ) + var representationRequests = 0 + + val candidates = + inspectorSearchCandidatesFor( + sections = listOf(InspectorSearchSectionBody("res", body)), + hasQuery = " ".isNotBlank(), + ) { + representationRequests++ + InspectorBodySearchRepresentation.FORMATTED + } + + assertTrue(candidates.isEmpty()) + assertEquals(0, representationRequests) + } + + @Test + fun `candidate cache input ignores changing section callbacks`() { + val body = InspectorDetailSectionBody.Code(listOf(InspectorCodeLine(value = "ok", valueColor = Color.White))) + val first = listOf(InspectorDetailSectionSpec("res", "Response", body, onCopy = {})) + val second = listOf(InspectorDetailSectionSpec("res", "Response", body, onCopy = {})) + + assertTrue(first != second) + assertEquals( + inspectorSearchSectionBodies(first, setOf("res")), + inspectorSearchSectionBodies(second, setOf("res")), + ) + } + + @Test + fun `highlight index groups targets and marks only active occurrence`() { + val matches = + listOf( + InspectorDetailSearchMatch(0, "res", "$/0:name", InspectorSearchField.KEY, 1, 5), + InspectorDetailSearchMatch(1, "res", "$/0:name", InspectorSearchField.KEY, 8, 12), + InspectorDetailSearchMatch(2, "res", "$/0:name", InspectorSearchField.VALUE, 0, 4), + ) + + val index = indexInspectorSearchHighlights(matches, currentMatchOrdinal = 1) + + assertEquals(2, index.highlightsFor("$/0:name", InspectorSearchField.KEY).size) + assertEquals(listOf(false, true), index.highlightsFor("$/0:name", InspectorSearchField.KEY).map { it.active }) + assertEquals(1, index.highlightsFor("$/0:name", InspectorSearchField.VALUE).size) + } + + @Test + fun `active line index resolves the full screen scroll target`() { + val matches = + listOf( + InspectorDetailSearchMatch(0, "res", "line:2", InspectorSearchField.VALUE, 0, 3), + InspectorDetailSearchMatch(1, "res", "line:42", InspectorSearchField.VALUE, 4, 7), + ) + + assertEquals(42, activeInspectorLineIndex(matches, currentMatchOrdinal = 1)) + assertEquals(null, activeInspectorLineIndex(matches, currentMatchOrdinal = 5)) + } + + @Test + fun `scope summary reflects multi section selection`() { + assertEquals( + "All sections", + inspectorSearchScopeSummary( + NetworkDetailSearchOptions, + NetworkDetailSearchOptions.sections.mapTo(mutableSetOf()) { it.key }, + ), + ) + assertEquals( + "Response body", + inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf(InspectorExchangeSection.SECONDARY_BODY.key)), + ) + assertEquals("2 sections", inspectorSearchScopeSummary(NetworkDetailSearchOptions, setOf("reqh", "res"))) + assertEquals("Nothing selected", inspectorSearchScopeSummary(NetworkDetailSearchOptions, emptySet())) + } + + @Test + fun `network search defaults to the two bodies and to keys plus values`() { + assertEquals( + InspectorExchangeSection.keysOf( + setOf( + InspectorExchangeSection.PRIMARY_BODY, + InspectorExchangeSection.SECONDARY_BODY, + ), + ), + NetworkDetailSearchOptions.defaultSectionKeys, + ) + assertEquals(InspectorSearchMode.KEYS_AND_VALUES, NetworkDetailSearchOptions.defaultMode) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt new file mode 100644 index 0000000..e4a8f50 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorObserveDetailMetaTest.kt @@ -0,0 +1,81 @@ +/** + * @author Shakib + * @since 18/08/26 + */ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * Locks the section-meta and match-label strings that the detail screen shows, so the extraction + * that split them out of InspectorObserveDetailScreen cannot drift. + */ +class InspectorObserveDetailMetaTest { + private fun search( + query: String = "id", + matchCount: Int = 0, + searchable: Boolean = true, + ) = NetworkSectionSearch( + query = query, + matches = + List(matchCount) { index -> + InspectorDetailSearchMatch( + ordinal = index, + sectionKey = "body", + itemId = "item$index", + field = InspectorSearchField.VALUE, + start = 0, + endExclusive = 1, + ) + }, + searchable = searchable, + ) + + @Test + fun `a searchable section with an active query reports its match count`() { + assertEquals("1 match", networkSectionMeta(search(matchCount = 1), expanded = true, total = 9)) + assertEquals("3 matches", networkSectionMeta(search(matchCount = 3), expanded = true, total = 9)) + assertEquals("no match", networkSectionMeta(search(matchCount = 0), expanded = true, total = 9)) + } + + @Test + fun `a section outside the search scope falls back to its line count`() { + val outOfScope = search(matchCount = 0, searchable = false) + assertEquals("4", networkSectionMeta(outOfScope, expanded = true, total = 4)) + assertEquals("4 lines", networkSectionMeta(outOfScope, expanded = false, total = 4)) + assertEquals("1 line", networkSectionMeta(outOfScope, expanded = false, total = 1)) + } + + /** An empty body reports nothing at all, expanded or not -- never "0" or "0 lines". */ + @Test + fun `an empty section reports no meta in either state`() { + val blank = search(query = "", searchable = false) + assertEquals("", networkSectionMeta(blank, expanded = true, total = 0)) + assertEquals("", networkSectionMeta(blank, expanded = false, total = 0)) + } + + @Test + fun `the match label counts hits on plain kinds and steps through them on searchable ones`() { + assertEquals( + "", + detailSearchMatchLabel("", searching = true, matchCount = 5, activeMatchOrdinal = 0, totalHits = 5), + ) + assertEquals( + "3/17", + detailSearchMatchLabel("id", searching = true, matchCount = 17, activeMatchOrdinal = 2, totalHits = 17), + ) + assertEquals( + "0/0", + detailSearchMatchLabel("id", searching = true, matchCount = 0, activeMatchOrdinal = 0, totalHits = 0), + ) + assertEquals( + "1 match", + detailSearchMatchLabel("id", searching = false, matchCount = 0, activeMatchOrdinal = 0, totalHits = 1), + ) + assertEquals( + "2 matches", + detailSearchMatchLabel("id", searching = false, matchCount = 0, activeMatchOrdinal = 0, totalHits = 2), + ) + } +} diff --git a/update.py b/update.py deleted file mode 100644 index c2bad70..0000000 --- a/update.py +++ /dev/null @@ -1,14 +0,0 @@ -import re -import os - -html_path = 'sdk/server-ktor/src/main/resources/devconsole-web/index.html' -css_path = 'sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css' - -with open(html_path, 'r') as f: - html = f.read() - -# Replace metrics-strip with metric-strip -html = html.replace('metrics-strip', 'metric-strip') - -with open(html_path, 'w') as f: - f.write(html)