25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
fix(redis): unify value search highlighting and add replace controls
二丫讲梵a86520234e6f
diff --git a/apps/desktop/src/components/common/JsonTree.vue b/apps/desktop/src/components/common/JsonTree.vueindex 5af0c3684e..6fc43122a6 100644--- a/apps/desktop/src/components/common/JsonTree.vue+++ b/apps/desktop/src/components/common/JsonTree.vue@@ -1,15 +1,19 @@<script setup lang="ts">-import { computed, defineComponent, h, nextTick, ref, shallowRef, watch, type VNodeChild } from "vue";+import { computed, defineComponent, h, nextTick, onBeforeUnmount, ref, shallowRef, watch, type VNodeChild } from "vue";import { DynamicScroller, DynamicScrollerItem } from "vue-virtual-scroller";import { ChevronDown, ChevronRight } from "@lucide/vue";import { createJsonTreeRoot, getJsonTreeChildren, getVisibleJsonTreeNodes, isJsonTreeClosingNode, isJsonTreeContainer, isJsonTreeInitiallyExpanded, jsonTreeContainerKind, jsonTreeContainerSummary, type JsonTreeNode } from "@/lib/common/jsonTree";import { isLosslessJsonNumber } from "@/lib/common/safeJsonFormat";+import { jsonTreeKeyText, jsonTreeScalarText, type JsonTreeSearchMatch } from "@/lib/common/jsonTreeSearch";+import { renderTextContentMatchesHtml } from "@/lib/common/textContentSearch";defineOptions({ name: "JsonTree" });const props = withDefaults(defineProps<{value: unknown;+ searchMatches?: JsonTreeSearchMatch[];+ activeSearchIndex?: number;wordWrap?: boolean;/** Optional Shiki-style inline highlighter retained for Redis value views. */highlightJson?: (json: string) => string;@@ -29,9 +33,11 @@ const props = withDefaults(type ExpansionMode = "default" | "all" | "none";type DynamicScrollerHandle = {forceUpdate: (clear?: boolean) => void;+ scrollToItem?: (index: number) => void;scrollToPosition?: (position: number) => void;};+const treeRoot = ref<HTMLElement>();const expansionMode = ref<ExpansionMode>("default");const expansionOverrides = shallowRef(new Map<string, boolean>());const virtualScroller = ref<DynamicScrollerHandle>();@@ -80,17 +86,79 @@ function scalarClass(value: unknown): string {return "json-tree-string";}-function scalarText(value: unknown): string {- if (isLosslessJsonNumber(value)) return value.raw;- if (typeof value === "string") return JSON.stringify(value);- if (value === null) return "null";- return String(value);-}+const scalarText = jsonTreeScalarText;++const searchParts = computed(() => {+ const parts = new Map<string, { matches: JsonTreeSearchMatch[]; active: number }>();+ for (const [index, match] of (props.searchMatches ?? []).entries()) {+ const key = JSON.stringify([match.path, match.part]);+ const entry = parts.get(key) ?? { matches: [], active: -1 };+ if (index === props.activeSearchIndex) entry.active = entry.matches.length;+ entry.matches.push(match);+ parts.set(key, entry);+ }+ return parts;+});-function highlightedJson(value: string): string {+function highlightedJson(value: string, node: JsonTreeNode, part: "key" | "value"): string {+ const entry = searchParts.value.get(JSON.stringify([node.path, part]));+ if (entry) return renderTextContentMatchesHtml(value, entry.matches, { activeMatchIndex: entry.active });return props.highlightJson?.(value) ?? escapeHtml(value);}+let searchNavigationRevision = 0;+const pendingSearchFrames = new Map<number, () => void>();+onBeforeUnmount(() => {+ searchNavigationRevision++;+ for (const [frame, resolve] of pendingSearchFrames) {+ cancelAnimationFrame(frame);+ resolve();+ }+ pendingSearchFrames.clear();+});++function nextSearchFrame(): Promise<void> {+ return new Promise((resolve) => {+ const frame = requestAnimationFrame(() => {+ pendingSearchFrames.delete(frame);+ resolve();+ });+ pendingSearchFrames.set(frame, resolve);+ });+}++async function revealSearchMatch() {+ const revision = ++searchNavigationRevision;+ const match = props.searchMatches?.[props.activeSearchIndex ?? -1];+ if (!match) return;+ const overrides = new Map(expansionOverrides.value);+ overrides.set("", true);+ const segments = match.path.split("/");+ for (let i = 1; i < segments.length; i++) overrides.set(segments.slice(0, i).join("/"), true);+ expansionOverrides.value = overrides;+ await nextTick();+ if (revision !== searchNavigationRevision) return;+ const index = visibleNodes.value.findIndex((node) => node.path === match.path);+ if (props.virtualized && index >= 0) virtualScroller.value?.scrollToItem?.(index);+ // Virtual rows are published on animation frames, after scroll events and size+ // measurements. A Vue tick alone can still observe the old recycled rows.+ let visibleFrames = 0;+ for (let attempt = 0; attempt < 20; attempt++) {+ await nextSearchFrame();+ await nextTick();+ if (revision !== searchNavigationRevision) return;+ const target = treeRoot.value?.querySelector<HTMLElement>('[data-document-search-active="true"]');+ if (target && target.closest<HTMLElement>("[data-json-path]")?.dataset.jsonPath === match.path && target.getClientRects().length) {+ target.scrollIntoView({ block: "nearest", inline: "nearest" });+ // Correct again after dynamic row measurement has had time to settle.+ if (++visibleFrames >= 3) return;+ } else {+ visibleFrames = 0;+ if (props.virtualized && index >= 0) virtualScroller.value?.scrollToItem?.(index);+ }+ }+}+function escapeHtml(value: string): string {return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");}@@ -100,9 +168,8 @@ function nodeAccessibleLabel(node: JsonTreeNode): string {return node.path || "$";}-function highlightedJsonSpan(className: string, json: string): VNodeChild {- if (!props.highlightJson) return h("span", { class: className }, json);- return h("span", { class: className, innerHTML: props.highlightJson(json) });+function highlightedJsonSpan(className: string, text: string, node: JsonTreeNode, part: "key" | "value"): VNodeChild {+ return h("span", { class: className, innerHTML: highlightedJson(text, node, part) });}function renderJsonNode(node: JsonTreeNode): VNodeChild {@@ -132,7 +199,7 @@ function renderJsonNode(node: JsonTreeNode): VNodeChild {}if (node.parentKind !== "root") {- rowChildren.push(node.parentKind === "array" ? h("span", { class: "json-tree-index" }, `[${node.label}]`) : highlightedJsonSpan("json-tree-key", JSON.stringify(node.label)), h("span", { class: "json-tree-punctuation" }, ":"));+ rowChildren.push(highlightedJsonSpan(node.parentKind === "array" ? "json-tree-index" : "json-tree-key", jsonTreeKeyText(node), node, "key"), h("span", { class: "json-tree-punctuation" }, ":"));}if (containerValue !== undefined) {@@ -142,7 +209,7 @@ function renderJsonNode(node: JsonTreeNode): VNodeChild {rowChildren.push(h("span", { class: "json-tree-summary" }, jsonTreeContainerSummary(containerValue)), h("span", { class: `json-tree-bracket is-${kind}` }, kind === "array" ? "]" : "}"));}} else {- rowChildren.push(highlightedJsonSpan(scalarClass(node.value), scalarText(node.value)));+ rowChildren.push(highlightedJsonSpan(scalarClass(node.value), scalarText(node.value), node, "value"));}const children =@@ -178,15 +245,17 @@ watch([() => props.value, () => props.initialExpandedDepth], () => {refresh(true);});-defineExpose({ expandAll, collapseAll, resetExpansion, refresh });+watch([() => props.searchMatches, () => props.activeSearchIndex], revealSearchMatch, { flush: "post", immediate: true });++defineExpose({ expandAll, collapseAll, resetExpansion, refresh, revealSearchMatch });</script><template>- <div class="json-tree" :class="{ 'is-nowrap': !wordWrap, 'is-virtualized': virtualized }">+ <div ref="treeRoot" class="json-tree" :class="{ 'is-nowrap': !wordWrap, 'is-virtualized': virtualized }"><!-- Virtual rows keep a fully expanded response responsive even when it has thousands of nodes. --><DynamicScroller v-if="virtualized" ref="virtualScroller" :items="visibleNodes" :min-item-size="24" :buffer="600" key-field="path" class="json-tree-scroller"><template #default="{ item: node, active, index }">- <DynamicScrollerItem :item="node" :active="active" :size-dependencies="[wordWrap, node.path, node.label, scalarText(node.value), isNodeExpanded(node)]" :data-index="index">+ <DynamicScrollerItem :item="node" :active="active" :size-dependencies="[wordWrap, node.path, node.label, scalarText(node.value), isNodeExpanded(node), searchMatches, activeSearchIndex]" :data-index="index"><div class="json-tree-node" :data-json-path="node.path"><div class="json-tree-row" :style="{ paddingInlineStart: `${node.depth * 16}px` }"><template v-if="isJsonTreeClosingNode(node)">@@ -200,8 +269,7 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });<span v-else class="json-tree-spacer" aria-hidden="true" /><template v-if="node.parentKind !== 'root'">- <span v-if="node.parentKind === 'array'" class="json-tree-index">[{{ node.label }}]</span>- <span v-else class="json-tree-key" v-html="highlightedJson(JSON.stringify(node.label))" />+ <span :class="node.parentKind === 'array' ? 'json-tree-index' : 'json-tree-key'" v-html="highlightedJson(jsonTreeKeyText(node), node, 'key')" /><span class="json-tree-punctuation">:</span></template>@@ -212,7 +280,7 @@ defineExpose({ expandAll, collapseAll, resetExpansion, refresh });<span class="json-tree-bracket" :class="`is-${jsonTreeContainerKind(node.value)}`">{{ jsonTreeContainerKind(node.value) === "array" ? "]" : "}" }}</span></template></template>- <span v-else :class="scalarClass(node.value)" v-html="highlightedJson(scalarText(node.value))" />+ <span v-else :class="scalarClass(node.value)" v-html="highlightedJson(scalarText(node.value), node, 'value')" /></template></div></div>diff --git a/apps/desktop/src/components/common/TextContentSearchBar.vue b/apps/desktop/src/components/common/TextContentSearchBar.vueindex d10f2d30ec..55166114bb 100644--- a/apps/desktop/src/components/common/TextContentSearchBar.vue+++ b/apps/desktop/src/components/common/TextContentSearchBar.vue@@ -18,15 +18,34 @@ const props = withDefaults(matchCount: number;showNavigation?: boolean;placeholder?: string;+ showSearchOptions?: boolean;+ caseSensitive?: boolean;+ useRegex?: boolean;+ error?: string;+ allowReplace?: boolean;+ replaceText?: string;+ busy?: boolean;}>(),{showNavigation: true,placeholder: undefined,+ showSearchOptions: false,+ caseSensitive: false,+ useRegex: false,+ error: "",+ allowReplace: false,+ replaceText: "",+ busy: false,},);const emit = defineEmits<{"update:modelValue": [value: string];+ "update:caseSensitive": [value: boolean];+ "update:useRegex": [value: boolean];+ "update:replaceText": [value: string];+ replace: [];+ replaceAll: [];activate: [delta: -1 | 1];prev: [];next: [];@@ -35,6 +54,7 @@ const emit = defineEmits<{const { t } = useI18n();+const showReplace = ref(false);const inputRef = ref<HTMLInputElement | null>(null);/** Drag offset from the default top-right anchor (absolute right/top). */const offsetX = ref(0);@@ -52,6 +72,7 @@ function resolvedPlaceholder() {}function onEnter(event: KeyboardEvent) {+ if (props.busy) return;emit("activate", event.shiftKey ? -1 : 1);}@@ -143,12 +164,17 @@ defineExpose({ focusInput, inputEl: inputRef });<GripVertical class="pointer-events-none h-4 w-4" /></button>- <div class="flex h-8 w-64 items-center rounded-md border border-input bg-background focus-within:border-ring focus-within:ring-1 focus-within:ring-ring" data-no-drag @pointerdown.stop>+ <button v-if="allowReplace" type="button" class="flex h-7 w-5 shrink-0 items-center justify-center rounded hover:bg-accent" :title="t('editor.search.replace')" :aria-label="t('editor.search.replace')" :aria-expanded="showReplace" @pointerdown.stop @click="showReplace = !showReplace">+ <ChevronDown class="h-4 w-4" :class="{ '-rotate-90': !showReplace }" />+ </button>+ <div class="flex h-8 w-64 items-center rounded-md border border-input bg-background focus-within:border-ring focus-within:ring-1 focus-within:ring-ring" :class="{ 'border-destructive focus-within:border-destructive focus-within:ring-destructive': error }" data-no-drag @pointerdown.stop><inputref="inputRef"data-text-content-search-inputdata-redis-value-search-input:value="modelValue"+ :aria-invalid="Boolean(error)"+ :title="error || undefined"autocapitalize="off"autocomplete="off"autocorrect="off"@@ -162,6 +188,36 @@ defineExpose({ focusInput, inputEl: inputRef });@keydown.enter.prevent="onEnter"@keydown.escape.prevent.stop="emit('close')"/>+ <template v-if="showSearchOptions">+ <button+ type="button"+ class="flex h-6 min-w-7 shrink-0 items-center justify-center rounded px-1.5 text-xs font-medium transition-colors hover:bg-accent hover:text-foreground"+ :class="caseSensitive ? 'bg-accent text-foreground' : 'text-muted-foreground'"+ :title="t('editor.search.caseSensitive')"+ :aria-label="t('editor.search.caseSensitive')"+ :aria-pressed="caseSensitive"+ @click="+ emit('update:caseSensitive', !caseSensitive);+ focusInput(false);+ "+ >+ Aa+ </button>+ <button+ type="button"+ class="mr-1 flex h-6 min-w-7 shrink-0 items-center justify-center rounded px-1.5 font-mono text-xs transition-colors hover:bg-accent hover:text-foreground"+ :class="useRegex ? 'bg-accent text-foreground' : 'text-muted-foreground'"+ :title="t('editor.search.regex')"+ :aria-label="t('editor.search.regex')"+ :aria-pressed="useRegex"+ @click="+ emit('update:useRegex', !useRegex);+ focusInput(false);+ "+ >+ .*+ </button>+ </template></div><span data-search-drag-chrome class="min-w-[3.4rem] shrink-0 select-none text-center text-xs tabular-nums" :class="modelValue && matchCount === 0 ? 'text-destructive' : 'text-muted-foreground'">@@ -174,7 +230,7 @@ defineExpose({ focusInput, inputEl: inputRef });data-no-dragclass="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40":title="t('editor.search.prevMatch')"- :disabled="matchCount === 0"+ :disabled="busy || matchCount === 0"@pointerdown.stop@click="emit('prev')">@@ -185,7 +241,7 @@ defineExpose({ focusInput, inputEl: inputRef });data-no-dragclass="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40":title="t('editor.search.nextMatch')"- :disabled="matchCount === 0"+ :disabled="busy || matchCount === 0"@pointerdown.stop@click="emit('next')">@@ -197,6 +253,20 @@ defineExpose({ focusInput, inputEl: inputRef });<X class="h-4 w-4" /></button></div>+ <div v-if="allowReplace && showReplace" class="flex items-center gap-1 pl-8" data-no-drag @pointerdown.stop>+ <input+ :value="replaceText"+ class="h-8 min-w-0 flex-1 rounded-md border border-input bg-background px-2 text-sm outline-none focus:border-ring"+ :placeholder="t('editor.search.replace')"+ :aria-label="t('editor.search.replace')"+ @input="emit('update:replaceText', ($event.target as HTMLInputElement).value)"+ @keydown.enter.prevent="!busy && !error && matchCount > 0 && emit('replace')"+ @keydown.escape.prevent.stop="emit('close')"+ />+ <button type="button" class="h-7 shrink-0 rounded-md border border-border px-2 text-xs hover:bg-accent disabled:opacity-40" :disabled="busy || Boolean(error) || matchCount === 0" @click="emit('replace')">{{ t("editor.search.replace") }}</button>+ <button type="button" class="h-7 shrink-0 rounded-md border border-border px-2 text-xs hover:bg-accent disabled:opacity-40" :disabled="busy || Boolean(error) || matchCount === 0" @click="emit('replaceAll')">{{ t("editor.search.replaceAll") }}</button>+ </div>+ <p v-if="error" role="alert" class="px-2 text-xs text-destructive">{{ error }}</p></div></template>diff --git a/apps/desktop/src/components/redis/RedisJsonEditor.vue b/apps/desktop/src/components/redis/RedisJsonEditor.vueindex d95e55e5e6..6239e43465 100644--- a/apps/desktop/src/components/redis/RedisJsonEditor.vue+++ b/apps/desktop/src/components/redis/RedisJsonEditor.vue@@ -4,12 +4,19 @@ import { useCellDetailEditor } from "@/composables/useCellDetailEditor";import { useTheme } from "@/composables/useTheme";import { isSaveShortcut } from "@/lib/editor/keyboardShortcuts";import { useSettingsStore } from "@/stores/settingsStore";+import { EditorView } from "@codemirror/view";+import { StateEffect, Transaction } from "@codemirror/state";+import { isolateHistory } from "@codemirror/commands";+import { foldedRanges, unfoldEffect } from "@codemirror/language";+import { externalSearchHighlights, setExternalSearchHighlights, type ExternalSearchHighlight } from "@/lib/editor/codemirrorExternalSearchHighlights";defineOptions({ name: "RedisJsonEditor" });const props = withDefaults(defineProps<{modelValue: string;+ language?: "json" | "text";+ autofocus?: boolean;/** Save shortcuts are still consumed while disabled so global handlers cannot act on them. */saveDisabled?: boolean;readOnly?: boolean;@@ -23,8 +30,11 @@ const props = withDefaults(* Default true so DocumentBrowser and other callers keep CodeMirror find.*/enableBuiltinFind?: boolean;+ searchHighlights?: ExternalSearchHighlight[];}>(),{+ language: "json",+ autofocus: false,saveDisabled: false,readOnly: false,wordWrap: false,@@ -40,13 +50,15 @@ const emit = defineEmits<{}>();const editorContainer = ref<HTMLElement>();+let searchHighlightsInstalled = false;const settingsStore = useSettingsStore();const { isDark, themePalette } = useTheme();const editor = useCellDetailEditor({- language: "json",+ language: props.language,+ preserveLineEndings: props.language === "text",lineNumbers: props.lineNumbers,- folding: true,+ folding: props.language === "json",lineWrapping: () => props.wordWrap,readOnly: () => props.readOnly,enableBuiltinFind: props.enableBuiltinFind,@@ -69,6 +81,8 @@ watch(editorContainer, async (container) => {if (!container) return;await editor.create(container, props.modelValue, "json");if (editor.getValue() !== props.modelValue) editor.setValue(props.modelValue, "json");+ syncSearchHighlights();+ if (props.autofocus) editor.view.value?.focus();});watch(@@ -79,22 +93,82 @@ watch(},);+function syncSearchHighlights() {+ const view = editor.view.value;+ if (!view || (!props.searchHighlights && !searchHighlightsInstalled)) return;+ if (!searchHighlightsInstalled) {+ view.dispatch({ effects: StateEffect.appendConfig.of(externalSearchHighlights()) });+ searchHighlightsInstalled = true;+ }+ const highlights = props.searchHighlights ?? [];+ view.dispatch({ effects: setExternalSearchHighlights.of(highlights) });+ const active = highlights.find((highlight) => highlight.active);+ if (active && !view.hasFocus) selectRange(active.from, active.to, { focus: false });+}++watch([() => props.searchHighlights, () => props.modelValue], syncSearchHighlights, { flush: "post" });+function openSearch(): boolean {return editor.openSearch();}function selectRange(from: number, to: number, options?: { focus?: boolean }): boolean {+ const view = editor.view.value;+ if (view && props.searchHighlights !== undefined) {+ const effects: StateEffect<unknown>[] = [];+ // Reveal only folds containing the target; keep unrelated nodes collapsed.+ foldedRanges(view.state).between(from, to, (start, end) => {+ if (start < to && end > from) effects.push(unfoldEffect.of({ from: start, to: end }));+ });+ if (effects.length) view.dispatch({ effects });+ }+ if (view && props.searchHighlights !== undefined) {+ view.dispatch({ effects: EditorView.scrollIntoView(Math.max(0, Math.min(from, view.state.doc.length)), { y: "center" }) });+ if (options?.focus !== false) view.focus();+ return true;+ }return editor.selectRange(from, to, options);}-defineExpose({ openSearch, selectRange });+function replaceRanges(text: string, changes: { from: number; to: number; insert: string }[]): boolean {+ const view = editor.view.value;+ if (!view || props.readOnly || view.state.doc.toString() !== text || !changes.length) return false;+ view.dispatch({ changes, annotations: [Transaction.userEvent.of("input.replace"), isolateHistory.of("full")] });+ return true;+}++defineExpose({ openSearch, selectRange, replaceRanges, hasFocus: () => editor.view.value?.hasFocus ?? false });</script><template>- <div ref="editorContainer" class="h-full min-h-0 w-full" :class="{ 'redis-json-editor--viewer': presentation === 'viewer' }" data-redis-json-editor />+ <div ref="editorContainer" class="h-full min-h-0 w-full" :class="{ 'redis-json-editor--viewer': presentation === 'viewer', 'redis-json-editor--dark': isDark }" data-redis-json-editor /></template><style scoped>+:deep(.cm-externalSearchMatch),+:deep(.cm-externalSearchMatchActive) {+ border-radius: 2px;+ background: #fde68a;+}++:deep(.cm-externalSearchMatchActive) {+ background: #f59e0b;+ outline: 1px solid #d97706;+}++:deep(.cm-externalSearchMatchActive),+:deep(.cm-externalSearchMatchActive *) {+ color: #111827;+}++.redis-json-editor--dark :deep(.cm-externalSearchMatch) {+ background: #854d0e;+}++.redis-json-editor--dark :deep(.cm-externalSearchMatchActive) {+ background: #fbbf24;+}+.redis-json-editor--viewer :deep(.cm-editor) {background: transparent;}diff --git a/apps/desktop/src/components/redis/RedisValueViewer.collectionSearch.spec.ts b/apps/desktop/src/components/redis/RedisValueViewer.collectionSearch.spec.tsindex 8d5e924c75..663852ff87 100644--- a/apps/desktop/src/components/redis/RedisValueViewer.collectionSearch.spec.ts+++ b/apps/desktop/src/components/redis/RedisValueViewer.collectionSearch.spec.ts@@ -33,6 +33,30 @@ vi.mock("@/lib/common/shikiJsonHighlighter", () => ({createShikiJsonHighlighter: vi.fn().mockResolvedValue(() => ""),}));+// Exercise the viewer's draft binding without mounting CodeMirror and its stores.+vi.mock("@/components/redis/RedisJsonEditor.vue", async () => {+ const { defineComponent, h, onMounted, ref } = await import("vue");+ return {+ default: defineComponent({+ props: { modelValue: String, readOnly: Boolean, autofocus: Boolean },+ emits: ["update:modelValue"],+ setup(props, { emit }) {+ const input = ref<HTMLTextAreaElement>();+ onMounted(() => {+ if (props.autofocus) input.value?.focus();+ });+ return () =>+ h("textarea", {+ ref: input,+ value: props.modelValue,+ readonly: props.readOnly,+ onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLTextAreaElement).value),+ });+ },+ }),+ };+});+import RedisValueViewer from "./RedisValueViewer.vue";const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];diff --git a/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts b/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.tsindex 52e2e382fd..1a515c1392 100644--- a/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts+++ b/apps/desktop/src/components/redis/RedisValueViewer.expiry.spec.ts@@ -32,6 +32,30 @@ vi.mock("@/lib/common/shikiJsonHighlighter", () => ({createShikiJsonHighlighter: vi.fn().mockResolvedValue(() => ""),}));+// Exercise the viewer's draft binding without mounting CodeMirror and its stores.+vi.mock("@/components/redis/RedisJsonEditor.vue", async () => {+ const { defineComponent, h, onMounted, ref } = await import("vue");+ return {+ default: defineComponent({+ props: { modelValue: String, readOnly: Boolean, autofocus: Boolean },+ emits: ["update:modelValue"],+ setup(props, { emit }) {+ const input = ref<HTMLTextAreaElement>();+ onMounted(() => {+ if (props.autofocus) input.value?.focus();+ });+ return () =>+ h("textarea", {+ ref: input,+ value: props.modelValue,+ readonly: props.readOnly,+ onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLTextAreaElement).value),+ });+ },+ }),+ };+});+import RedisValueViewer from "./RedisValueViewer.vue";const mountedApps: Array<{ unmount: () => void; host: HTMLElement }> = [];diff --git a/apps/desktop/src/components/redis/RedisValueViewer.vue b/apps/desktop/src/components/redis/RedisValueViewer.vueindex 9c11a9542e..f212c2ce2f 100644--- a/apps/desktop/src/components/redis/RedisValueViewer.vue+++ b/apps/desktop/src/components/redis/RedisValueViewer.vue@@ -16,6 +16,9 @@ import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";+import { jsonTreeSearchParts, type JsonTreeSearchMatch } from "@/lib/common/jsonTreeSearch";+import { createTextContentSearchPattern, type TextContentMatch } from "@/lib/common/textContentSearch";+import { startRedisContentSearch } from "@/lib/redis/redisContentSearchJob";import JsonTree from "@/components/common/JsonTree.vue";import RedisJsonEditor from "@/components/redis/RedisJsonEditor.vue";import * as api from "@/lib/backend/api";@@ -63,7 +66,7 @@ import {type RedisValueFormat,} from "@/lib/redis/redisValuePresentation";import { decompressRedisValue, decodeBase64RedisValue, decodePickle, decodeProtobuf, isGzipMagic, type RedisDecompressAlgorithm } from "@/lib/redis/codec";-import { canFullHighlightRedisText, findRedisTextMatches, nextRedisSearchMatchIndex, REDIS_VALUE_SEARCH_MATCH_LIMIT, renderRedisTextSearchHtml, redisValueSearchStatus } from "@/lib/redis/redisValueSearch";+import { nextRedisSearchMatchIndex, REDIS_VALUE_SEARCH_MATCH_LIMIT, redisValueSearchStatus } from "@/lib/redis/redisValueSearch";import TextContentSearchBar from "@/components/common/TextContentSearchBar.vue";import RedisHorizontalScrollbar from "@/components/redis/RedisHorizontalScrollbar.vue";import { decodeJsonUnicodeEscapes, formatJsonSource, mapDisplayToRaw } from "@/lib/common/safeJsonFormat";@@ -409,6 +412,13 @@ const zsetSortDir = ref<"asc" | "desc">("asc");*/const valueSearchOpen = ref(false);const valueSearchQuery = ref("");+const valueReplaceText = ref("");+const valueSearchBusy = ref(false);+const valueSearchFailed = ref(false);+const valueSearchCaseSensitive = ref(false);+const valueSearchUseRegex = ref(false);+const valueSearchOptions = computed(() => ({ caseSensitive: valueSearchCaseSensitive.value, useRegex: valueSearchUseRegex.value }));+const valueSearchError = computed(() => (valueSearchUseRegex.value && valueSearchQuery.value && !createTextContentSearchPattern(valueSearchQuery.value, valueSearchOptions.value) ? t("dataGenerate.invalidRegex") : valueSearchFailed.value ? t("editor.search.searchFailed") : ""));const valueSearchMatchIndex = ref(0);const valueSearchHasNavigated = ref(false);const collectionSearchQuery = ref("");@@ -418,12 +428,16 @@ const collectionSearchState = shallowRef(emptyRedisCollectionSearchState());let collectionBrowseSnapshot: { items: RedisCollectionItem[]; cursor: number | undefined } | undefined;let collectionSearchIntentRevision = 0;const valueSearchBarRef = ref<{ focusInput: (select?: boolean) => void } | null>(null);-type JsonEditorHandle = { openSearch: () => boolean; selectRange?: (from: number, to: number, options?: { focus?: boolean }) => boolean };+type JsonEditorHandle = { replaceRanges?: (text: string, changes: { from: number; to: number; insert: string }[]) => boolean; hasFocus?: () => boolean; openSearch: () => boolean; selectRange?: (from: number, to: number, options?: { focus?: boolean }) => boolean };const stringJsonEditorRef = ref<JsonEditorHandle | null>(null);const redisJsonEditorRef = ref<JsonEditorHandle | null>(null);const memberJsonEditorRef = ref<JsonEditorHandle | null>(null);-const stringTextareaRef = ref<HTMLTextAreaElement | null>(null);-const memberTextareaRef = ref<HTMLTextAreaElement | null>(null);+const stringTextEditorRef = ref<JsonEditorHandle | null>(null);+const memberTextEditorRef = ref<JsonEditorHandle | null>(null);+const searchPreviewRef = ref<JsonEditorHandle | null>(null);+type SearchTreeHandle = { revealSearchMatch: () => Promise<void> };+const stringSearchTreeRef = ref<SearchTreeHandle | null>(null);+const memberSearchTreeRef = ref<SearchTreeHandle | null>(null);const valueViewerSearchActive = ref(false);function toggleHashSort(column: "field" | "value") {@@ -619,7 +633,7 @@ const memberDecodedText = computed<string | null>(() => {/** Raw fallback shown while a decompress codec fails: keep the original content visible, never an error string in its place. */const decompressedRawFallbackText = computed(() => {- if (isDecompressCodec(stringValueCodec.value) && stringValueDetail.value) {+ if (!showMemberDetail.value && isDecompressCodec(stringValueCodec.value) && stringValueDetail.value) {return detailTextForFormat(stringValueDetail.value, stringValueDetail.value.defaultFormat);}if (isDecompressCodec(memberValueCodec.value) && selectedMemberDetail.value) {@@ -837,23 +851,114 @@ const zsetRows = computed<RedisCollectionRow<RedisZsetItem>[]>(() =>})),);-const usesJsonEditorForMain = computed(() => (isStringLikeKind.value && stringValueView.value === "json" && Boolean(stringValueDetail.value?.json)) || redisKind.value === "json");-const usesJsonEditorForMember = computed(() => isEditingHashJson.value);/** True when Ctrl+F content find applies (STRING, RedisJSON, or open member detail). */const valueSearchSupported = computed(() => showMemberDetail.value || isStringLikeKind.value || redisKind.value === "json");-const contentSearchText = computed(() => {- if (showMemberDetail.value) {- if (isEditingMember.value || isEditingHashJson.value) return memberEditValue.value;- return memberDecodedText.value ?? detailTextForFormat(selectedMemberDetail.value, memberValueView.value);- }- if (redisKind.value === "json") return editValue.value;- if (!isStringLikeKind.value || !stringValueDetail.value) return "";- if (stringValueCodec.value !== "none") return stringDecodedText.value ?? "";- if (stringValueView.value === "json" && stringValueDetail.value.json) return editValue.value;- if (stringValueView.value === "utf8" && canEditCurrentStringFormat.value) return editValue.value;- return detailTextForFormat(stringValueDetail.value, stringValueView.value);+// Resolve exactly the surface rendered by the active codec/view, including fallbacks.+const activeSearchTree = computed(() => {+ const member = showMemberDetail.value;+ if (member && (isEditingMember.value || isEditingHashJson.value)) return null;+ const view = member ? memberValueView.value : stringValueView.value;+ const codec = member ? memberValueCodec.value : stringValueCodec.value;+ const detail = member ? selectedMemberDetail.value : stringValueDetail.value;+ if (view !== "json" || !detail || (!member && codec === "none")) return null;+ if (member && codec === "none" && detail.json) return detail.json;+ const structured = member ? activeStructuredMemberDetail.value : activeStructuredStringDetail.value;+ if (structured) return structured;+ const base64 = member ? memberBase64Detail.value : stringBase64Detail.value;+ if (codec === "base64" && base64?.json) return base64.json;+ if (isDecompressCodec(codec) && decompressedState.value.status === "success") return decompressedJsonDetail.value;+ return null;+});+const displayedSearchText = computed(() => {+ const member = showMemberDetail.value;+ if (member && (isEditingMember.value || isEditingHashJson.value)) return memberEditValue.value;+ if (!member && redisKind.value === "json") return editValue.value;+ const detail = member ? selectedMemberDetail.value : stringValueDetail.value;+ if (!detail) return "";+ const view = member ? memberValueView.value : stringValueView.value;+ const codec = member ? memberValueCodec.value : stringValueCodec.value;+ const mismatch = member ? memberCodecMismatch.value : stringCodecMismatch.value;+ // Codec mismatch takes precedence over the view controls in the renderer.+ if (mismatch) return detailTextForFormat(detail, detail.defaultFormat);+ if (view === "hex" || view === "base64") return detailTextForFormat(detail, view);+ if (isDecompressCodec(codec)) {+ if (decompressedState.value.status === "loading") return "";+ if (decompressedState.value.status !== "success") return detailTextForFormat(detail, detail.defaultFormat);+ }+ const decoded = member ? memberDecodedText.value : stringDecodedText.value;+ if (decoded !== null) return decoded;+ if (!member && codec === "none" && ((view === "json" && detail.json) || (view === "utf8" && canEditCurrentStringFormat.value))) return editValue.value;+ return detailTextForFormat(detail, view);});-const contentSearchMatches = computed(() => findRedisTextMatches(contentSearchText.value, valueSearchQuery.value));+// CodeMirror normalizes line endings; offsets must use the same document representation.+const contentSearchText = computed(() => displayedSearchText.value.replace(/\r\n?/g, "\n"));+const contentSearchMatches = shallowRef<(TextContentMatch | JsonTreeSearchMatch)[]>([]);+const treeSearchMatches = computed(() => (activeSearchTree.value ? (contentSearchMatches.value as JsonTreeSearchMatch[]) : []));+let contentSearchJob: ReturnType<typeof startRedisContentSearch> | undefined;+let contentSearchRevision = 0;+let nextReplacementOffset: number | undefined;+watch(+ [contentSearchText, activeSearchTree, valueSearchQuery, valueSearchCaseSensitive, valueSearchUseRegex, valueSearchOpen],+ async () => {+ const revision = ++contentSearchRevision;+ contentSearchJob?.cancel();+ contentSearchMatches.value = [];+ valueSearchFailed.value = false;+ valueSearchBusy.value = false;+ if (!valueSearchOpen.value || !valueSearchQuery.value || valueSearchError.value) return;+ valueSearchBusy.value = true;+ contentSearchJob = startRedisContentSearch({ text: contentSearchText.value, treeParts: activeSearchTree.value ? [...jsonTreeSearchParts(activeSearchTree.value.value)] : undefined, query: valueSearchQuery.value, options: valueSearchOptions.value });+ const result = await contentSearchJob.result;+ if (revision !== contentSearchRevision || !result) return;+ valueSearchBusy.value = false;+ valueSearchFailed.value = Boolean(result.error);+ contentSearchMatches.value = result.matches;+ if (nextReplacementOffset !== undefined) {+ const nextIndex = result.matches.findIndex((match) => match.start >= nextReplacementOffset!);+ valueSearchMatchIndex.value = Math.max(0, nextIndex);+ nextReplacementOffset = undefined;+ }+ if (!activeContentEditor()?.hasFocus?.()) void scrollContentSearchMatchIntoView();+ },+ { flush: "sync" },+);+onBeforeUnmount(() => {+ contentSearchRevision++;+ contentSearchJob?.cancel();+});+const valueCanReplace = computed(() => {+ if (activeSearchTree.value) return false;+ if (showMemberDetail.value) return (isEditingMember.value || isEditingHashJson.value) && !savingMember.value;+ if (redisKind.value === "json") return !savingJson.value;+ return stringValueCodec.value === "none" && canEditCurrentStringFormat.value && !savingString.value && (stringValueView.value === "utf8" || stringValueView.value === "json");+});+async function replaceValueMatches(all: boolean) {+ if (!valueCanReplace.value || valueSearchBusy.value || !contentSearchMatches.value.length) return;+ const revision = ++contentSearchRevision;+ const editor = activeContentEditor();+ const text = contentSearchText.value;+ contentSearchJob?.cancel();+ valueSearchBusy.value = true;+ contentSearchJob = startRedisContentSearch({ text, query: valueSearchQuery.value, options: valueSearchOptions.value, replacement: valueReplaceText.value, range: all ? undefined : contentSearchMatches.value[contentSearchActiveIndex.value] });+ const result = await contentSearchJob.result;+ if (revision !== contentSearchRevision || !result) return;+ valueSearchBusy.value = false;+ valueSearchFailed.value = Boolean(result.error);+ if (!result.error && result.changes?.length && valueCanReplace.value && editor === activeContentEditor() && text === contentSearchText.value) {+ const change = result.changes[0];+ nextReplacementOffset = all ? undefined : change.from + change.insert.replace(/\r\n?/g, "\n").length;+ if (!editor?.replaceRanges?.(text, result.changes)) {+ nextReplacementOffset = undefined;+ return;+ }+ // An unchanged value does not trigger the search watcher. Advance using+ // the existing matches rather than leaving navigation pending indefinitely.+ if (contentSearchText.value === text) {+ nextReplacementOffset = undefined;+ if (!all) moveContentSearchMatch(1);+ }+ }+}const contentSearchMatchLimited = computed(() => contentSearchMatches.value.length >= REDIS_VALUE_SEARCH_MATCH_LIMIT);const contentSearchActiveIndex = computed(() => {if (contentSearchMatches.value.length === 0) return 0;@@ -861,13 +966,21 @@ const contentSearchActiveIndex = computed(() => {});const valueSearchStatus = computed(() => redisValueSearchStatus(contentSearchActiveIndex.value, contentSearchMatches.value.length, contentSearchMatchLimited.value));const valueSearchMatchCount = computed(() => contentSearchMatches.value.length);-const contentSearchHighlightedHtml = computed(() => {- if (!valueSearchOpen.value || !valueSearchQuery.value) return "";- return renderRedisTextSearchHtml(contentSearchText.value, valueSearchQuery.value, contentSearchActiveIndex.value);+const contentSearchHighlights = computed(() => (valueSearchOpen.value && !activeSearchTree.value ? contentSearchMatches.value.map((match, index) => ({ from: match.start, to: match.end, active: index === contentSearchActiveIndex.value })) : []));+const stringSearchHighlights = computed(() => (showMemberDetail.value ? [] : contentSearchHighlights.value));+const memberSearchHighlights = computed(() => (showMemberDetail.value ? contentSearchHighlights.value : []));+const showSearchPreview = computed(() => {+ const codec = showMemberDetail.value ? memberValueCodec.value : stringValueCodec.value;+ const view = showMemberDetail.value ? memberValueView.value : stringValueView.value;+ const decoding = isDecompressCodec(codec) && decompressedState.value.status === "loading" && view !== "hex" && view !== "base64";+ return valueSearchOpen.value && Boolean(valueSearchQuery.value) && !activeSearchTree.value && !decoding;+});+const searchPreviewNotice = computed(() => {+ if (showMemberDetail.value ? memberCodecMismatch.value : stringCodecMismatch.value) return t("redis.codecMismatch");+ const codec = showMemberDetail.value ? memberValueCodec.value : stringValueCodec.value;+ const view = showMemberDetail.value ? memberValueView.value : stringValueView.value;+ return isDecompressCodec(codec) && view !== "hex" && view !== "base64" ? decompressedFailureMessage.value : "";});-const canHighlightContentSearch = computed(() => valueSearchOpen.value && Boolean(valueSearchQuery.value) && canFullHighlightRedisText(contentSearchText.value.length));-const canHighlightStringSurface = computed(() => canHighlightContentSearch.value && !showMemberDetail.value);-const canHighlightMemberSurface = computed(() => canHighlightContentSearch.value && showMemberDetail.value);let hashResizeStartX = 0;let hashResizeStartWidth = 0;@@ -2216,7 +2329,7 @@ function startEditMember() {memberFieldEditValue.value = selectedMemberContext.value.field ?? "";}isEditingMember.value = true;- nextTick(() => memberTextareaRef.value?.focus());+ // The text editor applies autofocus after its asynchronous initialization.}function cancelEditMember() {@@ -2740,41 +2853,30 @@ function activateValueSearchMatch(delta: -1 | 1) {moveContentSearchMatch(delta);}-/** Scroll value body to the active match without stealing focus from the find input. */-function scrollTextareaToMatch(textarea: HTMLTextAreaElement, match: { start: number; end: number }) {- const lineHeight = Number.parseFloat(getComputedStyle(textarea).lineHeight || "20") || 20;- const textBefore = textarea.value.slice(0, match.start);- const line = textBefore.split("\n").length - 1;- textarea.scrollTop = Math.max(0, line * lineHeight - textarea.clientHeight / 3);+function activeContentEditor(): JsonEditorHandle | null {+ if (showMemberDetail.value) {+ if (isEditingMember.value) return memberTextEditorRef.value;+ return isEditingHashJson.value ? memberJsonEditorRef.value : searchPreviewRef.value;+ }+ if (redisKind.value === "json") return redisJsonEditorRef.value;+ if (stringValueCodec.value === "none") {+ if (stringValueView.value === "json" && stringValueDetail.value?.json) return stringJsonEditorRef.value;+ if (stringValueView.value === "utf8" && canEditCurrentStringFormat.value) return stringTextEditorRef.value;+ }+ return searchPreviewRef.value;}-/**- * Never focus the value body here — the find panel must keep the caret so typing stays in the search box.- * Enter / prev / next only change the active match index and scroll the body into view.- */+/** Navigate within the active surface without moving focus out of the find input. */async function scrollContentSearchMatchIntoView() {await nextTick();+ if (activeSearchTree.value) {+ await (showMemberDetail.value ? memberSearchTreeRef.value : stringSearchTreeRef.value)?.revealSearchMatch();+ return;+ }const match = contentSearchMatches.value[contentSearchActiveIndex.value];if (!match) return;-- // CM: update selection + scroll, but do not focus (keeps find input active).- if (showMemberDetail.value) {- if (usesJsonEditorForMember.value && memberJsonEditorRef.value?.selectRange?.(match.start, match.end, { focus: false })) return;- if (isEditingMember.value && memberTextareaRef.value) {- scrollTextareaToMatch(memberTextareaRef.value, match);- return;- }- } else if (redisKind.value === "json") {- if (redisJsonEditorRef.value?.selectRange?.(match.start, match.end, { focus: false })) return;- } else {- if (usesJsonEditorForMain.value && stringJsonEditorRef.value?.selectRange?.(match.start, match.end, { focus: false })) return;- if (stringValueView.value === "utf8" && canEditCurrentStringFormat.value && stringTextareaRef.value) {- scrollTextareaToMatch(stringTextareaRef.value, match);- return;- }- }-- document.querySelector<HTMLElement>('[data-document-search-active="true"]')?.scrollIntoView({ block: "center", inline: "nearest" });+ const editor = activeContentEditor();+ editor?.selectRange?.(match.start, match.end, { focus: false });}/** Ctrl/Cmd+F on STRING body or member detail → floating find. */@@ -2789,17 +2891,18 @@ function handleValueViewerPointerDown(event: PointerEvent) {valueViewerSearchActive.value = target instanceof Element && !!target.closest("[data-redis-value-viewer], [data-redis-value-search], [data-text-content-search], [data-draggable-search-panel], [data-redis-member-detail]");}-watch(valueSearchQuery, () => {+watch([valueSearchQuery, valueSearchCaseSensitive, valueSearchUseRegex], () => {+ nextReplacementOffset = undefined;// Typing: recompute matches/highlights; keep caret in the find input.valueSearchMatchIndex.value = 0;valueSearchHasNavigated.value = false;if (valueSearchOpen.value) void scrollContentSearchMatchIntoView();});-watch(contentSearchText, () => {+watch([contentSearchText, activeSearchTree], () => {valueSearchMatchIndex.value = 0;valueSearchHasNavigated.value = false;- if (valueSearchOpen.value) void scrollContentSearchMatchIntoView();+ if (valueSearchOpen.value && !activeContentEditor()?.hasFocus?.()) void scrollContentSearchMatchIntoView();});watch(@@ -2882,13 +2985,22 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</script><template>- <div data-redis-value-viewer class="relative h-full flex flex-col overflow-hidden" :style="editorFontFamilyStyle">+ <div data-redis-value-viewer :class="{ 'redis-value-viewer--dark': isDark }" class="relative h-full flex flex-col overflow-hidden" :style="editorFontFamilyStyle"><!-- STRING body find — mounted inside the value pane (not teleported out of focus). --><TextContentSearchBarv-if="valueSearchOpen && data && valueSearchSupported && !showMemberDetail"ref="valueSearchBarRef"v-model="valueSearchQuery"- :status="valueSearchStatus"+ v-model:case-sensitive="valueSearchCaseSensitive"+ v-model:use-regex="valueSearchUseRegex"+ show-search-options+ v-model:replace-text="valueReplaceText"+ :allow-replace="valueCanReplace"+ :busy="valueSearchBusy"+ @replace="replaceValueMatches(false)"+ @replace-all="replaceValueMatches(true)"+ :error="valueSearchError"+ :status="valueSearchBusy ? t('common.loading') : valueSearchStatus":match-count="valueSearchMatchCount":show-navigation="true":placeholder="t('editor.search.find')"@@ -3058,6 +3170,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<RedisJsonEditorv-if="stringValueView === 'json' && stringValueDetail.json && stringValueCodec === 'none'"ref="stringJsonEditorRef"+ :search-highlights="stringSearchHighlights"v-model="editValue"class="min-h-0 flex-1":save-disabled="savingString || !stringValueChanged"@@ -3066,12 +3179,52 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving:enable-builtin-find="false"@save="saveString"/>+ <RedisJsonEditor+ v-else-if="stringValueView === 'utf8' && canEditCurrentStringFormat && stringValueCodec === 'none'"+ ref="stringTextEditorRef"+ v-model="editValue"+ language="text"+ presentation="viewer"+ :line-numbers="false"+ class="min-h-0 flex-1"+ :read-only="savingString"+ :word-wrap="redisJsonWordWrap"+ :search-highlights="stringSearchHighlights"+ :enable-builtin-find="false"+ :save-disabled="savingString || !stringValueChanged"+ @save="saveString"+ />+ <div v-else-if="showSearchPreview && !showMemberDetail" class="min-h-0 flex-1 flex flex-col overflow-hidden">+ <RedisJsonEditor ref="searchPreviewRef" :model-value="contentSearchText" language="text" :line-numbers="false" read-only presentation="viewer" class="min-h-0 flex-1" :word-wrap="redisJsonWordWrap" :search-highlights="stringSearchHighlights" :enable-builtin-find="false" />+ <div v-if="searchPreviewNotice" class="flex shrink-0 items-center gap-2 border-t px-4 py-2 text-xs text-muted-foreground">+ <span>{{ searchPreviewNotice }}</span>+ <Button v-if="!(showMemberDetail ? memberCodecMismatch : stringCodecMismatch) && decompressedState.status === 'error' && decompressedState.reason !== 'limit'" variant="outline" size="sm" @click="retryDecompressAsDeflate">{{ t("redis.decompressedRetryAsDeflate") }}</Button>+ </div>+ </div><div v-else-if="activeStructuredStringDetail && stringValueView !== 'hex' && stringValueView !== 'base64'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-4 text-sm leading-6">- <JsonTree v-if="stringValueView === 'json'" :value="activeStructuredStringDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <JsonTree+ ref="stringSearchTreeRef"+ :search-matches="!showMemberDetail ? treeSearchMatches : []"+ :active-search-index="contentSearchActiveIndex"+ v-if="stringValueView === 'json'"+ :value="activeStructuredStringDetail.value"+ :word-wrap="redisJsonWordWrap"+ :highlight-json="highlightRedisJson"+ virtualized+ /><pre v-else class="w-full min-w-0 max-w-full" :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'">{{ stringDecodedText }}</pre></div>- <div v-else-if="stringValueCodec === 'base64' && stringBase64Detail" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-4 text-sm leading-6">- <JsonTree v-if="stringValueView === 'json' && stringBase64Detail.json" :value="stringBase64Detail.json.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <div v-else-if="stringValueCodec === 'base64' && stringBase64Detail && stringValueView !== 'hex' && stringValueView !== 'base64'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-4 text-sm leading-6">+ <JsonTree+ ref="stringSearchTreeRef"+ :search-matches="!showMemberDetail ? treeSearchMatches : []"+ :active-search-index="contentSearchActiveIndex"+ v-if="stringValueView === 'json' && stringBase64Detail.json"+ :value="stringBase64Detail.json.value"+ :word-wrap="redisJsonWordWrap"+ :highlight-json="highlightRedisJson"+ virtualized+ /><pre v-else class="w-full min-w-0 max-w-full" :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'">{{ stringDecodedText }}</pre></div><div v-else-if="stringCodecMismatch" class="min-h-0 flex-1 flex flex-col overflow-hidden">@@ -3083,11 +3236,9 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<span>{{ t("grid.hexViewer") }}</span><span>{{ t("grid.hexViewerByteCount", { count: stringValueDetail.byteCount }) }}</span></div>- <pre v-if="stringValueDetail.hexRows.length > 0 && canHighlightStringSurface" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all" v-html="contentSearchHighlightedHtml" />- <pre v-else-if="stringValueDetail.hexRows.length > 0" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all">{{ detailTextForFormat(stringValueDetail, "hex") }}</pre>+ <pre v-if="stringValueDetail.hexRows.length > 0" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all">{{ detailTextForFormat(stringValueDetail, "hex") }}</pre><div v-else class="text-muted-foreground">{{ t("grid.hexViewerEmpty") }}</div></div>- <pre v-else-if="stringValueView === 'base64' && canHighlightStringSurface" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-4 text-sm leading-6 whitespace-pre-wrap break-all" v-html="contentSearchHighlightedHtml" /><pre v-else-if="stringValueView === 'base64'" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-4 text-sm leading-6 whitespace-pre-wrap break-all">{{ stringValueDetail.base64Text }}</pre><div v-else-if="isDecompressCodec(stringValueCodec)" class="min-h-0 flex-1 flex flex-col overflow-hidden"><div v-if="decompressedState.status === 'loading'" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-muted-foreground">@@ -3096,7 +3247,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</div><div v-else-if="decompressedState.status === 'success'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background"><div v-if="stringValueView === 'json' && decompressedJsonDetail" class="h-full p-4">- <JsonTree :value="decompressedJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <JsonTree ref="stringSearchTreeRef" :search-matches="!showMemberDetail ? treeSearchMatches : []" :active-search-index="contentSearchActiveIndex" :value="decompressedJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized /></div><pre v-else class="w-full min-w-0 max-w-full p-4 text-sm leading-6" :class="detailTextClass('utf8')">{{ stringDecodedText }}</pre></div>@@ -3118,16 +3269,6 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</div></template></div>- <textarea- v-else-if="stringValueView === 'utf8' && canEditCurrentStringFormat && stringValueCodec === 'none'"- ref="stringTextareaRef"- v-model="editValue"- class="dbx-editor-font-family flex-1 resize-none bg-background p-4 text-sm outline-none"- :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'"- :readonly="!canEditCurrentStringFormat || savingString"- spellcheck="false"- />- <pre v-else-if="canHighlightStringSurface" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-4 text-sm leading-6" :class="detailTextClass(stringValueView)" v-html="contentSearchHighlightedHtml" /><pre v-else class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-4 text-sm leading-6" :class="detailTextClass(stringValueView)">{{ detailTextForFormat(stringValueDetail, stringValueView) }}</pre><div v-if="isStringValueTruncated" data-redis-large-string-preview class="flex shrink-0 items-center gap-2 border-t bg-muted/30 px-4 py-2 text-xs text-muted-foreground"><Eye class="h-3.5 w-3.5 shrink-0" />@@ -3171,7 +3312,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<Switch size="sm" :model-value="redisJsonWordWrap" @update:model-value="setRedisJsonWordWrap(Boolean($event))" /></label></div>- <RedisJsonEditor ref="redisJsonEditorRef" v-model="editValue" class="min-h-0 flex-1" :save-disabled="savingJson || !redisJsonValueChanged" :read-only="savingJson" :word-wrap="redisJsonWordWrap" :enable-builtin-find="false" @save="saveJson" />+ <RedisJsonEditor :search-highlights="stringSearchHighlights" ref="redisJsonEditorRef" v-model="editValue" class="min-h-0 flex-1" :save-disabled="savingJson || !redisJsonValueChanged" :read-only="savingJson" :word-wrap="redisJsonWordWrap" :enable-builtin-find="false" @save="saveJson" /><div v-if="redisJsonValueChanged" class="px-4 py-2 border-t flex justify-end gap-2 shrink-0"><Button variant="ghost" size="sm" :disabled="savingJson" @click="discardRedisJsonEdit">{{ t("grid.discard") }}</Button><Button size="sm" :disabled="savingJson" @click="saveJson"><Loader2 v-if="savingJson" class="w-3 h-3 mr-1 animate-spin" /><Save v-else class="w-3 h-3 mr-1" /> {{ t("grid.save") }}</Button>@@ -3777,7 +3918,15 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</Dialog><Dialog :open="showMemberDetail" @update:open="handleMemberDetailOpenChange">- <DialogContent data-redis-member-detail class="relative flex h-[min(760px,85vh)] w-[calc(100vw-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[960px]" :style="editorFontFamilyStyle" @close-auto-focus="finishMemberDetailClose" @pointer-down-outside.prevent @interact-outside.prevent>+ <DialogContent+ data-redis-member-detail+ :class="{ 'redis-value-viewer--dark': isDark }"+ class="relative flex h-[min(760px,85vh)] w-[calc(100vw-2rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[960px]"+ :style="editorFontFamilyStyle"+ @close-auto-focus="finishMemberDetailClose"+ @pointer-down-outside.prevent+ @interact-outside.prevent+ ><!--Inside DialogContent (focus trap). absolute — not fixed — so dialogtransform/overflow do not break hit-testing or caret.@@ -3786,7 +3935,16 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || savingv-if="valueSearchOpen && showMemberDetail"ref="valueSearchBarRef"v-model="valueSearchQuery"- :status="valueSearchStatus"+ v-model:case-sensitive="valueSearchCaseSensitive"+ v-model:use-regex="valueSearchUseRegex"+ show-search-options+ v-model:replace-text="valueReplaceText"+ :allow-replace="valueCanReplace"+ :busy="valueSearchBusy"+ @replace="replaceValueMatches(false)"+ @replace-all="replaceValueMatches(true)"+ :error="valueSearchError"+ :status="valueSearchBusy ? t('common.loading') : valueSearchStatus":match-count="valueSearchMatchCount":show-navigation="true":placeholder="t('editor.search.find')"@@ -3808,7 +3966,22 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</DialogTitle></DialogHeader><template v-if="isEditingMember">- <textarea ref="memberTextareaRef" data-redis-member-utf8-editor v-model="memberEditValue" class="dbx-editor-font-family min-h-0 flex-1 resize-none bg-background p-5 text-[13px] leading-6 outline-none" :readonly="savingMember" spellcheck="false" />+ <RedisJsonEditor+ ref="memberTextEditorRef"+ presentation="viewer"+ data-redis-member-utf8-editor+ v-model="memberEditValue"+ language="text"+ :line-numbers="false"+ autofocus+ class="min-h-0 flex-1"+ :read-only="savingMember"+ :word-wrap="redisJsonWordWrap"+ :search-highlights="memberSearchHighlights"+ :enable-builtin-find="false"+ :save-disabled="savingMember || !memberValueChanged"+ @save="saveMemberEdit"+ /></template><template v-else><div class="flex h-9 items-center gap-2 border-b px-5 text-xs">@@ -3847,16 +4020,64 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<Button variant="ghost" size="sm" class="h-6 shrink-0 rounded-[5px] px-2 text-xs" :class="{ 'bg-background shadow-sm': redisJsonDecoded }" @click="setRedisJsonUnicodeMode('decoded')">{{ t("redis.jsonViewDecoded") }}</Button></div></div>- <RedisJsonEditor v-if="isEditingHashJson" ref="memberJsonEditorRef" v-model="memberEditValue" class="min-h-0 flex-1" :save-disabled="savingMember || !memberValueChanged" :read-only="savingMember" :word-wrap="redisJsonWordWrap" :enable-builtin-find="false" @save="saveMemberEdit" />+ <RedisJsonEditor+ :search-highlights="memberSearchHighlights"+ v-if="isEditingHashJson"+ ref="memberJsonEditorRef"+ v-model="memberEditValue"+ class="min-h-0 flex-1"+ :save-disabled="savingMember || !memberValueChanged"+ :read-only="savingMember"+ :word-wrap="redisJsonWordWrap"+ :enable-builtin-find="false"+ @save="saveMemberEdit"+ />+ <div v-else-if="showSearchPreview" class="min-h-0 flex-1 flex flex-col overflow-hidden">+ <RedisJsonEditor+ ref="searchPreviewRef"+ :model-value="contentSearchText"+ language="text"+ :line-numbers="false"+ read-only+ presentation="viewer"+ class="min-h-0 flex-1"+ :word-wrap="redisJsonWordWrap"+ :search-highlights="memberSearchHighlights"+ :enable-builtin-find="false"+ @dblclick="memberValueView === 'utf8' && memberValueCodec === 'none' && canEditCurrentMemberFormat && startEditMember()"+ />+ <div v-if="searchPreviewNotice" class="flex shrink-0 items-center gap-2 border-t px-4 py-2 text-xs text-muted-foreground">+ <span>{{ searchPreviewNotice }}</span>+ <Button v-if="!(showMemberDetail ? memberCodecMismatch : stringCodecMismatch) && decompressedState.status === 'error' && decompressedState.reason !== 'limit'" variant="outline" size="sm" @click="retryDecompressAsDeflate">{{ t("redis.decompressedRetryAsDeflate") }}</Button>+ </div>+ </div><div v-else-if="memberValueView === 'json' && selectedMemberDetail.json && memberValueCodec === 'none'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6">- <JsonTree :value="selectedMemberDetail.json.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <JsonTree ref="memberSearchTreeRef" :search-matches="showMemberDetail ? treeSearchMatches : []" :active-search-index="contentSearchActiveIndex" :value="selectedMemberDetail.json.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized /></div><div v-else-if="activeStructuredMemberDetail && memberValueView !== 'hex' && memberValueView !== 'base64'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6">- <JsonTree v-if="memberValueView === 'json'" :value="activeStructuredMemberDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <JsonTree+ ref="memberSearchTreeRef"+ :search-matches="showMemberDetail ? treeSearchMatches : []"+ :active-search-index="contentSearchActiveIndex"+ v-if="memberValueView === 'json'"+ :value="activeStructuredMemberDetail.value"+ :word-wrap="redisJsonWordWrap"+ :highlight-json="highlightRedisJson"+ virtualized+ /><pre v-else class="w-full min-w-0 max-w-full" :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'">{{ memberDecodedText }}</pre></div>- <div v-else-if="memberValueCodec === 'base64' && memberBase64Detail" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6">- <JsonTree v-if="memberValueView === 'json' && memberBase64Detail.json" :value="memberBase64Detail.json.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <div v-else-if="memberValueCodec === 'base64' && memberBase64Detail && memberValueView !== 'hex' && memberValueView !== 'base64'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background p-5 text-[13px] leading-6">+ <JsonTree+ ref="memberSearchTreeRef"+ :search-matches="showMemberDetail ? treeSearchMatches : []"+ :active-search-index="contentSearchActiveIndex"+ v-if="memberValueView === 'json' && memberBase64Detail.json"+ :value="memberBase64Detail.json.value"+ :word-wrap="redisJsonWordWrap"+ :highlight-json="highlightRedisJson"+ virtualized+ /><pre v-else class="w-full min-w-0 max-w-full" :class="redisJsonWordWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'">{{ memberDecodedText }}</pre></div><div v-else-if="memberCodecMismatch" class="min-h-0 flex-1 flex flex-col overflow-hidden">@@ -3868,11 +4089,9 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving<span>{{ t("grid.hexViewer") }}</span><span>{{ t("grid.hexViewerByteCount", { count: selectedMemberDetail.byteCount }) }}</span></div>- <pre v-if="selectedMemberDetail.hexRows.length > 0 && canHighlightMemberSurface" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all" v-html="contentSearchHighlightedHtml" />- <pre v-else-if="selectedMemberDetail.hexRows.length > 0" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all">{{ detailTextForFormat(selectedMemberDetail, "hex") }}</pre>+ <pre v-if="selectedMemberDetail.hexRows.length > 0" class="dbx-editor-font-family w-full min-w-0 max-w-full select-all whitespace-pre-wrap break-all">{{ detailTextForFormat(selectedMemberDetail, "hex") }}</pre><div v-else class="text-muted-foreground">{{ t("grid.hexViewerEmpty") }}</div></div>- <pre v-else-if="memberValueView === 'base64' && canHighlightMemberSurface" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-5 text-[13px] leading-6 whitespace-pre-wrap break-all" v-html="contentSearchHighlightedHtml" /><pre v-else-if="memberValueView === 'base64'" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-5 text-[13px] leading-6 whitespace-pre-wrap break-all">{{ selectedMemberDetail.base64Text }}</pre><div v-else-if="isDecompressCodec(memberValueCodec)" class="min-h-0 flex-1 flex flex-col overflow-hidden"><div v-if="decompressedState.status === 'loading'" class="flex min-h-0 flex-1 items-center justify-center gap-2 text-muted-foreground">@@ -3881,7 +4100,7 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</div><div v-else-if="decompressedState.status === 'success'" class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background"><div v-if="memberValueView === 'json' && decompressedJsonDetail" class="h-full p-5">- <JsonTree :value="decompressedJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized />+ <JsonTree ref="memberSearchTreeRef" :search-matches="showMemberDetail ? treeSearchMatches : []" :active-search-index="contentSearchActiveIndex" :value="decompressedJsonDetail.value" :word-wrap="redisJsonWordWrap" :highlight-json="highlightRedisJson" virtualized /></div><pre v-else class="w-full min-w-0 max-w-full p-5 text-[13px] leading-6" :class="detailTextClass('utf8')">{{ memberDecodedText }}</pre></div>@@ -3904,10 +4123,8 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || saving</template></div><div v-else-if="memberValueView === 'utf8' && canEditCurrentMemberFormat && memberValueCodec === 'none'" data-redis-member-utf8-viewer class="dbx-editor-font-family min-h-0 flex-1 overflow-auto bg-background text-[13px] leading-6 cursor-text" @dblclick.self.prevent="startEditMember">- <pre v-if="canHighlightMemberSurface" data-redis-member-utf8-text class="inline-block min-w-0 p-5 align-top select-text" :class="[detailTextClass('utf8'), redisJsonWordWrap ? 'max-w-full' : 'min-w-max']" v-html="contentSearchHighlightedHtml" />- <pre v-else data-redis-member-utf8-text class="inline-block min-w-0 p-5 align-top select-text" :class="[detailTextClass('utf8'), redisJsonWordWrap ? 'max-w-full' : 'min-w-max']">{{ detailTextForFormat(selectedMemberDetail, "utf8") }}</pre>+ <pre data-redis-member-utf8-text class="inline-block min-w-0 p-5 align-top select-text" :class="[detailTextClass('utf8'), redisJsonWordWrap ? 'max-w-full' : 'min-w-max']">{{ detailTextForFormat(selectedMemberDetail, "utf8") }}</pre></div>- <pre v-else-if="canHighlightMemberSurface" class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-5 text-[13px] leading-6" :class="detailTextClass(memberValueView)" v-html="contentSearchHighlightedHtml" /><pre v-else class="dbx-editor-font-family min-h-0 w-full min-w-0 max-w-full flex-1 overflow-auto bg-background p-5 text-[13px] leading-6" :class="detailTextClass(memberValueView)">{{ detailTextForFormat(selectedMemberDetail, memberValueView) }}</pre></template><DialogFooter class="mx-0 mb-0 shrink-0 border-t px-5 py-3">@@ -3961,13 +4178,13 @@ useUpdateBlocker(() => (hasUnsavedRedisDraft.value || editingTtl.value || savingoutline: 1px solid #d97706;}-:global(.dark) :deep(.document-search-match),-:global(.dark) :deep(.redis-value-search-match) {+.redis-value-viewer--dark :deep(.document-search-match),+.redis-value-viewer--dark :deep(.redis-value-search-match) {background: #854d0e;}-:global(.dark) :deep(.document-search-match-active),-:global(.dark) :deep(.redis-value-search-match-active) {+.redis-value-viewer--dark :deep(.document-search-match-active),+.redis-value-viewer--dark :deep(.redis-value-search-match-active) {background: #fbbf24;color: #111827;}diff --git a/apps/desktop/src/composables/useCellDetailEditor.ts b/apps/desktop/src/composables/useCellDetailEditor.tsindex 4936372982..f66044b34d 100644--- a/apps/desktop/src/composables/useCellDetailEditor.ts+++ b/apps/desktop/src/composables/useCellDetailEditor.ts@@ -20,6 +20,7 @@ import type { EditorTheme } from "@/stores/settingsStore";import type { AppThemeAppearance, AppThemePalette } from "@/lib/app/appTheme";import { selectAllCellDetailText } from "@/lib/dataGrid/cellDetailSelection";import { selectLineEnds } from "@/lib/editor/selectLineEnds";+import { preserveSourceHistory, rawSourceField, restoreRawSource } from "@/lib/editor/preserveTextLineEndings";export interface UseCellDetailEditorOptions {onChange?: (value: string) => void;@@ -27,7 +28,9 @@ export interface UseCellDetailEditorOptions {onBlur?: () => void;/** Return true after handling a save shortcut so CodeMirror consumes it. */onSaveShortcut?: (event: KeyboardEvent) => boolean;- language?: "auto" | "json";+ language?: "auto" | "json" | "text";+ /** Keep source line endings and suppress change events during external text synchronization. */+ preserveLineEndings?: boolean;readOnly?: boolean | (() => boolean);/** Keep cell detail editors gutter-free unless a caller explicitly opts in. */lineNumbers?: boolean;@@ -87,6 +90,7 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCelconst shortcutComp = new Compartment();let destroyed = false;+ let synchronizingValue = false;let currentIsJson = false;let liveFontSize = clampEditorFontSize(options.fontSize());let gestureStartFontSize = liveFontSize;@@ -213,7 +217,7 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCelif (destroyed) return;const doc = initialValue ?? "";- currentIsJson = options.language === "json" || shouldUseJsonMode(columnType, doc);+ currentIsJson = options.language !== "text" && (options.language === "json" || shouldUseJsonMode(columnType, doc));const theme = await loadEditorTheme(options.editorTheme(), options.appAppearance(), undefined, options.appPalette());if (destroyed) return;@@ -236,6 +240,7 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCel...(options.folding ? [createConsistentFoldGutter()] : []),highlightSpecialChars(),history(),+ ...(options.preserveLineEndings ? preserveSourceHistory(doc) : []),drawSelection(),editorClipboardLineEndingsExtension(EditorView),trimmedSelectionLayer(),@@ -290,7 +295,12 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCel]),EditorView.updateListener.of((update) => {if (update.docChanged) {- options.onChange?.(update.state.doc.toString());+ if (options.preserveLineEndings) {+ if (synchronizingValue) return;+ options.onChange?.(update.state.field(rawSourceField));+ } else {+ options.onChange?.(update.state.doc.toString());+ }}}),EditorView.domEventHandlers({@@ -351,7 +361,7 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCelif (!editor || destroyed) return;const text = value ?? "";- const newIsJson = options.language === "json" || shouldUseJsonMode(columnType, text);+ const newIsJson = options.language !== "text" && (options.language === "json" || shouldUseJsonMode(columnType, text));const effects: ReturnType<typeof Compartment.prototype.reconfigure>[] = [];if (newIsJson !== currentIsJson) {@@ -359,13 +369,19 @@ export function useCellDetailEditor(options: UseCellDetailEditorOptions): UseCelcurrentIsJson = newIsJson;}- editor.dispatch({- changes: { from: 0, to: editor.state.doc.length, insert: text },- effects,- });+ synchronizingValue = true;+ try {+ editor.dispatch({+ changes: { from: 0, to: editor.state.doc.length, insert: text },+ effects: options.preserveLineEndings ? [...effects, restoreRawSource.of(text)] : effects,+ });+ } finally {+ synchronizingValue = false;+ }}function getValue(): string {+ if (options.preserveLineEndings && view.value) return view.value.state.field(rawSourceField);return view.value?.state.doc.toString() ?? "";}diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.tsindex 8ccdc1dfb9..1a3e275b97 100644--- a/apps/desktop/src/i18n/locales/az.ts+++ b/apps/desktop/src/i18n/locales/az.ts@@ -1590,6 +1590,7 @@ export default withEnglishFallback({find: "Tap",replace: "Əvəz et",replaceAll: "Hamısını əvəz et",+ searchFailed: "Axtarış uğursuz oldu və ya vaxtı bitdi. İfadəni sadələşdirib yenidən cəhd edin.",caseSensitive: "Böyük və kiçik hərflərə həssas",regex: "Müntəzəm ifadə",collapseReplace: "Əvəzetməni yığ",diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 84b42c288b..135327756f 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1964,6 +1964,7 @@ export default {find: "Find",replace: "Replace",replaceAll: "Replace All",+ searchFailed: "Search failed or timed out. Simplify the expression and try again.",caseSensitive: "Case sensitive",regex: "Regular expression",collapseReplace: "Collapse replace",diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 0e4dfd9964..b05cf01c57 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1934,6 +1934,7 @@ export default withEnglishFallback({find: "Buscar",replace: "Reemplazar",replaceAll: "Reemplazar todo",+ searchFailed: "La búsqueda falló o agotó el tiempo. Simplifica la expresión e inténtalo de nuevo.",caseSensitive: "Distinguir mayúsculas",regex: "Expresión regular",collapseReplace: "Contraer reemplazo",diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.tsindex cbd4eb5c1a..9ed77accb0 100644--- a/apps/desktop/src/i18n/locales/id.ts+++ b/apps/desktop/src/i18n/locales/id.ts@@ -1854,6 +1854,7 @@ export default withEnglishFallback({find: "Cari",replace: "Ganti",replaceAll: "Ganti Semua",+ searchFailed: "Pencarian gagal atau kehabisan waktu. Sederhanakan ekspresi dan coba lagi.",caseSensitive: "Case sensitive",regex: "Ekspresi reguler",collapseReplace: "Ciutkan ganti",diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 1fd7a85bf3..7f7f9c1c7a 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1843,6 +1843,7 @@ export default withEnglishFallback({find: "Trova",replace: "Sostituisci",replaceAll: "Sostituisci Tutto",+ searchFailed: "Ricerca non riuscita o scaduta. Semplifica l’espressione e riprova.",caseSensitive: "Maiuscole/Minuscole",regex: "Espressione regolare",collapseReplace: "Comprimi sostituzione",diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex b72b5ef3bd..f25a8ec3d5 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1863,6 +1863,7 @@ export default withEnglishFallback({find: "検索",replace: "置換",replaceAll: "すべて置換",+ searchFailed: "検索に失敗したかタイムアウトしました。式を簡略化して再試行してください。",caseSensitive: "大文字/小文字を区別",regex: "正規表現",collapseReplace: "置換を折りたたむ",diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 1a575055a4..362fd9cce7 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1790,6 +1790,7 @@ export default withEnglishFallback({find: "찾기",replace: "바꾸기",replaceAll: "모두 바꾸기",+ searchFailed: "검색에 실패했거나 시간이 초과되었습니다. 표현식을 간단히 하고 다시 시도하세요.",caseSensitive: "대소문자 구분",regex: "정규 표현식",collapseReplace: "바꾸기 접기",diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 2490aa1fe5..f49e85e7fd 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1844,6 +1844,7 @@ export default withEnglishFallback({find: "Localizar",replace: "Substituir",replaceAll: "Substituir Tudo",+ searchFailed: "A busca falhou ou excedeu o tempo. Simplifique a expressão e tente novamente.",caseSensitive: "Diferenciar maiúsculas/minúsculas",regex: "Expressão regular",collapseReplace: "Recolher substituição",diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.tsindex 9b99ceee3b..90c55056ff 100644--- a/apps/desktop/src/i18n/locales/ru.ts+++ b/apps/desktop/src/i18n/locales/ru.ts@@ -1871,6 +1871,7 @@ export default withEnglishFallback({find: "Найти",replace: "Заменить",replaceAll: "Заменить всё",+ searchFailed: "Поиск не выполнен или превышено время ожидания. Упростите выражение и повторите попытку.",caseSensitive: "Учитывать регистр",regex: "Регулярное выражение",collapseReplace: "Свернуть замену",diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.tsindex d7219170b5..d9e817cea6 100644--- a/apps/desktop/src/i18n/locales/tr.ts+++ b/apps/desktop/src/i18n/locales/tr.ts@@ -1589,6 +1589,7 @@ export default withEnglishFallback({find: "Bul",replace: "Değiştir",replaceAll: "Tümünü Değiştir",+ searchFailed: "Arama başarısız oldu veya zaman aşımına uğradı. İfadeyi basitleştirip tekrar deneyin.",caseSensitive: "Büyük/küçük harfe duyarlı",regex: "Düzenli ifade",collapseReplace: "Değiştirmeyi daralt",diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 2055bc1230..a270aeb854 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1900,6 +1900,7 @@ export default withEnglishFallback({find: "查找",replace: "替换",replaceAll: "全部替换",+ searchFailed: "搜索失败或超时,请简化表达式后重试。",caseSensitive: "区分大小写",regex: "正则表达式",collapseReplace: "收起替换",diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 3256d8f6d6..f51eb07cf2 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1847,6 +1847,7 @@ export default withEnglishFallback({find: "尋找",replace: "取代",replaceAll: "全部取代",+ searchFailed: "搜尋失敗或逾時,請簡化運算式後重試。",caseSensitive: "區分大小寫",regex: "正規表示式",collapseReplace: "收起取代",diff --git a/apps/desktop/src/lib/common/jsonTreeSearch.ts b/apps/desktop/src/lib/common/jsonTreeSearch.tsnew file mode 100644index 0000000000..9b99b56762--- /dev/null+++ b/apps/desktop/src/lib/common/jsonTreeSearch.ts@@ -0,0 +1,54 @@+import { createJsonTreeRoot, getJsonTreeChildren, isJsonTreeContainer, type JsonTreeNode } from "./jsonTree";+import { isLosslessJsonNumber } from "./safeJsonFormat";+import { findTextContentMatches, TEXT_CONTENT_SEARCH_MATCH_LIMIT, type TextContentSearchOptions } from "./textContentSearch";++export function jsonTreeScalarText(value: unknown): string {+ if (isLosslessJsonNumber(value)) return value.raw;+ if (typeof value === "string") return JSON.stringify(value);+ if (value === null) return "null";+ return String(value);+}++export interface JsonTreeSearchMatch {+ path: string;+ part: "key" | "value";+ start: number;+ end: number;+}++export interface JsonTreeSearchPart {+ path: string;+ part: "key" | "value";+ text: string;+}++/** Render before crossing the worker boundary: lossless numbers use symbol tags. */+export function* jsonTreeSearchParts(value: unknown): Generator<JsonTreeSearchPart> {+ const pending = [createJsonTreeRoot(value)];+ while (pending.length) {+ const node = pending.pop()!;+ if (node.parentKind !== "root") yield { path: node.path, part: "key", text: jsonTreeKeyText(node) };+ if (!isJsonTreeContainer(node.value)) yield { path: node.path, part: "value", text: jsonTreeScalarText(node.value) };+ const children = getJsonTreeChildren(node);+ for (let index = children.length - 1; index >= 0; index--) pending.push(children[index]);+ }+}++export function findJsonTreePartMatches(parts: Iterable<JsonTreeSearchPart>, query: string, options: TextContentSearchOptions = {}): JsonTreeSearchMatch[] {+ if (!query) return [];+ const result: JsonTreeSearchMatch[] = [];+ for (const { path, part, text } of parts) {+ for (const match of findTextContentMatches(text, query, TEXT_CONTENT_SEARCH_MATCH_LIMIT - result.length, options)) result.push({ ...match, path, part });+ if (result.length >= TEXT_CONTENT_SEARCH_MATCH_LIMIT) break;+ }+ return result;+}++/** Search the tree's rendered labels and scalars, including collapsed nodes. */+export function findJsonTreeMatches(value: unknown, query: string, options: TextContentSearchOptions = {}): JsonTreeSearchMatch[] {+ return findJsonTreePartMatches(jsonTreeSearchParts(value), query, options);+}++export function jsonTreeKeyText(node: JsonTreeNode): string {+ return node.parentKind === "array" ? `[${node.label}]` : JSON.stringify(node.label);+}diff --git a/apps/desktop/src/lib/common/textContentSearch.ts b/apps/desktop/src/lib/common/textContentSearch.tsindex 2f0b34232d..6855487a45 100644--- a/apps/desktop/src/lib/common/textContentSearch.ts+++ b/apps/desktop/src/lib/common/textContentSearch.ts@@ -7,6 +7,20 @@ export interface TextContentMatch {end: number;}+export interface TextContentSearchOptions {+ caseSensitive?: boolean;+ useRegex?: boolean;+}++/** Null denotes an invalid expression; callers can display a localized error. */+export function createTextContentSearchPattern(query: string, options: TextContentSearchOptions = {}): RegExp | null {+ try {+ return new RegExp(options.useRegex ? query : escapeRegExp(query), options.caseSensitive ? "gu" : "giu");+ } catch {+ return null;+ }+}+export interface TextContentSearchRenderOptions {activeMatchIndex?: number;matchClass?: string;@@ -15,12 +29,15 @@ export interface TextContentSearchRenderOptions {activeAttribute?: (index: number) => string;}-export function findTextContentMatches(text: string, query: string, limit = TEXT_CONTENT_SEARCH_MATCH_LIMIT): TextContentMatch[] {+export function findTextContentMatches(text: string, query: string, limit = TEXT_CONTENT_SEARCH_MATCH_LIMIT, options: TextContentSearchOptions = {}): TextContentMatch[] {if (!query || limit <= 0) return [];// Match the original UTF-16 text so Unicode case folding keeps offsets valid.- const pattern = new RegExp(escapeRegExp(query), "giu");+ const pattern = createTextContentSearchPattern(query, options);+ if (!pattern) return [];const matches: TextContentMatch[] = [];for (const match of text.matchAll(pattern)) {+ // matchAll advances safely over zero-width matches, including Unicode text.+ if (match[0].length === 0) continue;matches.push({ start: match.index, end: match.index + match[0].length });if (matches.length >= limit) break;}diff --git a/apps/desktop/src/lib/editor/codemirrorExternalSearchHighlights.ts b/apps/desktop/src/lib/editor/codemirrorExternalSearchHighlights.tsnew file mode 100644index 0000000000..4b7f60fecf--- /dev/null+++ b/apps/desktop/src/lib/editor/codemirrorExternalSearchHighlights.ts@@ -0,0 +1,39 @@+import { StateEffect, StateField, type Extension } from "@codemirror/state";+import { Decoration, EditorView, type DecorationSet } from "@codemirror/view";++export interface ExternalSearchHighlight {+ from: number;+ to: number;+ active?: boolean;+}++export const setExternalSearchHighlights = StateEffect.define<ExternalSearchHighlight[]>();++const matchDecoration = Decoration.mark({ class: "cm-externalSearchMatch" });+const activeMatchDecoration = Decoration.mark({ class: "cm-externalSearchMatchActive" });++function buildDecorations(highlights: readonly ExternalSearchHighlight[], length: number): DecorationSet {+ const ranges = highlights+ .filter(({ from, to }) => Number.isFinite(from) && Number.isFinite(to) && from < to)+ .flatMap(({ from, to, active }) => {+ const start = Math.max(0, Math.min(from, length));+ const end = Math.max(start, Math.min(to, length));+ return start < end ? [(active ? activeMatchDecoration : matchDecoration).range(start, end)] : [];+ })+ .sort((a, b) => a.from - b.from || a.to - b.to);+ return ranges.length ? Decoration.set(ranges) : Decoration.none;+}++export function externalSearchHighlights(): Extension {+ return StateField.define<DecorationSet>({+ create: () => Decoration.none,+ update(value, transaction) {+ let next = transaction.docChanged ? value.map(transaction.changes) : value;+ for (const effect of transaction.effects) {+ if (effect.is(setExternalSearchHighlights)) next = buildDecorations(effect.value, transaction.state.doc.length);+ }+ return next;+ },+ provide: (field) => EditorView.decorations.from(field),+ });+}diff --git a/apps/desktop/src/lib/editor/preserveTextLineEndings.ts b/apps/desktop/src/lib/editor/preserveTextLineEndings.tsnew file mode 100644index 0000000000..686adc7abd--- /dev/null+++ b/apps/desktop/src/lib/editor/preserveTextLineEndings.ts@@ -0,0 +1,46 @@+import { StateEffect, StateField, type ChangeSet } from "@codemirror/state";+import { invertedEffects } from "@codemirror/commands";++/** Apply normalized editor offsets without rewriting untouched source line endings. */+export function applyChangesPreservingLineEndings(source: string, changes: ChangeSet): string {+ const lineEnding = source.match(/\r\n|\r|\n/)?.[0] ?? "\n";+ let rawOffset = 0;+ let documentOffset = 0;+ function sourceOffset(target: number): number {+ while (documentOffset < target && rawOffset < source.length) {+ if (source[rawOffset] === "\r" && source[rawOffset + 1] === "\n") rawOffset++;+ rawOffset++;+ documentOffset++;+ }+ return rawOffset;+ }++ const parts: string[] = [];+ let copiedUntil = 0;+ changes.iterChanges((from, to, _fromNew, _toNew, inserted) => {+ const start = sourceOffset(from);+ const end = sourceOffset(to);+ parts.push(source.slice(copiedUntil, start), inserted.sliceString(0, inserted.length, lineEnding));+ copiedUntil = end;+ });+ parts.push(source.slice(copiedUntil));+ return parts.join("");+}++// Store raw source alongside the normalized document and include it in undo/redo.+export const restoreRawSource = StateEffect.define<string>();+export const rawSourceField = StateField.define<string>({+ create: () => "",+ update(source, transaction) {+ // Grouped history events carry newest-to-oldest inverse effects.+ for (let index = transaction.effects.length - 1; index >= 0; index--) {+ const effect = transaction.effects[index];+ if (effect.is(restoreRawSource)) return effect.value;+ }+ return transaction.docChanged ? applyChangesPreservingLineEndings(source, transaction.changes) : source;+ },+});++export function preserveSourceHistory(source: string) {+ return [rawSourceField.init(() => source), invertedEffects.of((transaction) => (transaction.docChanged || transaction.effects.some((effect) => effect.is(restoreRawSource)) ? [restoreRawSource.of(transaction.startState.field(rawSourceField))] : []))];+}diff --git a/apps/desktop/src/lib/redis/redisContentSearch.worker.ts b/apps/desktop/src/lib/redis/redisContentSearch.worker.tsnew file mode 100644index 0000000000..5e2ec8a818--- /dev/null+++ b/apps/desktop/src/lib/redis/redisContentSearch.worker.ts@@ -0,0 +1,38 @@+import { findJsonTreePartMatches } from "../common/jsonTreeSearch";+import { createTextContentSearchPattern, findTextContentMatches, TEXT_CONTENT_SEARCH_MATCH_LIMIT } from "../common/textContentSearch";+import type { RedisContentSearchRequest } from "./redisContentSearchJob";++self.onmessage = ({ data }: MessageEvent<RedisContentSearchRequest>) => {+ try {+ if (data.treeParts !== undefined) {+ self.postMessage({ matches: findJsonTreePartMatches(data.treeParts, data.query, data.options) });+ return;+ }+ if (data.replacement === undefined) {+ self.postMessage({ matches: findTextContentMatches(data.text, data.query, TEXT_CONTENT_SEARCH_MATCH_LIMIT, data.options) });+ return;+ }+ const pattern = createTextContentSearchPattern(data.query, data.options);+ const changes: { from: number; to: number; insert: string }[] = [];+ if (pattern && data.query) {+ for (const match of data.text.matchAll(pattern)) {+ if (!match[0].length) continue;+ if (data.range && (match.index !== data.range.start || match.index + match[0].length !== data.range.end)) continue;+ // Use captures from the original document so lookarounds retain context.+ const insert = data.options.useRegex+ ? data.replacement.replace(/\$(\$|\d+|&)/g, (token, ref: string) => {+ if (ref === "$") return "$";+ if (ref === "&") return match[0];+ const index = Number(ref);+ return index > 0 && index < match.length ? (match[index] ?? "") : token;+ })+ : data.replacement;+ changes.push({ from: match.index, to: match.index + match[0].length, insert });+ if (data.range) break;+ }+ }+ self.postMessage({ matches: [], changes });+ } catch {+ self.postMessage({ matches: [], error: true });+ }+};diff --git a/apps/desktop/src/lib/redis/redisContentSearchJob.ts b/apps/desktop/src/lib/redis/redisContentSearchJob.tsnew file mode 100644index 0000000000..f6083cfc5c--- /dev/null+++ b/apps/desktop/src/lib/redis/redisContentSearchJob.ts@@ -0,0 +1,41 @@+import type { TextContentMatch, TextContentSearchOptions } from "../common/textContentSearch";+import type { JsonTreeSearchMatch, JsonTreeSearchPart } from "../common/jsonTreeSearch";++export interface RedisContentSearchRequest {+ text: string;+ query: string;+ options: TextContentSearchOptions;+ treeParts?: JsonTreeSearchPart[];+ replacement?: string;+ range?: TextContentMatch;+}+export interface RedisContentSearchResult {+ matches: (TextContentMatch | JsonTreeSearchMatch)[];+ changes?: { from: number; to: number; insert: string }[];+ error?: boolean;+}++/** Each job owns a worker, allowing cancellation even during regex backtracking. */+export function startRedisContentSearch(request: RedisContentSearchRequest) {+ let cancel = () => {};+ const result = new Promise<RedisContentSearchResult | null>((resolve) => {+ let worker: Worker | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const finish = (value: RedisContentSearchResult | null) => {+ clearTimeout(timer);+ worker?.terminate();+ resolve(value);+ };+ cancel = () => finish(null);+ try {+ worker = new Worker(new URL("./redisContentSearch.worker.ts", import.meta.url), { type: "module" });+ worker.onmessage = (event: MessageEvent<RedisContentSearchResult>) => finish(event.data);+ worker.onerror = () => finish({ matches: [], error: true });+ timer = setTimeout(() => finish({ matches: [], error: true }), 2000);+ worker.postMessage(request);+ } catch {+ finish({ matches: [], error: true });+ }+ });+ return { result, cancel: () => cancel() };+}