From 6450bb51a46199516e77cb4eb449979d2d0cf2f3 Mon Sep 17 00:00:00 2001 From: Johny Date: Sun, 23 Aug 2026 18:51:35 +0600 Subject: [PATCH 1/3] tweak ui on compose part --- .../ui/compose/InspectorJsonHighlight.kt | 187 +++++++++ .../ui/compose/InspectorJsonModel.kt | 4 +- .../ui/compose/InspectorMockRuleBodyFormat.kt | 27 +- .../ui/compose/InspectorMockRuleEditor.kt | 385 ++++++++++++++---- .../ui/compose/InspectorTextField.kt | 43 ++ .../ui/compose/InspectorJsonHighlightTest.kt | 73 ++++ .../InspectorMockRuleBodyFormatTest.kt | 45 ++ 7 files changed, 676 insertions(+), 88 deletions(-) create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonHighlight.kt create mode 100644 sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorJsonHighlightTest.kt diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonHighlight.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonHighlight.kt new file mode 100644 index 0000000..a3dbdf6 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonHighlight.kt @@ -0,0 +1,187 @@ +/** + * @author Shakib + * @since 23/08/26 + * + * Syntax colouring for *editable* JSON. The viewer side ([InspectorFormattableBody]) colours parsed + * rows via [MinimalJsonParser], which is no use in a text field: half-typed JSON doesn't parse, and + * a field that loses its colours on every keystroke is worse than one with none. So this is a + * forgiving lexer over raw text -- unterminated strings, trailing commas and garbage all just stop + * a span instead of failing -- reusing the same [DevConsoleColors] JSON palette as the viewer. + */ +@file:Suppress("MagicNumber") + +package io.devconsole.ui.compose + +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.buildAnnotatedString +import androidx.compose.ui.text.input.OffsetMapping +import androidx.compose.ui.text.input.TransformedText +import androidx.compose.ui.text.input.VisualTransformation + +internal enum class JsonTokenType { KEY, STRING, NUMBER, BOOLEAN, NULL, BRACE, PUNCT } + +/** [start], [end] are indices into the lexed text; [depth] is the nesting rung, only set for [JsonTokenType.BRACE]. */ +internal data class JsonTokenSpan( + val start: Int, + val end: Int, + val type: JsonTokenType, + val depth: Int = 0, +) + +/** Tokenizes [text] far enough to colour it -- never validates, never throws. */ +internal fun jsonHighlightSpans(text: String): List { + val spans = mutableListOf() + var depth = 0 + var i = 0 + while (i < text.length) { + val c = text[i] + val span = + when { + c == '"' -> { + val end = jsonStringEnd(text, i) + // A string is a key only when a ':' follows it -- the one bit of context this lexer keeps. + val type = if (nextNonSpace(text, end) == ':') JsonTokenType.KEY else JsonTokenType.STRING + JsonTokenSpan(i, end, type) + } + c == '{' || c == '[' -> JsonTokenSpan(i, i + 1, JsonTokenType.BRACE, depth++) + // Unbalanced closers (mid-edit) clamp at 0 rather than colouring off the end of the palette. + c == '}' || c == ']' -> { + depth = (depth - 1).coerceAtLeast(0) + JsonTokenSpan(i, i + 1, JsonTokenType.BRACE, depth) + } + c == ':' || c == ',' -> JsonTokenSpan(i, i + 1, JsonTokenType.PUNCT) + else -> jsonScalarSpan(text, i) + } + // No span means whitespace or garbage: skip the char, keep colouring what follows. + i = span?.end ?: (i + 1) + span?.let(spans::add) + } + return spans +} + +/** Number/true/false/null starting exactly at [start], or null when nothing literal begins there. */ +private fun jsonScalarSpan( + text: String, + start: Int, +): JsonTokenSpan? = + when { + text[start] == '-' || text[start].isDigit() -> { + var end = start + 1 + while (end < text.length && (text[end].isDigit() || text[end] in ".eE+-")) end++ + JsonTokenSpan(start, end, JsonTokenType.NUMBER) + } + text.startsWith("true", start) -> JsonTokenSpan(start, start + 4, JsonTokenType.BOOLEAN) + text.startsWith("false", start) -> JsonTokenSpan(start, start + 5, JsonTokenType.BOOLEAN) + text.startsWith("null", start) -> JsonTokenSpan(start, start + 4, JsonTokenType.NULL) + else -> null + } + +/** Index just past the closing quote of the string opening at [start]; end of text when unterminated. */ +private fun jsonStringEnd( + text: String, + start: Int, +): Int { + var i = start + 1 + while (i < text.length) { + when (text[i]) { + '\\' -> i++ + '"' -> return i + 1 + } + i++ + } + return text.length +} + +private fun nextNonSpace( + text: String, + from: Int, +): Char? { + var i = from + while (i < text.length && text[i].isWhitespace()) i++ + return text.getOrNull(i) +} + +private fun JsonTokenSpan.color(colors: DevConsoleColors): Color = + when (type) { + JsonTokenType.KEY -> colors.jsonKey + JsonTokenType.STRING -> colors.jsonString + JsonTokenType.NUMBER -> colors.jsonNumber + JsonTokenType.BOOLEAN -> colors.jsonBoolean + JsonTokenType.NULL -> colors.jsonNull + // Same rainbow-brace cycling as the viewer, so a body reads the same coloured in both places. + JsonTokenType.BRACE -> colors.jsonBraces[depth % colors.jsonBraces.size] + JsonTokenType.PUNCT -> colors.text3 + } + +/** + * Every occurrence of [query] in [text], ignoring case -- keys, values and anything else, because a + * body is as often searched for the value you are about to change as for the key holding it, and a + * plain find keeps working on the non-JSON bodies (HTML, templates) this field also accepts. Blank + * query matches nothing rather than everything; overlapping hits count once (the caller highlights + * ranges, so "aa" in "aaa" is one hit, not two). + */ +internal fun bodySearchMatches( + text: String, + query: String, +): List { + val needle = query.trim() + if (needle.isEmpty()) return emptyList() + val matches = mutableListOf() + var from = text.indexOf(needle, ignoreCase = true) + while (from >= 0) { + matches += from until from + needle.length + from = text.indexOf(needle, from + needle.length, ignoreCase = true) + } + return matches +} + +/** + * Applies [jsonHighlightSpans] to a text field's contents, plus a search wash over every + * [bodySearchMatches] hit for [query]; offsets are untouched, so caret/selection stay put. + */ +internal fun AnnotatedString.jsonHighlighted( + colors: DevConsoleColors, + query: String = "", + activeMatch: IntRange? = null, +): AnnotatedString = + buildAnnotatedString { + append(this@jsonHighlighted) + val raw = this@jsonHighlighted.text + jsonHighlightSpans(raw).forEach { span -> + addStyle(SpanStyle(color = span.color(colors)), span.start, span.end) + } + // Same two-tone wash the read-only viewer paints behind search hits (inspectorHighlightedText): + // solid signal on the one the arrows are parked on, soft on the rest. + bodySearchMatches(raw, query).forEach { match -> + val background = if (match == activeMatch) colors.signal else colors.signalSoft + addStyle(SpanStyle(background = background), match.first, match.last + 1) + } + } + +/** + * JSON colouring for a `BasicTextField`, off past [MAX_AUTO_FORMAT_BODY_CHARS] (see that constant + * for why). Plain text is the graceful degradation: the field still edits and saves, it just stops + * paying to re-colour a body that big. + * + * ponytail: re-lexes the whole body on every keystroke -- fine under the cap (~10ms for 32KB); + * lex only the edited line's neighbourhood if the cap ever needs raising. + */ +@Composable +internal fun rememberJsonSyntaxTransformation( + colors: DevConsoleColors, + query: String = "", + activeMatch: IntRange? = null, +): VisualTransformation = + remember(colors, query, activeMatch) { + VisualTransformation { text -> + if (text.length > MAX_AUTO_FORMAT_BODY_CHARS) { + TransformedText(text, OffsetMapping.Identity) + } else { + TransformedText(text.jsonHighlighted(colors, query, activeMatch), OffsetMapping.Identity) + } + } + } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonModel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonModel.kt index 4bcbf03..51f074c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonModel.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorJsonModel.kt @@ -50,8 +50,10 @@ internal sealed interface JsonValue { data object Null : JsonValue } +/** [offset] is where the parser gave up, so a caller with the text on screen can point at it. */ internal class JsonSyntaxException( message: String, + val offset: Int = 0, ) : Exception(message) /** Pretty-prints with [indentUnit]-per-level indentation (2-space by default, matching every caller). */ @@ -114,7 +116,7 @@ internal class MinimalJsonParser( return value } - private fun fail(message: String): Nothing = throw JsonSyntaxException(message) + private fun fail(message: String): Nothing = throw JsonSyntaxException(message, pos) private fun skipWhitespace() { while (pos < text.length && text[pos].isWhitespace()) pos++ diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormat.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormat.kt index 0ea923e..3aa9478 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormat.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormat.kt @@ -22,6 +22,7 @@ internal sealed interface JsonFormatResult { data class Error( val message: String, + val offset: Int = 0, ) : JsonFormatResult } @@ -37,5 +38,29 @@ internal fun formatMockRuleBodyJson(input: String): JsonFormatResult = val value = MinimalJsonParser(input).parseDocument() JsonFormatResult.Formatted(value.prettyPrint()) } catch (error: JsonSyntaxException) { - JsonFormatResult.Error(error.message ?: "Invalid JSON") + JsonFormatResult.Error(error.message ?: "Invalid JSON", error.offset) + } + +/** + * Ceiling for the *automatic* niceties -- opening pretty-printed and syntax colouring. Both are + * per-keystroke work in a `BasicTextField`, which lays out its whole string in one un-virtualized + * text node: a 512KB capture preview (the default `responseBodyPreviewBytes`) pretty-prints to well + * over a megabyte and tens of thousands of spans, which janks the field for a body nobody hand-edits + * anyway. Above this the body opens exactly as captured, uncoloured. The FORMAT button is + * deliberately *not* capped -- that one the user asked for. + */ +internal const val MAX_AUTO_FORMAT_BODY_CHARS = 32 * 1024 + +/** + * [formatMockRuleBodyJson] for display: pretty JSON when it parses, the input untouched when it + * doesn't -- or when it is past [MAX_AUTO_FORMAT_BODY_CHARS]. + */ +internal fun prettyOrRaw(input: String): String = + when { + input.length > MAX_AUTO_FORMAT_BODY_CHARS -> input + else -> + when (val result = formatMockRuleBodyJson(input)) { + is JsonFormatResult.Formatted -> result.text + is JsonFormatResult.Error -> input + } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt index a18f53d..c0e3add 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt @@ -2,6 +2,7 @@ * @author Shakib * @since 05/08/26 */ +@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @file:Suppress("FunctionNaming", "MagicNumber", "TooManyFunctions", "UnusedPrivateMember", "MatchingDeclarationName") package io.devconsole.ui.compose @@ -18,6 +19,8 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.relocation.BringIntoViewRequester +import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.material3.minimumInteractiveComponentSize @@ -26,6 +29,7 @@ import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable @@ -37,11 +41,15 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextLayoutResult +import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import kotlinx.coroutines.launch import java.util.Locale /** @@ -174,7 +182,10 @@ internal fun MockRuleEditorScreen( val errors = rememberMockRuleFormErrors(form) var showErrors by remember { mutableStateOf(false) } var advancedExpanded by rememberSaveable { mutableStateOf(false) } - var bodyFormatError by remember { mutableStateOf(null) } + // Collapsed when the rule already carries headers -- a capture prefill dumps 20+ lines here and + // pushed status/body off-screen. A blank rule opens expanded: nothing to hide, and the field is + // where a new rule's Content-Type gets typed. + var headersExpanded by rememberSaveable(target.formSourceKey()) { mutableStateOf(initial.headers.isEmpty()) } BackHandler(onBack = onCancel) @@ -216,9 +227,9 @@ internal fun MockRuleEditorScreen( delayError = errors.delay, advancedExpanded = advancedExpanded, onAdvancedExpandedChange = { advancedExpanded = it }, - bodyFormatError = bodyFormatError, - onBodyFormatErrorChange = { bodyFormatError = it }, prefillNote = (target as? MockRuleEditorTarget.New)?.prefillNote, + headersExpanded = headersExpanded, + onHeadersExpandedChange = { headersExpanded = it }, ) } } @@ -328,35 +339,19 @@ private fun MockRuleEditorBodyFields( delayError: String?, advancedExpanded: Boolean, onAdvancedExpandedChange: (Boolean) -> Unit, - bodyFormatError: String?, - onBodyFormatErrorChange: (String?) -> Unit, prefillNote: String?, + headersExpanded: Boolean, + onHeadersExpandedChange: (Boolean) -> Unit, ) { - MockRuleTextField( - "Response headers", - form.headersText.value, - { form.headersText.value = it }, - colors, - placeholder = "Content-Type: application/json", - singleLine = false, - minLines = 3, + MockRuleHeadersSection( + form = form, + colors = colors, + expanded = headersExpanded, + onToggle = { onHeadersExpandedChange(!headersExpanded) }, ) MockRuleBodyField( value = form.bodyText.value, - onValueChange = { - form.bodyText.value = it - onBodyFormatErrorChange(null) - }, - formatError = bodyFormatError, - onFormatClick = { - when (val result = formatMockRuleBodyJson(form.bodyText.value)) { - is JsonFormatResult.Formatted -> { - form.bodyText.value = result.text - onBodyFormatErrorChange(null) - } - is JsonFormatResult.Error -> onBodyFormatErrorChange("Not valid JSON: ${result.message}") - } - }, + onValueChange = { form.bodyText.value = it }, colors = colors, ) if (prefillNote != null) { @@ -471,50 +466,33 @@ private fun MockRuleTextField( placeholder: String = "", enabled: Boolean = true, errorText: String? = null, - singleLine: Boolean = true, - minLines: Int = 1, ) { // The field's own accessible name, announced on the actual editable/value node (not merged with // the sibling label Text) so its edit action stays reachable. val fieldDescription = if (errorText != null) "$label, error: $errorText" else label Column(modifier = modifier.fillMaxWidth().padding(bottom = 16.dp)) { MockRuleFieldLabel(label, colors) - if (singleLine) { - Row( - modifier = - Modifier - .fillMaxWidth() - .heightIn(min = 48.dp) - .clip(RoundedCornerShape(50)) - .background(if (enabled) colors.surface2 else colors.surface3) - .padding(horizontal = 16.dp) - .semantics(mergeDescendants = true) { contentDescription = fieldDescription }, - verticalAlignment = Alignment.CenterVertically, - ) { - if (enabled) { - InspectorPlainTextField(value, onValueChange, placeholder, colors.ink, colors.text3) - } else { - Text( - value.ifBlank { placeholder }, - color = colors.muted, - fontFamily = FontFamily.Monospace, - fontSize = 14.sp, - maxLines = 1, - ) - } - } - } else { - Box( - modifier = - Modifier - .fillMaxWidth() - .heightIn(min = 22.dp * minLines + 24.dp) - .clip(RoundedCornerShape(16.dp)) - .background(colors.surface2) - .padding(horizontal = 16.dp, vertical = 12.dp) - .semantics(mergeDescendants = true) { contentDescription = fieldDescription }, - ) { - InspectorMultilineTextField(value, onValueChange, placeholder, colors.ink, colors.text3) + Row( + modifier = + Modifier + .fillMaxWidth() + .heightIn(min = 48.dp) + .clip(RoundedCornerShape(50)) + .background(if (enabled) colors.surface2 else colors.surface3) + .padding(horizontal = 16.dp) + .semantics(mergeDescendants = true) { contentDescription = fieldDescription }, + verticalAlignment = Alignment.CenterVertically, + ) { + if (enabled) { + InspectorPlainTextField(value, onValueChange, placeholder, colors.ink, colors.text3) + } else { + Text( + value.ifBlank { placeholder }, + color = colors.muted, + fontFamily = FontFamily.Monospace, + fontSize = 14.sp, + maxLines = 1, + ) } } if (errorText != null) { @@ -528,15 +506,127 @@ private fun MockRuleTextField( } } -/** Response body field with a non-blocking JSON Format action. */ +/** + * Response headers behind a [CollapsibleSection]. The meta line carries what collapsing would + * otherwise hide: how many headers are in there, and how many lines Save is going to drop on the + * floor (a line with no colon parses to nothing -- silent until now). + */ +@Composable +private fun MockRuleHeadersSection( + form: MockRuleFormFields, + colors: DevConsoleColors, + expanded: Boolean, + onToggle: () -> Unit, +) { + val parsed = remember(form.headersText.value) { parseMockRuleHeaderLines(form.headersText.value) } + CollapsibleSection( + label = "Response headers", + expanded = expanded, + onToggle = onToggle, + meta = parsed.metaLabel(), + metaColor = if (parsed.skippedLines > 0) colors.warn else colors.muted, + modifier = Modifier.padding(bottom = 12.dp), + ) { + Box( + modifier = + Modifier + .fillMaxWidth() + .padding(bottom = 12.dp) + .heightIn(min = 90.dp) + .clip(RoundedCornerShape(16.dp)) + .background(colors.surface2) + .padding(horizontal = 16.dp, vertical = 12.dp) + .semantics(mergeDescendants = true) { contentDescription = "Response headers" }, + ) { + InspectorMultilineTextField( + form.headersText.value, + { form.headersText.value = it }, + "Content-Type: application/json", + colors.ink, + colors.text3, + ) + } + } +} + +/** + * Kept short on purpose: the section header gives the label only what is left after the meta, and + * "23 headers \u00b7 1 ignored" is long enough to ellipsize "Response headers" itself. The noun is + * already in the label, so the flagged variant drops it. + */ +private fun ParsedMockRuleHeaders.metaLabel(): String = + if (skippedLines == 0) { + "${headers.size} header${if (headers.size == 1) "" else "s"}" + } else { + "${headers.size} \u00b7 $skippedLines ignored" + } + +/** + * Response body field with a non-blocking JSON Format action and a FIND toggle that reveals a + * key search: matching keys get the same wash the read-only viewer uses, and the count sits in the + * search field itself. Collapsed by default -- most rules are small enough to read. + */ @Composable private fun MockRuleBodyField( value: String, onValueChange: (String) -> Unit, - formatError: String?, - onFormatClick: () -> Unit, colors: DevConsoleColors, ) { + // Search state is this field's own business: nothing above it saves, validates or reads a query. + var searchExpanded by rememberSaveable { mutableStateOf(false) } + var query by rememberSaveable { mutableStateOf("") } + val matches = remember(value, query) { bodySearchMatches(value, query) } + // Editing the body or the query re-keys this, so the arrows always restart from the first hit + // rather than pointing at an ordinal that no longer means the same match. + var activeIndex by remember(matches) { mutableStateOf(0) } + // The caret lives here (not in the form) because only the arrows need to move it. Coerced on + // read: FORMAT rewrites the body underneath us, which can leave a stale range past its end. + var selection by remember { mutableStateOf(TextRange.Zero) } + val activeMatch = matches.getOrNull(activeIndex) + val fieldValue = TextFieldValue(text = value, selection = selection.within(value.length)) + + // Scroll-to-match without focus: a FocusRequester would work too, but focusing a text field + // summons the keyboard (hide() loses the race against the IME's own show), which both covers the + // body and leaves the scaffold's ime padding fighting the scroll. bringIntoView needs neither. + val bringMatchIntoView = remember { BringIntoViewRequester() } + var bodyTextLayout by remember { mutableStateOf(null) } + val scope = rememberCoroutineScope() + + // Lives here rather than in the parent so FORMAT can share the caret and scroll the arrows use. + var formatError by remember { mutableStateOf(null) } + + fun revealOffset(offset: Int) { + val at = offset.coerceIn(0, (value.length - 1).coerceAtLeast(0)) + selection = TextRange(at, (at + 1).coerceAtMost(value.length)) + val layout = bodyTextLayout ?: return + scope.launch { bringMatchIntoView.bringIntoView(layout.getBoundingBox(at)) } + } + + // Wraps in both directions -- "next" off the last hit lands on the first, same as any find bar. + fun jumpToMatch(step: Int) { + if (matches.isEmpty()) return + val next = (activeIndex + step).mod(matches.size) + activeIndex = next + revealOffset(matches[next].first) + selection = TextRange(matches[next].first, matches[next].last + 1) + } + + // Re-indenting valid-but-mangled JSON is the whole job here. Broken JSON can't be reformatted -- + // a formatter that guessed where your missing comma went would be worse than one that refuses -- + // so instead the caret goes to the character the parser choked on, which is the actionable half. + fun formatBody() { + when (val result = formatMockRuleBodyJson(value)) { + is JsonFormatResult.Formatted -> { + onValueChange(result.text) + formatError = null + } + is JsonFormatResult.Error -> { + formatError = "Not valid JSON: ${result.message}" + revealOffset(result.offset) + } + } + } + Column(Modifier.fillMaxWidth().padding(bottom = 16.dp)) { Row( Modifier.fillMaxWidth(), @@ -544,20 +634,33 @@ private fun MockRuleBodyField( verticalAlignment = Alignment.CenterVertically, ) { MockRuleFieldLabel("Response body", colors) - Text( - "FORMAT", - color = colors.put, - fontFamily = FontFamily.Monospace, - fontWeight = FontWeight.Bold, - fontSize = 11.5.sp, - modifier = - Modifier - .minimumInteractiveComponentSize() - .clip(RoundedCornerShape(6.dp)) - .background(colors.putSoft) - .clickable(onClick = onFormatClick, role = Role.Button) - .padding(horizontal = 10.dp, vertical = 6.dp) - .semantics { contentDescription = "Format response body as JSON" }, + MockRuleBodyActions( + colors = colors, + searchExpanded = searchExpanded, + // Collapsing clears the query: a hidden find that still filters nothing but is + // secretly holding "aut" is a surprise waiting for the next time it opens. It also + // collapses the selection the arrows left behind -- otherwise the match you stepped + // to stays visibly highlighted by the field's own selection colour, so closing the + // search looks like it kept one hit selected for no reason. Caret stays where the + // match was, so typing carries on from there. + onToggleSearch = { + searchExpanded = !searchExpanded + if (!searchExpanded) { + query = "" + selection = TextRange(selection.start) + } + }, + onFormat = { formatBody() }, + ) + } + if (searchExpanded) { + MockRuleBodySearchRow( + query = query, + onQueryChange = { query = it }, + activeIndex = activeIndex, + matchCount = matches.size, + colors = colors, + onStep = ::jumpToMatch, ) } val bodyDescription = if (formatError != null) "Response body, error: $formatError" else "Response body" @@ -571,11 +674,26 @@ private fun MockRuleBodyField( .padding(horizontal = 16.dp, vertical = 12.dp) .semantics(mergeDescendants = true) { contentDescription = bodyDescription }, ) { - InspectorMultilineTextField(value, onValueChange, "{ }", colors.ink, colors.text3) + InspectorMultilineTextField( + fieldValue, + { edited -> + selection = edited.selection + if (edited.text != value) { + formatError = null + onValueChange(edited.text) + } + }, + "{ }", + colors.ink, + colors.text3, + modifier = Modifier.bringIntoViewRequester(bringMatchIntoView), + onTextLayout = { bodyTextLayout = it }, + visualTransformation = rememberJsonSyntaxTransformation(colors, query, activeMatch), + ) } - if (formatError != null) { + formatError?.let { message -> Text( - formatError, + message, color = colors.warn, fontSize = 11.5.sp, modifier = Modifier.padding(top = 4.dp, start = 4.dp), @@ -584,6 +702,99 @@ private fun MockRuleBodyField( } } +/** The body field's find row: query, "3/12", and the two step arrows. [onStep] takes -1 or +1. */ +@Composable +private fun MockRuleBodySearchRow( + query: String, + onQueryChange: (String) -> Unit, + activeIndex: Int, + matchCount: Int, + colors: DevConsoleColors, + onStep: (Int) -> Unit, +) { + InspectorDetailSearchField( + query = query, + onQueryChange = onQueryChange, + matchLabel = bodyMatchLabel(query, activeIndex, matchCount), + placeholder = "Find in body", + matchColor = if (query.isNotBlank() && matchCount == 0) colors.warn else colors.muted, + onPrevious = { onStep(-1) }, + onNext = { onStep(1) }, + navigationEnabled = matchCount > 0, + ) +} + +/** Keeps a caret from pointing past the end of a body that FORMAT just rewrote shorter. */ +private fun TextRange.within(length: Int): TextRange = TextRange(start.coerceIn(0, length), end.coerceIn(0, length)) + +/** The body field's FIND (filled while open) and FORMAT pills. */ +@Composable +private fun MockRuleBodyActions( + colors: DevConsoleColors, + searchExpanded: Boolean, + onToggleSearch: () -> Unit, + onFormat: () -> Unit, +) { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { + MockRuleBodyAction( + label = "FIND", + color = if (searchExpanded) colors.signalInk else colors.signal, + container = if (searchExpanded) colors.signal else colors.signalSoft, + description = if (searchExpanded) "Hide body search" else "Search response body", + onClick = onToggleSearch, + ) + MockRuleBodyAction( + label = "FORMAT", + color = colors.put, + container = colors.putSoft, + description = "Format response body as JSON", + onClick = onFormat, + ) + } +} + +/** The FORMAT/FIND pills above the body field -- same shape, different tone. */ +@Composable +private fun MockRuleBodyAction( + label: String, + color: Color, + container: Color, + description: String, + onClick: () -> Unit, +) { + Text( + label, + color = color, + fontFamily = FontFamily.Monospace, + fontWeight = FontWeight.Bold, + fontSize = 11.5.sp, + modifier = + Modifier + .minimumInteractiveComponentSize() + .clip(RoundedCornerShape(6.dp)) + .background(container) + .clickable(onClick = onClick, role = Role.Button) + .padding(horizontal = 10.dp, vertical = 6.dp) + .semantics { contentDescription = description }, + ) +} + +/** + * "3/12" while there is something to step through -- same shape as [detailSearchMatchLabel] on the + * read-only detail screens. Empty while nothing is typed: a "0" on an empty query reads as a failed + * search. + */ +private fun bodyMatchLabel( + query: String, + activeIndex: Int, + matchCount: Int, +): String = + when { + query.isBlank() -> "" + matchCount == 0 -> "No match" + else -> "${activeIndex + 1}/$matchCount" + } + /** * Editable Compose state for every field on the sheet, seeded once from [initial]. [methodChips]/ * [scopeChips] carry the chip options actually offered -- [chipsIncluding] appends the initial @@ -631,7 +842,9 @@ private fun rememberMockRuleFormFields( pathPattern = rememberSaveable(sourceKey) { mutableStateOf(initial.pathPattern) }, statusText = rememberSaveable(sourceKey) { mutableStateOf(initial.statusCode.toString()) }, headersText = rememberSaveable(sourceKey) { mutableStateOf(initial.headers.toMockRuleHeaderLines()) }, - bodyText = rememberSaveable(sourceKey) { mutableStateOf(initial.body) }, + // Opens pretty-printed so a captured one-line JSON body is readable without tapping + // Format; a non-JSON body (HTML, plain text, template) stays exactly as captured. + bodyText = rememberSaveable(sourceKey) { mutableStateOf(prettyOrRaw(initial.body)) }, priorityText = rememberSaveable(sourceKey) { mutableStateOf(initial.priority.toString()) }, scope = rememberSaveable(sourceKey) { mutableStateOf(initial.scope) }, scopeChips = remember(initial.scope) { chipsIncluding(MOCK_RULE_SCOPES, initial.scope) }, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorTextField.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorTextField.kt index 33ee4d6..4aa60d3 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorTextField.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorTextField.kt @@ -13,8 +13,11 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.input.TextFieldValue +import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp @@ -74,6 +77,7 @@ internal fun InspectorMultilineTextField( modifier: Modifier = Modifier, fontSize: TextUnit = 13.sp, fontFamily: FontFamily = FontFamily.Monospace, + visualTransformation: VisualTransformation = VisualTransformation.None, ) { BasicTextField( value = value, @@ -82,6 +86,7 @@ internal fun InspectorMultilineTextField( textStyle = TextStyle(color = textColor, fontSize = fontSize, fontFamily = fontFamily), singleLine = false, cursorBrush = SolidColor(textColor), + visualTransformation = visualTransformation, decorationBox = { innerTextField -> if (value.isEmpty()) { Text(placeholder, color = placeholderColor, fontSize = fontSize, fontFamily = fontFamily) @@ -90,3 +95,41 @@ internal fun InspectorMultilineTextField( }, ) } + +/** + * [TextFieldValue] flavour of [InspectorMultilineTextField], for the one caller that has to *move* + * the selection rather than only read the text: the mock body's find arrows select the match they + * step to. [onTextLayout] hands that caller the laid-out text so it can turn a match offset into a + * rectangle worth scrolling to. + */ +@Suppress("LongParameterList") // Same contract as the String flavour above. +@Composable +internal fun InspectorMultilineTextField( + value: TextFieldValue, + onValueChange: (TextFieldValue) -> Unit, + placeholder: String, + textColor: Color, + placeholderColor: Color, + modifier: Modifier = Modifier, + fontSize: TextUnit = 13.sp, + fontFamily: FontFamily = FontFamily.Monospace, + visualTransformation: VisualTransformation = VisualTransformation.None, + onTextLayout: (TextLayoutResult) -> Unit = {}, +) { + BasicTextField( + value = value, + onValueChange = onValueChange, + modifier = modifier.fillMaxWidth(), + textStyle = TextStyle(color = textColor, fontSize = fontSize, fontFamily = fontFamily), + singleLine = false, + cursorBrush = SolidColor(textColor), + visualTransformation = visualTransformation, + onTextLayout = onTextLayout, + decorationBox = { innerTextField -> + if (value.text.isEmpty()) { + Text(placeholder, color = placeholderColor, fontSize = fontSize, fontFamily = fontFamily) + } + innerTextField() + }, + ) +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorJsonHighlightTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorJsonHighlightTest.kt new file mode 100644 index 0000000..76aba28 --- /dev/null +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorJsonHighlightTest.kt @@ -0,0 +1,73 @@ +package io.devconsole.ui.compose + +import org.junit.Assert.assertEquals +import org.junit.Test + +class InspectorJsonHighlightTest { + private fun types(text: String) = jsonHighlightSpans(text).map { text.substring(it.start, it.end) to it.type } + + @Test + fun `keys strings numbers booleans and nulls are told apart`() { + assertEquals( + listOf( + "{" to JsonTokenType.BRACE, + "\"a\"" to JsonTokenType.KEY, + ":" to JsonTokenType.PUNCT, + "\"a\"" to JsonTokenType.STRING, + "," to JsonTokenType.PUNCT, + "\"n\"" to JsonTokenType.KEY, + ":" to JsonTokenType.PUNCT, + "-1.5e3" to JsonTokenType.NUMBER, + "," to JsonTokenType.PUNCT, + "\"b\"" to JsonTokenType.KEY, + ":" to JsonTokenType.PUNCT, + "true" to JsonTokenType.BOOLEAN, + "," to JsonTokenType.PUNCT, + "\"z\"" to JsonTokenType.KEY, + ":" to JsonTokenType.PUNCT, + "null" to JsonTokenType.NULL, + "}" to JsonTokenType.BRACE, + ), + types("""{"a": "a", "n": -1.5e3, "b": true, "z": null}"""), + ) + } + + @Test + fun `braces carry their nesting depth`() { + val depths = + jsonHighlightSpans("""{"a":[{"b":1}]}""") + .filter { it.type == JsonTokenType.BRACE } + .map { it.depth } + assertEquals(listOf(0, 1, 2, 2, 1, 0), depths) + } + + @Test + fun `half-typed json still lexes instead of throwing`() { + // Unterminated string swallows the rest; nothing after it is mis-coloured as structure. + assertEquals(listOf("{" to JsonTokenType.BRACE, "\"ab: 1" to JsonTokenType.STRING), types("""{"ab: 1""")) + assertEquals(emptyList>(), types("")) + } + + @Test + fun `structural characters inside strings are not tokenized`() { + val escaped = "\"{\\\"a\\\": 1}\"" + assertEquals(listOf(escaped to JsonTokenType.STRING), types(escaped)) + } + + @Test + fun `body search finds keys and values alike, ignoring case`() { + val json = """{"userId":1,"note":"the ID lives here"}""" + + val hits = bodySearchMatches(json, "id").map { json.substring(it) } + + // Two in the key "userId"/"Id" casing and one inside the value -- values are searchable too. + assertEquals(listOf("Id", "ID"), hits) + } + + @Test + fun `overlapping hits are counted once and blank queries match nothing`() { + assertEquals(1, bodySearchMatches("aaa", "aa").size) + assertEquals(emptyList(), bodySearchMatches("""{"a":1}""", "")) + assertEquals(emptyList(), bodySearchMatches("""{"a":1}""", " ")) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormatTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormatTest.kt index c1db861..ed51ef1 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormatTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleBodyFormatTest.kt @@ -77,4 +77,49 @@ class InspectorMockRuleBodyFormatTest { assertTrue(result is JsonFormatResult.Error) } + + @Test + fun `prettyOrRaw pretty-prints JSON and passes non-JSON through`() { + assertEquals("{\n \"a\": 1\n}", prettyOrRaw("""{"a":1}""")) + assertEquals("nope", prettyOrRaw("nope")) + assertEquals("", prettyOrRaw("")) + } + + @Test + fun `a body past the auto-format cap opens exactly as captured`() { + val big = """{"a":"${"x".repeat(MAX_AUTO_FORMAT_BODY_CHARS)}"}""" + + assertEquals(big, prettyOrRaw(big)) + // The explicit FORMAT action is uncapped -- the user asked for that one. + assertTrue(formatMockRuleBodyJson(big) is JsonFormatResult.Formatted) + } + + @Test + fun `a syntax error carries the offset it choked on`() { + val body = """{"a":1,"b":}""" + + val result = formatMockRuleBodyJson(body) + + check(result is JsonFormatResult.Error) + // Points at the '}' that showed up where a value belonged, not at the start of the body. + assertEquals('}', body[result.offset]) + } + + @Test + fun `re-formatting mangled-but-valid json is the normal case`() { + val mangled = "{\n\"a\" : 1,\n\t\t\"b\":[ 2 ,3 ] }" + + assertEquals( + """ + { + "a": 1, + "b": [ + 2, + 3 + ] + } + """.trimIndent(), + (formatMockRuleBodyJson(mangled) as JsonFormatResult.Formatted).text, + ) + } } From 6865e3aea95ea7b707acc3cb5d17c951adef3257 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Mon, 24 Aug 2026 15:40:18 +0600 Subject: [PATCH 2/3] Fixed console mock ui --- .../resources/devconsole-web/dashboard.css | 14 +++++++++ .../resources/devconsole-web/dashboard.js | 29 +++++++++++++++++++ .../main/resources/devconsole-web/index.html | 3 +- .../ui/compose/InspectorMockRuleEditor.kt | 16 ++++------ .../ui/compose/InspectorMockRuleEditorTest.kt | 6 ++-- 5 files changed, 55 insertions(+), 13 deletions(-) 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 d0f8af7..e66c8e7 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1230,6 +1230,20 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } without the path/headers/body rows wrapping too tightly. */ .modal.modal-wide { max-width: 640px; } .mock-body-toolbar { display: flex; align-items: center; gap: 12px; margin-top: -4px; } +/* The status text is the flexible middle so the full-window toggle always parks on the right edge, + and can shrink/ellipse rather than shoving the toggle out of the row on a long parse error. */ +#mockRuleBodyStatus { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +#mockRuleBodyExpand { flex: 0 0 auto; } +/* A mock body is JSON far more often than it is one line, so the editor opens tall enough to read + a formatted payload without scrolling; `rows` only sets the floor before this applies. */ +#mockRuleBody { min-height: 232px; line-height: 1.6; resize: vertical; } +/* Full window mode: same near-viewport box as .modal-fullscreen, with the extra height handed to + the body editor. The grid's own rows stay content-sized, so the editor is sized in vh directly + rather than flexed -- a grid item can't stretch into a row it doesn't define. */ +.modal.mock-modal-expanded { max-width: 96vw; width: 96vw; height: 92vh; max-height: 92vh; } +.mock-modal-expanded #mockRuleBody { min-height: clamp(232px, 62vh, 78vh); } +/* Capped so the live preview can't push the editor itself off-screen in the scrolling body. */ +.mock-modal-expanded #mockRuleBodyPreview .code-block { max-height: 34vh; overflow-y: auto; } /* Code block fullscreen overlay: near-viewport-size instead of the generic 480px modal so a long JSON/code body gets real room. Its .code-block-lg content scrolls inside .modal-body-code. */ diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 7450801..4f7303c 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -37,6 +37,10 @@ // draft came from "Mock this response" (or an edit of a rule that already had one), reset on // every dialog open, and included in the save payload as-is (never re-derived from edited fields). let mockRuleDraftSourceBodySnapshot = null; + // Full-window mode for the mock rule dialog. Deliberately outside openMockRuleDialog so it + // sticks for the rest of the page session: someone hand-writing JSON bodies wants the big + // editor on every rule, not one dialog at a time. + let mockBodyExpanded = false; let preferencesEditable = false; let databaseEditable = false; let filesEditable = false; @@ -1472,6 +1476,29 @@ } refreshMockBodyEditor(); } + /** Applies full-window mode to the dialog shell and syncs the toggle's label, icon, and pressed + * state. Only the box grows -- no field is hidden, so a validation error can never land on + * something the user can't see. */ + function setMockBodyExpanded(expanded) { + mockBodyExpanded = expanded; + const modal = $('mockRuleModal')?.querySelector('.modal'); + const btn = $('mockRuleBodyExpand'); + if (!modal || !btn) return; + modal.classList.toggle('mock-modal-expanded', expanded); + btn.setAttribute('aria-pressed', String(expanded)); + btn.title = expanded ? 'Shrink the dialog back to its normal size' : 'Expand the dialog to fill the window (the body editor takes the extra room)'; + $('mockRuleBodyExpandLabel').textContent = expanded ? 'Exit full window' : 'Full window'; + btn.querySelector('use')?.setAttribute('href', expanded ? '#dc-collapse' : '#dc-expand'); + } + function toggleMockBodyExpanded() { + setMockBodyExpanded(!mockBodyExpanded); + const el = $('mockRuleBody'); + // A plain focus() scrolls the *end* of a now-tall textarea into view, hiding the start of the + // body; park the field at the top of the scrolling .modal-body instead so the toggle lands on + // line 1 either way. + el.focus({ preventScroll: true }); + el.closest('.field')?.scrollIntoView({ block: 'start' }); + } /** Only a plain (optionally delayed) static response with an untruncated body survives a round * trip through this dialog -- richer actions (ConnectionFailure/Timeout/TemplateResponse/etc.) * and truncated bodies have no representation in the form, so saving one back would silently @@ -1502,6 +1529,7 @@ setFieldError(f.headers, false); setMockDialogError(''); $('mockRuleModalTitleText').textContent = editing ? 'Edit mock rule' : 'New mock rule'; + setMockBodyExpanded(mockBodyExpanded); refreshMockBodyEditor(); syncMockRuleDialogGate(); mockDialogOpenerEl = document.activeElement; @@ -7516,6 +7544,7 @@ $('mockRuleCancel').onclick = closeMockRuleDialog; $('mockRuleSave').onclick = saveMockRuleDialog; $('mockRuleBodyFormat').onclick = formatMockRuleBody; + $('mockRuleBodyExpand').onclick = toggleMockBodyExpanded; $('mockRuleBody').addEventListener('input', refreshMockBodyEditor); $('mockRuleBody').addEventListener('blur', formatMockRuleBody); wireCardGrid('mockRuleList', { diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index ffe0657..57a1129 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -683,11 +683,12 @@
+
diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt index c0e3add..733bf5f 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditor.kt @@ -56,9 +56,8 @@ import java.util.Locale * Which rule the create/edit sheet is showing; [InspectorMockRuleUi.id] is disabled for [Edit]. * [New.draft] lets a caller prefill a brand-new rule (e.g. mock-from-capture's * [mockRuleDraftFromTransaction]) while keeping the id field editable, unlike [Edit]. - * [New.prefillNote], when set, renders under the body field -- honesty about *where* a prefilled - * body/headers came from (a redacted, possibly-truncated capture preview) rather than presenting it - * as the real payload. + * [New.prefillNote], when set, renders under the body field -- reserved for a prefill the form + * genuinely could not carry (a binary response body), not for narrating an ordinary one. */ internal sealed interface MockRuleEditorTarget { /** @@ -900,9 +899,6 @@ private val MOCK_DRAFT_STRIPPED_HEADERS = /** The exact placeholder [FullInspectorDataSource]'s `previewText()` returns for a non-textual response. */ private val BINARY_PREVIEW_PLACEHOLDER = Regex("""\[binary, \d+ bytes]""") -private const val CAPTURE_PREFILL_NOTE = - "Prefilled from a captured response — the body and headers are the redacted preview and may " + - "be truncated. Review before saving." private const val CAPTURE_PREFILL_BINARY_NOTE = "The captured response body is binary and can't be prefilled here — enter one manually." @@ -910,9 +906,9 @@ private const val CAPTURE_PREFILL_BINARY_NOTE = * Prefills a brand-new rule from a captured transaction -- the net detail's "Mock this response" * action. [existingIds] lets [suggestMockRuleId] avoid suggesting an id that already names a rule. * [InspectorTransactionUi.responsePreview] is a *redacted, possibly-truncated* capture preview, not - * the real payload -- [MockRuleEditorTarget.New.prefillNote] carries that caveat - * to the sheet; a binary response's literal `"[binary, N bytes]"` placeholder is never usable as a - * body, so it prefills empty with a more specific note instead. + * the real payload -- the prefilled body is editable, so that needs no on-screen caveat. A binary + * response's literal `"[binary, N bytes]"` placeholder, though, is never usable as a body, so it + * prefills empty and carries a [MockRuleEditorTarget.New.prefillNote] saying to enter one by hand. */ internal fun mockRuleDraftFromTransaction( transaction: InspectorTransactionUi, @@ -936,7 +932,7 @@ internal fun mockRuleDraftFromTransaction( ) return MockRuleEditorTarget.New( draft = draft, - prefillNote = if (isBinary) CAPTURE_PREFILL_BINARY_NOTE else CAPTURE_PREFILL_NOTE, + prefillNote = if (isBinary) CAPTURE_PREFILL_BINARY_NOTE else null, sourceKey = transaction.id, ) } diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt index d6107c5..96b98c5 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorMockRuleEditorTest.kt @@ -40,12 +40,14 @@ class InspectorMockRuleEditorTest { assertEquals(mapOf("Content-Type" to "application/json", "X-Trace" to "1"), target.draft.headers) } + // A prefilled body is editable in the sheet, so an ordinary capture carries no note at all -- + // only the binary case, which genuinely can't be prefilled, still explains itself. @Test - fun `a normal text preview prefills the body and carries the redaction caveat note`() { + fun `a normal text preview prefills the body with no note`() { val target = mockRuleDraftFromTransaction(transaction("""{"ok":true}""")) assertEquals("""{"ok":true}""", target.draft.body) - assertTrue(target.prefillNote.orEmpty().contains("redacted")) + assertNull(target.prefillNote) } @Test From e987c0353cd16c1441cc0f06cee18a7a42322a05 Mon Sep 17 00:00:00 2001 From: "Md. Asaduzzaman Nur" Date: Mon, 24 Aug 2026 16:33:50 +0600 Subject: [PATCH 3/3] add search in dev console --- .../resources/devconsole-web/dashboard.css | 32 +++- .../resources/devconsole-web/dashboard.js | 160 +++++++++++++++++- .../main/resources/devconsole-web/index.html | 11 +- .../server/ktor/DashboardAssetsTest.kt | 66 ++++++++ 4 files changed, 256 insertions(+), 13 deletions(-) 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 e66c8e7..69922f0 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.css @@ -1230,13 +1230,39 @@ body.detail-zoom .split-shell.collapse-detail { grid-template-columns: 1fr; } without the path/headers/body rows wrapping too tightly. */ .modal.modal-wide { max-width: 640px; } .mock-body-toolbar { display: flex; align-items: center; gap: 12px; margin-top: -4px; } -/* The status text is the flexible middle so the full-window toggle always parks on the right edge, - and can shrink/ellipse rather than shoving the toggle out of the row on a long parse error. */ +/* The JSON status is the one thing on its row that can run long (a parse error carries the + engine's own message), so it takes the slack and ellipses rather than widening the dialog. + The full-window toggle lives on the find bar below and parks on that row's right edge. */ #mockRuleBodyStatus { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -#mockRuleBodyExpand { flex: 0 0 auto; } +#mockRuleBodyExpand { margin-left: auto; } /* A mock body is JSON far more often than it is one line, so the editor opens tall enough to read a formatted payload without scrolling; `rows` only sets the floor before this applies. */ #mockRuleBody { min-height: 232px; line-height: 1.6; resize: vertical; } + +/* Find-in-body. A textarea can only ever show ONE hit -- its selection, and only while focused -- + so every match is painted by a mirrored, non-interactive layer sitting underneath a + now-transparent textarea. The mirror only ever renders color: transparent text; the glyphs the + user reads are still the textarea's own, drawn on top. That means every property affecting glyph + position (font, size, line-height, padding, wrapping) MUST stay identical between the two rules + below, or the marks slide off the words they belong to. The scrollbar gutter is the one that + can't be written here -- its width is measured and applied in syncMockBodyHighlightMetrics. */ +.mock-body-editor { position: relative; display: block; } +.mock-body-editor > textarea { position: relative; z-index: 1; display: block; width: 100%; background: transparent; } +.mock-body-highlight { + position: absolute; inset: 1px; z-index: 0; overflow: hidden; pointer-events: none; + padding: 9px 11px; border-radius: 6px; background: var(--code-bg); + font-family: var(--font-mono); font-size: 12.5px; line-height: 1.6; + white-space: pre-wrap; overflow-wrap: break-word; color: transparent; +} +/* Same --signal-soft the .code-line/.kv-grid search hits use. The current match is stronger but + still translucent: the readable glyphs belong to the textarea above and stay --ink either way, + so a solid --signal fill would bury them. */ +.mock-body-highlight mark { background: var(--signal-soft); color: transparent; border-radius: 2px; } +.mock-body-highlight mark.current { background: color-mix(in srgb, var(--signal) 45%, transparent); } +.mock-body-findbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.mock-body-find-wrap { flex: 1 1 200px; min-width: 160px; max-width: 320px; } +.mock-body-findbar .xs { flex: 0 0 auto; } +#mockRuleBodyFindCount { flex: 1 1 auto; min-width: 0; white-space: nowrap; } /* Full window mode: same near-viewport box as .modal-fullscreen, with the extra height handed to the body editor. The grid's own rows stay content-sized, so the editor is sized in vh directly rather than flexed -- a grid item can't stretch into a row it doesn't define. */ diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 4f7303c..1a16d75 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -41,6 +41,10 @@ // sticks for the rest of the page session: someone hand-writing JSON bodies wants the big // editor on every rule, not one dialog at a time. let mockBodyExpanded = false; + // Find-in-body for the response body editor. `ranges` are [start, end) offsets into the + // textarea's CURRENT value, so they are recomputed from scratch on every body change (Format + // rewrites the whole string) rather than carried across edits. Reset on each dialog open. + let mockBodyFind = { query: '', ranges: [], index: 0 }; let preferencesEditable = false; let databaseEditable = false; let filesEditable = false; @@ -1405,6 +1409,10 @@ // codeBlockHtml, which already esc()s every token. // ================================================================ const MOCK_RULE_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/; + // Find-in-body stops counting here: a one-character query against a large body would + // otherwise build tens of thousands of s on every keystroke. The count renders as + // "N+" when it caps, so the number on screen is never quietly wrong. + const MOCK_BODY_FIND_MAX = 2000; const MOCK_HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; function mockRuleFieldEls() { return { @@ -1454,17 +1462,27 @@ const raw = $('mockRuleBody').value; const statusEl = $('mockRuleBodyStatus'); const previewEl = $('mockRuleBodyPreview'); - if (!raw.trim()) { statusEl.textContent = ''; statusEl.className = 'card-field-help'; previewEl.innerHTML = ''; return; } - try { - const parsed = JSON.parse(raw); - statusEl.textContent = 'valid JSON'; - statusEl.className = 'card-field-help tone-text-signal'; - previewEl.innerHTML = codeBlockHtml(formatJsonLines(parsed), false, 'Mock rule body preview'); - } catch (err) { - statusEl.textContent = 'not JSON — will be sent verbatim: ' + err.message; - statusEl.className = 'card-field-help tone-text-warn'; + if (!raw.trim()) { + statusEl.textContent = ''; + statusEl.className = 'card-field-help'; previewEl.innerHTML = ''; + } else { + try { + const parsed = JSON.parse(raw); + statusEl.textContent = 'valid JSON'; + statusEl.className = 'card-field-help tone-text-signal'; + previewEl.innerHTML = codeBlockHtml(formatJsonLines(parsed), false, 'Mock rule body preview'); + } catch (err) { + statusEl.textContent = 'not JSON — will be sent verbatim: ' + err.message; + statusEl.className = 'card-field-help tone-text-warn'; + previewEl.innerHTML = ''; + } } + // Every path that changes the body funnels through here (the input listener, Format's direct + // .value rewrite, and the dialog opening on a different rule), so it is the one place find + // offsets can be kept honest. An empty body takes the branch above rather than returning + // early: reopening on a blank rule still has to clear the previous rule's highlights. + refreshMockBodyFind(); } function formatMockRuleBody() { const el = $('mockRuleBody'); @@ -1476,6 +1494,105 @@ } refreshMockBodyEditor(); } + /** Literal (never regex) case-insensitive scan for non-overlapping matches of [query] in [text]. + * A mock body is JSON, so `"`, `{` and `[` are ordinary things to search for -- treating the + * query as a pattern would make the common case throw or silently match the wrong thing. */ + function mockBodyFindRanges(text, query) { + if (!query) return []; + const haystack = text.toLowerCase(); + const needle = query.toLowerCase(); + const ranges = []; + for (let i = haystack.indexOf(needle); i !== -1; i = haystack.indexOf(needle, i + needle.length)) { + ranges.push([i, i + needle.length]); + if (ranges.length >= MOCK_BODY_FIND_MAX) break; + } + return ranges; + } + /** The mirror is laid out by CSS except for the scrollbar gutter: once the textarea overflows, + * its content box narrows by the scrollbar's width and its text rewraps. The mirror has + * `overflow: hidden` and never grows one, so that width is measured off the live element and + * added as padding -- otherwise every mark below the first wrapped line drifts. */ + function syncMockBodyHighlightMetrics() { + const ta = $('mockRuleBody'); + const layer = $('mockRuleBodyHighlight'); + if (!ta || !layer) return; + const gutter = Math.max(0, ta.offsetWidth - ta.clientWidth - 2); + layer.style.paddingRight = 11 + gutter + 'px'; + layer.scrollTop = ta.scrollTop; + layer.scrollLeft = ta.scrollLeft; + } + /** Paints the mirror. Skipped entirely with no active query -- the layer still has to exist to + * carry the editor's background (the textarea above it is transparent), but building a copy of + * the whole body on every keystroke would be pure waste when nothing is highlighted. */ + function renderMockBodyHighlight() { + const layer = $('mockRuleBodyHighlight'); + if (!layer) return; + const { query, ranges, index } = mockBodyFind; + if (!query || !ranges.length) { layer.innerHTML = ''; return; } + const text = $('mockRuleBody').value; + let html = ''; + let at = 0; + ranges.forEach(([start, end], i) => { + html += esc(text.slice(at, start)); + html += `${esc(text.slice(start, end))}`; + at = end; + }); + // The trailing newline keeps the mirror's last line box in step with the textarea's, which + // always reserves one for the caret. + layer.innerHTML = html + esc(text.slice(at)) + '\n'; + syncMockBodyHighlightMetrics(); + } + /** Scrolls the current match into view without focusing the textarea, so the find field keeps + * the caret and Enter can keep stepping. The mark's own laid-out position in the mirror is the + * measurement -- the textarea can't report where a range sits, and asking it to scroll would + * mean focusing it. */ + function revealMockBodyMatch() { + const ta = $('mockRuleBody'); + const mark = $('mockRuleBodyHighlight')?.querySelector('mark.current'); + if (!ta || !mark) return; + const top = mark.offsetTop; + const bottom = top + mark.offsetHeight; + if (top < ta.scrollTop || bottom > ta.scrollTop + ta.clientHeight) { + ta.scrollTop = Math.max(0, top - ta.clientHeight / 2 + mark.offsetHeight / 2); + } + // Also park the textarea's own selection on the match, so clicking into the editor lands the + // caret where the user was looking rather than back where they last typed. + const [start, end] = mockBodyFind.ranges[mockBodyFind.index]; + ta.setSelectionRange(start, end); + syncMockBodyHighlightMetrics(); + } + function setMockBodyFindCount(text, tone) { + const el = $('mockRuleBodyFindCount'); + el.textContent = text; + el.className = 'card-field-help' + (tone ? ' ' + tone : ''); + } + /** Recomputes matches against the live body and repaints. [keepIndex] holds the user's place + * across a body edit; the find field's own input resets to the first match instead. */ + function refreshMockBodyFind({ keepIndex = true, reveal = false } = {}) { + const ranges = mockBodyFindRanges($('mockRuleBody').value, mockBodyFind.query); + mockBodyFind.ranges = ranges; + mockBodyFind.index = ranges.length ? (keepIndex ? Math.min(mockBodyFind.index, ranges.length - 1) : 0) : 0; + const capped = ranges.length >= MOCK_BODY_FIND_MAX; + $('mockRuleBodyFindPrev').disabled = ranges.length < 2; + $('mockRuleBodyFindNext').disabled = ranges.length < 2; + if (!mockBodyFind.query) setMockBodyFindCount(''); + else if (!ranges.length) setMockBodyFindCount('no matches', 'tone-text-warn'); + else setMockBodyFindCount(mockBodyFind.index + 1 + ' of ' + ranges.length + (capped ? '+' : '')); + renderMockBodyHighlight(); + if (reveal) revealMockBodyMatch(); + } + function stepMockBodyFind(delta) { + const total = mockBodyFind.ranges.length; + if (!total) return; + mockBodyFind.index = (mockBodyFind.index + delta + total) % total; + setMockBodyFindCount(mockBodyFind.index + 1 + ' of ' + total + (total >= MOCK_BODY_FIND_MAX ? '+' : '')); + renderMockBodyHighlight(); + revealMockBodyMatch(); + } + function applyMockBodyFindQuery(query) { + mockBodyFind.query = query; + refreshMockBodyFind({ keepIndex: false, reveal: true }); + } /** Applies full-window mode to the dialog shell and syncs the toggle's label, icon, and pressed * state. Only the box grows -- no field is hidden, so a validation error can never land on * something the user can't see. */ @@ -1492,6 +1609,8 @@ } function toggleMockBodyExpanded() { setMockBodyExpanded(!mockBodyExpanded); + // The box just changed width, so the body rewraps and the scrollbar may come or go. + syncMockBodyHighlightMetrics(); const el = $('mockRuleBody'); // A plain focus() scrolls the *end* of a now-tall textarea into view, hiding the start of the // body; park the field at the top of the scrolling .modal-body instead so the toggle lands on @@ -1530,6 +1649,8 @@ setMockDialogError(''); $('mockRuleModalTitleText').textContent = editing ? 'Edit mock rule' : 'New mock rule'; setMockBodyExpanded(mockBodyExpanded); + $('mockRuleBodyFind').value = ''; + mockBodyFind = { query: '', ranges: [], index: 0 }; refreshMockBodyEditor(); syncMockRuleDialogGate(); mockDialogOpenerEl = document.activeElement; @@ -7547,6 +7668,27 @@ $('mockRuleBodyExpand').onclick = toggleMockBodyExpanded; $('mockRuleBody').addEventListener('input', refreshMockBodyEditor); $('mockRuleBody').addEventListener('blur', formatMockRuleBody); + $('mockRuleBody').addEventListener('scroll', syncMockBodyHighlightMetrics); + $('mockRuleBodyFind').addEventListener('input', (e) => applyMockBodyFindQuery(e.target.value)); + $('mockRuleBodyFind').addEventListener('keydown', (e) => { + if (e.key === 'Enter') { e.preventDefault(); stepMockBodyFind(e.shiftKey ? -1 : 1); return; } + // Escape clears the search before it closes the dialog -- stopPropagation keeps + // mockDialogKeydown (a document listener) from dismissing a dialog mid-edit over a + // keystroke the user meant for the find field. With the field already empty it falls + // through and Escape closes the dialog as it does everywhere else. + if (e.key === 'Escape' && e.target.value) { + e.preventDefault(); + e.stopPropagation(); + e.target.value = ''; + applyMockBodyFindQuery(''); + } + }); + for (const [id, delta] of [['mockRuleBodyFindPrev', -1], ['mockRuleBodyFindNext', 1]]) { + // Stepping must not pull focus out of the find field (and must not blur the textarea into + // formatMockRuleBody, which would rewrite the body under the offsets being stepped through). + $(id).addEventListener('mousedown', (e) => e.preventDefault()); + $(id).onclick = () => stepMockBodyFind(delta); + } wireCardGrid('mockRuleList', { onToggle: (id) => { const checked = document.querySelector(`[data-card-toggle="${CSS.escape(id)}"]`)?.getAttribute('aria-checked') === 'true'; diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 57a1129..4763167 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -683,11 +683,20 @@
+
+
+ + + +
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt index 44d5a90..79d9c6f 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DashboardAssetsTest.kt @@ -205,4 +205,70 @@ class DashboardAssetsTest { assertTrue(dashboard.contains("
assertTrue("missing find-in-body hook \"$id\"", dashboard.contains(id)) } + } + + @Test + fun `find-in-body is wired to the body editor and steps through matches`() { + val script = DashboardAssets.js() + + assertTrue(script.contains("function mockBodyFindRanges(")) + assertTrue(script.contains("function stepMockBodyFind(")) + assertTrue(script.contains("$('mockRuleBodyFind').addEventListener('input'")) + // The mirror only lines up with the textarea while their scroll offsets agree. + assertTrue(script.contains("$('mockRuleBody').addEventListener('scroll', syncMockBodyHighlightMetrics)")) + } + + /** + * Regression: `refreshMockBodyEditor` used to `return` early on a blank body, which skipped the + * find rescan at its end. Opening a rule with a body, searching it, then opening a *blank* rule + * left the previous rule's marks painted over an empty editor with a stale match count. The + * blank case has to fall through to the shared tail instead, so the guard is now an if/else. + */ + @Test + fun `an empty response body still rescans find state instead of returning early`() { + val script = DashboardAssets.js() + val body = + script + .substringAfter( + "function refreshMockBodyEditor()", + ).substringBefore("function formatMockRuleBody()") + + assertFalse( + "blank-body guard must not return before the find rescan", + body.contains("previewEl.innerHTML = ''; return; }"), + ) + assertTrue("refreshMockBodyEditor must end by rescanning find offsets", body.contains("refreshMockBodyFind();")) + } + + /** + * A mock body is JSON, so `"`, `[` and `{` are ordinary things to search for. Building a + * RegExp from the query would throw on the single `[` a user types on the way to `["id"]`. + */ + @Test + fun `find-in-body treats the query as literal text rather than a pattern`() { + val script = DashboardAssets.js() + val fn = + script + .substringAfter( + "function mockBodyFindRanges(", + ).substringBefore("function syncMockBodyHighlightMetrics(") + + assertTrue(fn.contains("indexOf(needle")) + assertFalse("query must never reach RegExp", fn.contains("RegExp")) + } }