feat(redis): improve key browser workflows

This commit is contained in:
t8y2 committed 2026-05-20 18:54:18 +08:00
1 parent 1b5eea19c2
commit 5c2028c2c4
14 files changed
+999 -350

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -8,12 +8,13 @@ import { Badge } from "@/components/ui/badge";
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"; import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue"; import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";
import * as api from "@/lib/api"; import * as api from "@/lib/api";
import type { RedisValue } from "@/lib/api"; import type { RedisKeyInfo, RedisValue } from "@/lib/api";
import { useToast } from "@/composables/useToast"; import { useToast } from "@/composables/useToast";
import { import {
canEditRedisMemberDetail, canEditRedisMemberDetail,
clampRedisMemberDetailSheetWidth, clampRedisMemberDetailSheetWidth,
formatRedisMemberDetail, formatRedisMemberDetail,
formatRedisStringValue,
getRedisMemberSelectionKey, getRedisMemberSelectionKey,
highlightRedisJsonDetail, highlightRedisJsonDetail,
} from "@/lib/redisValuePresentation"; } from "@/lib/redisValuePresentation";
@@ -26,6 +27,7 @@ const props = defineProps<{
db: number; db: number;
keyDisplay: string; keyDisplay: string;
keyRaw: string; keyRaw: string;
metadata?: RedisKeyInfo | null;
}>(); }>();
const emit = defineEmits<{ deleted: [] }>(); const emit = defineEmits<{ deleted: [] }>();
@@ -95,6 +97,20 @@ const deleteDetails = computed(() => {
const isBinaryStringValue = computed(() => data.value?.key_type === "string" && data.value?.value_is_binary); const isBinaryStringValue = computed(() => data.value?.key_type === "string" && data.value?.value_is_binary);
const hasMore = computed(() => scanCursor.value != null && scanCursor.value > 0); const hasMore = computed(() => scanCursor.value != null && scanCursor.value > 0);
const metadataSizeLabel = computed(() => {
const metadata = props.metadata;
if (!metadata || metadata.size <= 0) return "";
if (metadata.key_type === "string") {
if (metadata.size >= 1024) return `${(metadata.size / 1024).toFixed(1)} KB`;
return `${metadata.size} B`;
}
return String(metadata.size);
});
function collectionCountLabel(kind: "items" | "fields" | "members", loaded: number, total?: number | null) {
if (total == null || total === loaded) return t(`redis.${kind}`, { count: loaded });
return t(`redis.loaded${kind[0].toUpperCase()}${kind.slice(1)}`, { loaded, total });
}
async function load(options: { selectDefaultMember?: boolean } = {}) { async function load(options: { selectDefaultMember?: boolean } = {}) {
const shouldSelectDefaultMember = options.selectDefaultMember ?? true; const shouldSelectDefaultMember = options.selectDefaultMember ?? true;
@@ -103,7 +119,7 @@ async function load(options: { selectDefaultMember?: boolean } = {}) {
data.value = await api.redisGetValue(props.connectionId, props.db, props.keyRaw); data.value = await api.redisGetValue(props.connectionId, props.db, props.keyRaw);
scanCursor.value = data.value.scan_cursor ?? undefined; scanCursor.value = data.value.scan_cursor ?? undefined;
if (data.value.key_type === "string") { if (data.value.key_type === "string") {
editValue.value = String(data.value.value); editValue.value = formatRedisStringValue(data.value.value);
clearSelectedMember(); clearSelectedMember();
} else if (["list", "set", "zset", "hash"].includes(data.value.key_type)) { } else if (["list", "set", "zset", "hash"].includes(data.value.key_type)) {
collectionItems.value = Array.isArray(data.value.value) ? [...data.value.value] : []; collectionItems.value = Array.isArray(data.value.value) ? [...data.value.value] : [];
@@ -428,7 +444,7 @@ async function confirmDelete() {
} }
function formatValue(val: any): string { function formatValue(val: any): string {
if (typeof val === "string") return val; if (typeof val === "string") return formatRedisStringValue(val);
return JSON.stringify(val, null, 2); return JSON.stringify(val, null, 2);
} }
@@ -444,42 +460,53 @@ onBeforeUnmount(stopResizeMemberSheet);
<template v-else-if="data"> <template v-else-if="data">
<!-- Header --> <!-- Header -->
<div class="h-9 flex items-center gap-2 px-4 border-b bg-muted/30 shrink-0"> <div class="shrink-0 border-b bg-background">
<span class="font-mono text-sm font-medium truncate">{{ data.key_display }}</span> <div class="flex h-9 items-center gap-2 px-4">
<Badge variant="secondary" class="text-xs">{{ data.key_type }}</Badge> <span class="min-w-0 flex-1 truncate font-mono text-sm font-semibold">{{ data.key_display }}</span>
<template v-if="!editingTtl"> <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="load"
<Badge ><RefreshCw class="h-3.5 w-3.5"
v-if="data.ttl > 0" /></Button>
variant="outline" <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0" @click="copyValue"
class="text-xs cursor-pointer hover:bg-accent" ><Copy class="h-3.5 w-3.5"
@click="startEditTtl" /></Button>
>TTL: {{ data.ttl }}s</Badge <Button variant="ghost" size="icon" class="h-7 w-7 shrink-0 text-destructive" @click="requestDeleteKey"
> ><Trash2 class="h-3.5 w-3.5"
<Badge /></Button>
v-else-if="data.ttl === -1" </div>
variant="outline"
class="text-xs opacity-50 cursor-pointer hover:bg-accent hover:opacity-100" <div class="flex min-h-7 flex-wrap items-center gap-2 px-4 pb-1">
@click="startEditTtl" <Badge variant="secondary" class="font-mono text-xs uppercase">{{ data.key_type }}</Badge>
>{{ t("redis.noExpiry") }}</Badge <Badge v-if="metadataSizeLabel" variant="outline" class="text-xs text-muted-foreground">
> {{ t("redis.columnSize") }}: {{ metadataSizeLabel }}
</template> </Badge>
<div v-else class="flex items-center gap-1"> <template v-if="!editingTtl">
<Input <Badge
v-model="ttlInput" v-if="data.ttl > 0"
class="h-6 w-20 text-xs" variant="outline"
placeholder="seconds (-1=no expiry)" class="text-xs cursor-pointer text-muted-foreground hover:bg-accent"
autofocus @click="startEditTtl"
@keydown.enter="saveTtl" >TTL: {{ data.ttl }}s</Badge
@keydown.escape="cancelEditTtl" >
/> <Badge
<Button variant="ghost" size="icon" class="h-6 w-6" @click="saveTtl"><Save class="h-3 w-3" /></Button> v-else-if="data.ttl === -1"
variant="outline"
class="text-xs cursor-pointer text-muted-foreground hover:bg-accent"
@click="startEditTtl"
>{{ t("redis.noExpiry") }}</Badge
>
</template>
<div v-else class="flex items-center gap-1">
<Input
v-model="ttlInput"
class="h-6 w-20 text-xs"
placeholder="seconds (-1=no expiry)"
autofocus
@keydown.enter="saveTtl"
@keydown.escape="cancelEditTtl"
/>
<Button variant="ghost" size="icon" class="h-6 w-6" @click="saveTtl"><Save class="h-3 w-3" /></Button>
</div>
</div> </div>
<span class="flex-1" />
<Button variant="ghost" size="icon" class="h-7 w-7" @click="load"><RefreshCw class="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" class="h-7 w-7" @click="copyValue"><Copy class="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" class="h-7 w-7 text-destructive" @click="requestDeleteKey"
><Trash2 class="h-3.5 w-3.5"
/></Button>
</div> </div>
<!-- String --> <!-- String -->
@@ -499,7 +526,7 @@ onBeforeUnmount(stopResizeMemberSheet);
size="sm" size="sm"
@click=" @click="
isEditing = false; isEditing = false;
editValue = String(data.value); editValue = formatRedisStringValue(data.value);
" "
>{{ t("grid.discard") }}</Button >{{ t("grid.discard") }}</Button
> >
@@ -511,7 +538,7 @@ onBeforeUnmount(stopResizeMemberSheet);
<div v-else-if="data.key_type === 'list'" class="flex-1 flex flex-col overflow-hidden"> <div v-else-if="data.key_type === 'list'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0"> <div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
<span class="text-xs text-muted-foreground">{{ <span class="text-xs text-muted-foreground">{{
t("redis.items", { count: collectionItems.length }) + (data.total != null ? ` / ${data.total}` : "") collectionCountLabel("items", collectionItems.length, data.total)
}}</span> }}</span>
<span class="flex-1" /> <span class="flex-1" />
<Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="value" @keydown.enter="listPush" /> <Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="value" @keydown.enter="listPush" />
@@ -573,7 +600,7 @@ onBeforeUnmount(stopResizeMemberSheet);
<div v-else-if="data.key_type === 'set'" class="flex-1 flex flex-col overflow-hidden"> <div v-else-if="data.key_type === 'set'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0"> <div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
<span class="text-xs text-muted-foreground">{{ <span class="text-xs text-muted-foreground">{{
t("redis.items", { count: collectionItems.length }) + (data.total != null ? ` / ${data.total}` : "") collectionCountLabel("items", collectionItems.length, data.total)
}}</span> }}</span>
<span class="flex-1" /> <span class="flex-1" />
<Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="member" @keydown.enter="setAdd" /> <Input v-model="newValue" class="h-6 w-40 text-xs" placeholder="member" @keydown.enter="setAdd" />
@@ -633,7 +660,7 @@ onBeforeUnmount(stopResizeMemberSheet);
<div v-else-if="data.key_type === 'hash'" class="flex-1 flex flex-col overflow-hidden"> <div v-else-if="data.key_type === 'hash'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0"> <div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
<span class="text-xs text-muted-foreground">{{ <span class="text-xs text-muted-foreground">{{
t("redis.fields", { count: collectionItems.length }) + (data.total != null ? ` / ${data.total}` : "") collectionCountLabel("fields", collectionItems.length, data.total)
}}</span> }}</span>
<span class="flex-1" /> <span class="flex-1" />
<Input v-model="newField" class="h-6 w-24 text-xs" placeholder="field" /> <Input v-model="newField" class="h-6 w-24 text-xs" placeholder="field" />
@@ -696,7 +723,7 @@ onBeforeUnmount(stopResizeMemberSheet);
<div v-else-if="data.key_type === 'zset'" class="flex-1 flex flex-col overflow-hidden"> <div v-else-if="data.key_type === 'zset'" class="flex-1 flex flex-col overflow-hidden">
<div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0"> <div class="flex items-center gap-2 px-4 py-1.5 border-b shrink-0">
<span class="text-xs text-muted-foreground">{{ <span class="text-xs text-muted-foreground">{{
t("redis.members", { count: collectionItems.length }) + (data.total != null ? ` / ${data.total}` : "") collectionCountLabel("members", collectionItems.length, data.total)
}}</span> }}</span>
<span class="flex-1" /> <span class="flex-1" />
<Input v-model="newScore" class="h-6 w-20 text-xs" placeholder="score" /> <Input v-model="newScore" class="h-6 w-20 text-xs" placeholder="score" />
@@ -655,6 +655,7 @@ const createDatabaseName = ref("");
const createDatabaseCharset = ref("utf8mb4"); const createDatabaseCharset = ref("utf8mb4");
const createDatabaseCollation = ref("utf8mb4_unicode_ci"); const createDatabaseCollation = ref("utf8mb4_unicode_ci");
const showDropDatabaseConfirm = ref(false); const showDropDatabaseConfirm = ref(false);
const showFlushRedisDbConfirm = ref(false);
const showCreateSchemaDialog = ref(false); const showCreateSchemaDialog = ref(false);
const createSchemaName = ref(""); const createSchemaName = ref("");
const showDropSchemaConfirm = ref(false); const showDropSchemaConfirm = ref(false);
@@ -1010,6 +1011,28 @@ function dropDatabase() {
showDropDatabaseConfirm.value = true; showDropDatabaseConfirm.value = true;
} }
function flushRedisDb() {
showFlushRedisDbConfirm.value = true;
}
async function confirmFlushRedisDb() {
const node = props.node;
if (node.type !== "redis-db" || !node.connectionId || !node.database) return;
try {
await connectionStore.ensureConnected(node.connectionId);
await api.redisFlushDb(node.connectionId, Number(node.database));
connectionStore.updateRedisDbKeyStats(node.connectionId, Number(node.database), { loaded: 0, total: 0 });
window.dispatchEvent(
new CustomEvent("dbx-redis-db-flushed", {
detail: { connectionId: node.connectionId, db: Number(node.database) },
}),
);
toast(t("redis.flushDbSuccess", { db: node.database }), 3000);
} catch (e: any) {
toast(t("contextMenu.tableOperationFailed", { message: e?.message || String(e) }), 5000);
}
}
async function confirmDropDatabase() { async function confirmDropDatabase() {
const node = props.node; const node = props.node;
if (!node.connectionId) return; if (!node.connectionId) return;
@@ -1943,6 +1966,12 @@ const isDragging = computed(() => dragState.active && dragState.draggedId === pr
<ContextMenuItem v-if="isNodeDefaultDatabase" @click="clearNodeDefaultDatabase"> <ContextMenuItem v-if="isNodeDefaultDatabase" @click="clearNodeDefaultDatabase">
<Database class="w-4 h-4" /> {{ t("contextMenu.clearDefaultDatabase") }} <Database class="w-4 h-4" /> {{ t("contextMenu.clearDefaultDatabase") }}
</ContextMenuItem> </ContextMenuItem>
<template v-if="node.type === 'redis-db'">
<ContextMenuSeparator />
<ContextMenuItem class="text-destructive" @click="flushRedisDb">
<Eraser class="w-4 h-4" /> {{ t("redis.flushDb") }}
</ContextMenuItem>
</template>
</template> </template>
<template v-if="node.type === 'table' || node.type === 'view'"> <template v-if="node.type === 'table' || node.type === 'view'">
@@ -2328,6 +2357,15 @@ const isDragging = computed(() => dragState.active && dragState.draggedId === pr
@confirm="confirmDropDatabase" @confirm="confirmDropDatabase"
/> />
<DangerConfirmDialog
v-model:open="showFlushRedisDbConfirm"
:title="t('redis.flushDb')"
:message="t('redis.flushDbMessage')"
:details="t('redis.flushDbDetails', { db: node.database })"
:confirm-label="t('redis.flushDbConfirm')"
@confirm="confirmFlushRedisDb"
/>
<Dialog v-model:open="showCreateSchemaDialog"> <Dialog v-model:open="showCreateSchemaDialog">
<DialogContent class="sm:max-w-[400px]"> <DialogContent class="sm:max-w-[400px]">
<DialogHeader> <DialogHeader>
+26 -1
View File
@@ -876,6 +876,9 @@ export default {
items: "{count} items", items: "{count} items",
fields: "{count} fields", fields: "{count} fields",
members: "{count} members", members: "{count} members",
loadedItems: "{loaded} of {total} items loaded",
loadedFields: "{loaded} of {total} fields loaded",
loadedMembers: "{loaded} of {total} members loaded",
entries: "{count} entries", entries: "{count} entries",
noExpiry: "no expiry", noExpiry: "no expiry",
columnType: "Type", columnType: "Type",
@@ -889,13 +892,35 @@ export default {
deleteGroup: "Delete group", deleteGroup: "Delete group",
deleteGroupDetails: "{target}\n{count} keys", deleteGroupDetails: "{target}\n{count} keys",
flushDb: "Clear current DB", flushDb: "Clear current DB",
flushDbDetails: "Redis db{db}", flushDbMessage: "This will delete every key in the current Redis database and cannot be undone. Continue?",
flushDbDetails: "Target: Redis db{db}\nScope: all keys in the current DB",
flushDbConfirm: "Clear DB",
flushDbSuccess: "Redis db{db} cleared",
keyDetail: "Key detail",
commandLine: "Command line",
selectKeyForDetail: "Select a key to view details",
commandWelcome: "Welcome to the Redis command console",
commandPlaceholder: "Redis command, e.g. GET user:1", commandPlaceholder: "Redis command, e.g. GET user:1",
commandPrefix: "CMD", commandPrefix: "CMD",
commandHint: "Enter a Redis command, e.g. SMEMBERS feature:flags", commandHint: "Enter a Redis command, e.g. SMEMBERS feature:flags",
executeCommand: "Execute command", executeCommand: "Execute command",
commandEmpty: "Enter a Redis command", commandEmpty: "Enter a Redis command",
commandEmptyResult: "Run a Redis command to see the result",
commandBlocked: "This Redis command is blocked for safety", commandBlocked: "This Redis command is blocked for safety",
createKey: "Create key",
createKeyName: "Key",
createKeyNamePlaceholder: "user:1",
createKeyType: "Type",
createValue: "Value",
createMember: "Member",
createField: "Field",
createFieldPlaceholder: "name",
createScore: "Score",
createValuePlaceholder: "value",
createKeySubmit: "Create",
createKeyNameRequired: "Enter a key name",
createFieldRequired: "Enter a hash field",
createScoreInvalid: "Enter a valid score",
member: "Member", member: "Member",
memberDetail: "Member detail", memberDetail: "Member detail",
viewMember: "View full value", viewMember: "View full value",
+27 -1
View File
@@ -774,6 +774,9 @@ export default {
items: "{count} elementos", items: "{count} elementos",
fields: "{count} campos", fields: "{count} campos",
members: "{count} miembros", members: "{count} miembros",
loadedItems: "{loaded} de {total} elementos cargados",
loadedFields: "{loaded} de {total} campos cargados",
loadedMembers: "{loaded} de {total} miembros cargados",
entries: "{count} entradas", entries: "{count} entradas",
noExpiry: "sin expiración", noExpiry: "sin expiración",
columnType: "Tipo", columnType: "Tipo",
@@ -787,13 +790,36 @@ export default {
deleteGroup: "Eliminar grupo", deleteGroup: "Eliminar grupo",
deleteGroupDetails: "{target}\n{count} claves", deleteGroupDetails: "{target}\n{count} claves",
flushDb: "Limpiar DB actual", flushDb: "Limpiar DB actual",
flushDbDetails: "Redis db{db}", flushDbMessage:
"Esto eliminará todas las claves de la base de datos Redis actual y no se puede deshacer. ¿Continuar?",
flushDbDetails: "Destino: Redis db{db}\nAlcance: todas las claves de la DB actual",
flushDbConfirm: "Limpiar DB",
flushDbSuccess: "Redis db{db} limpiada",
keyDetail: "Detalle de clave",
commandLine: "Línea de comandos",
selectKeyForDetail: "Selecciona una clave para ver detalles",
commandWelcome: "Bienvenido a la consola de comandos Redis",
commandPlaceholder: "Comando Redis, p. ej. GET user:1", commandPlaceholder: "Comando Redis, p. ej. GET user:1",
commandPrefix: "CMD", commandPrefix: "CMD",
commandHint: "Ingresa un comando Redis, p. ej. SMEMBERS feature:flags", commandHint: "Ingresa un comando Redis, p. ej. SMEMBERS feature:flags",
executeCommand: "Ejecutar comando", executeCommand: "Ejecutar comando",
commandEmpty: "Ingresa un comando Redis", commandEmpty: "Ingresa un comando Redis",
commandEmptyResult: "Ejecuta un comando Redis para ver el resultado",
commandBlocked: "Este comando Redis está bloqueado por seguridad", commandBlocked: "Este comando Redis está bloqueado por seguridad",
createKey: "Crear clave",
createKeyName: "Clave",
createKeyNamePlaceholder: "user:1",
createKeyType: "Tipo",
createValue: "Valor",
createMember: "Miembro",
createField: "Campo",
createFieldPlaceholder: "name",
createScore: "Puntuación",
createValuePlaceholder: "valor",
createKeySubmit: "Crear",
createKeyNameRequired: "Ingresa una clave",
createFieldRequired: "Ingresa un campo hash",
createScoreInvalid: "Ingresa una puntuación válida",
member: "Miembro", member: "Miembro",
memberDetail: "Detalle del miembro", memberDetail: "Detalle del miembro",
viewMember: "Ver valor completo", viewMember: "Ver valor completo",
+26 -1
View File
@@ -857,6 +857,9 @@ export default {
items: "{count} 个元素", items: "{count} 个元素",
fields: "{count} 个字段", fields: "{count} 个字段",
members: "{count} 个成员", members: "{count} 个成员",
loadedItems: "已加载 {loaded} / 共 {total} 个元素",
loadedFields: "已加载 {loaded} / 共 {total} 个字段",
loadedMembers: "已加载 {loaded} / 共 {total} 个成员",
entries: "{count} 条记录", entries: "{count} 条记录",
noExpiry: "永不过期", noExpiry: "永不过期",
columnType: "类型", columnType: "类型",
@@ -869,13 +872,35 @@ export default {
deleteGroup: "删除分组", deleteGroup: "删除分组",
deleteGroupDetails: "{target}\n{count} 个 key", deleteGroupDetails: "{target}\n{count} 个 key",
flushDb: "清空当前 DB", flushDb: "清空当前 DB",
flushDbDetails: "Redis db{db}", flushDbMessage: "这会删除当前 Redis 数据库中的所有 key,且不可撤销。确认继续?",
flushDbDetails: "目标: Redis db{db}\n范围: 当前 DB 的所有 key",
flushDbConfirm: "清空 DB",
flushDbSuccess: "Redis db{db} 已清空",
keyDetail: "键详情",
commandLine: "命令行",
selectKeyForDetail: "选择一个 key 查看详情",
commandWelcome: "欢迎使用 Redis 命令行控制台",
commandPlaceholder: "Redis 命令,如 GET user:1", commandPlaceholder: "Redis 命令,如 GET user:1",
commandPrefix: "命令", commandPrefix: "命令",
commandHint: "输入 Redis 命令,如 SMEMBERS feature:flags", commandHint: "输入 Redis 命令,如 SMEMBERS feature:flags",
executeCommand: "执行命令", executeCommand: "执行命令",
commandEmpty: "请输入 Redis 命令", commandEmpty: "请输入 Redis 命令",
commandEmptyResult: "执行 Redis 命令后会在这里显示结果",
commandBlocked: "出于安全考虑,此 Redis 命令已被阻止", commandBlocked: "出于安全考虑,此 Redis 命令已被阻止",
createKey: "新增 key",
createKeyName: "Key",
createKeyNamePlaceholder: "user:1",
createKeyType: "类型",
createValue: "值",
createMember: "成员",
createField: "字段",
createFieldPlaceholder: "name",
createScore: "分数",
createValuePlaceholder: "value",
createKeySubmit: "新增",
createKeyNameRequired: "请输入 key 名称",
createFieldRequired: "请输入 hash 字段",
createScoreInvalid: "请输入有效分数",
member: "成员", member: "成员",
memberDetail: "成员详情", memberDetail: "成员详情",
viewMember: "查看完整内容", viewMember: "查看完整内容",
@@ -0,0 +1,22 @@
export function nextRedisCommandDb(currentDb: number, command: string, result: unknown): number {
if (result !== "OK") return currentDb;
const match = command.trim().match(/^SELECT\s+(\d+)\s*;?$/i);
if (!match) return currentDb;
const nextDb = Number.parseInt(match[1], 10);
return Number.isFinite(nextDb) ? nextDb : currentDb;
}
export function isRedisClearScreenCommand(command: string): boolean {
return /^(clear|cls)\s*;?$/i.test(command.trim());
}
export function redisKeyTextToRaw(key: string): string {
const bytes = new TextEncoder().encode(key);
let binary = "";
for (const byte of bytes) {
binary += String.fromCharCode(byte);
}
return btoa(binary);
}
+23 -9
View File
@@ -24,15 +24,8 @@ export function clampRedisMemberDetailSheetWidth(width: number, viewportWidth: n
export function formatRedisMemberDetail(value: unknown): RedisMemberDetail { export function formatRedisMemberDetail(value: unknown): RedisMemberDetail {
if (typeof value === "string") { if (typeof value === "string") {
const trimmed = value.trim(); const formatted = formatRedisJsonString(value);
if (trimmed) { return formatted ? { text: formatted, format: "json" } : { text: value, format: "text" };
try {
return { text: JSON.stringify(JSON.parse(trimmed), null, 2), format: "json" };
} catch {
/* fall through to plain text */
}
}
return { text: value, format: "text" };
} }
try { try {
@@ -42,6 +35,27 @@ export function formatRedisMemberDetail(value: unknown): RedisMemberDetail {
} }
} }
export function formatRedisStringValue(value: unknown): string {
if (typeof value !== "string") return String(value ?? "");
return formatRedisJsonString(value) ?? value;
}
export function formatRedisCommandResult(value: unknown): string {
if (typeof value === "string") return formatRedisStringValue(value);
return JSON.stringify(value, null, 2);
}
function formatRedisJsonString(value: string): string | null {
const trimmed = value.trim();
if (!trimmed) return null;
try {
return JSON.stringify(JSON.parse(trimmed), null, 2);
} catch {
return null;
}
}
export function getRedisMemberSelectionKey(title: string, value: unknown): string { export function getRedisMemberSelectionKey(title: string, value: unknown): string {
return `${title}\n${formatRedisMemberDetail(value).text}`; return `${title}\n${formatRedisMemberDetail(value).text}`;
} }
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
isRedisClearScreenCommand,
nextRedisCommandDb,
redisKeyTextToRaw,
} from "../../apps/desktop/src/lib/redisCommandSession.ts";
test("keeps Redis command session database after SELECT succeeds", () => {
assert.equal(nextRedisCommandDb(3, "SELECT 0", "OK"), 0);
assert.equal(nextRedisCommandDb(0, "select 12", "OK"), 12);
});
test("does not change Redis command session database for failed or non-select commands", () => {
assert.equal(nextRedisCommandDb(3, "SELECT nope", "OK"), 3);
assert.equal(nextRedisCommandDb(3, "SELECT 2", "ERR invalid DB index"), 3);
assert.equal(nextRedisCommandDb(3, "HGET farmer:1 balance", "42"), 3);
});
test("recognizes local Redis terminal clear commands", () => {
assert.equal(isRedisClearScreenCommand("clear"), true);
assert.equal(isRedisClearScreenCommand(" CLEAR "), true);
assert.equal(isRedisClearScreenCommand("cls"), true);
assert.equal(isRedisClearScreenCommand("clear key"), false);
assert.equal(isRedisClearScreenCommand("DEL clear"), false);
});
test("encodes Redis key text as the raw base64 transport value", () => {
assert.equal(redisKeyTextToRaw("user:1"), "dXNlcjox");
assert.equal(redisKeyTextToRaw("用户:配置"), "55So5oi3OumFjee9rg==");
});
@@ -0,0 +1,109 @@
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import test from "node:test";
test("Redis key browser exposes a create key dialog for common value types", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /<Plus class="h-3 w-3" \/>/);
assert.match(source, /v-model:open="showCreateKeyDialog"/);
assert.match(source, /createKeyTypeOptions/);
assert.match(source, /value: "string"/);
assert.match(source, /value: "hash"/);
assert.match(source, /value: "list"/);
assert.match(source, /value: "set"/);
assert.match(source, /value: "zset"/);
});
test("Redis command line opens in the right workspace instead of taking permanent row space", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /activeSidePanel/);
assert.match(source, /@click="openCommandPanel"/);
assert.match(source, /<Tabs v-model="activeSidePanel"/);
assert.match(source, /<TabsContent value="command"/);
assert.match(source, /t\("redis\.keyDetail"\)/);
assert.match(source, /t\("redis\.commandLine"\)/);
assert.match(source, /data-redis-command-input/);
assert.doesNotMatch(source, /<Terminal class=/);
assert.doesNotMatch(source, /absolute inset-x-0 bottom-0/);
assert.doesNotMatch(source, /<div class="min-h-9 flex items-center gap-1 px-2 border-b bg-muted\/20 shrink-0">/);
});
test("Redis key list keeps metadata out of the browsing rows until a key is selected", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.doesNotMatch(source, /t\("redis\.columnValue"\)/);
assert.doesNotMatch(source, /t\("redis\.columnSize"\)/);
assert.doesNotMatch(source, /t\("redis\.columnTTL"\)/);
assert.match(source, /:metadata="selectedKey"/);
});
test("Redis key list uses readable leaf rows with stable key icons", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /:item-size="30"/);
assert.match(source, /:style="\{ height: '30px' \}"/);
assert.match(source, /text-\[13px\]/);
assert.match(source, /class="h-3\.5 w-3\.5 text-muted-foreground\/70 transition-opacity group-hover:opacity-0"/);
assert.match(source, /class="relative flex h-4 w-4 shrink-0 items-center justify-center"/);
assert.match(source, /group-hover:opacity-0/);
assert.match(source, /group-hover:opacity-100/);
});
test("Redis key browser uses side-by-side panes for key list and value details", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /<Splitpanes class="redis-workspace-splitpanes h-full">/);
assert.doesNotMatch(source, /<Splitpanes class="h-full" horizontal>/);
assert.match(source, /<Pane :size="36" :min-size="24">/);
assert.match(source, /<Pane :size="64" :min-size="36">/);
assert.doesNotMatch(source, /v-if="showSidePanel"/);
});
test("Redis workspace tab bar aligns with the key browser toolbar height", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /class="h-9 shrink-0 border-b bg-background px-3 flex items-center"/);
assert.doesNotMatch(source, /class="h-10 shrink-0 border-b bg-muted\/20 px-3 flex items-center"/);
});
test("Redis workspace tabs use compact shadcn tabs with icons and no underline", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /<TabsList class="h-7 gap-1 p-0\.5"/);
assert.doesNotMatch(source, /<TabsList variant="line"/);
assert.doesNotMatch(source, /data-active:after:/);
assert.doesNotMatch(source, /data-active:text-destructive/);
assert.match(source, /<KeyRound class="size-3\.5"/);
assert.match(source, /<TerminalSquare class="size-3\.5"/);
assert.doesNotMatch(source, /grid h-7 w-52 grid-cols-2 p-0\.5/);
});
test("Redis command workspace uses a terminal-like surface", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /type RedisCommandHistoryEntry/);
assert.match(source, /commandHistory/);
assert.match(source, /isRedisClearScreenCommand/);
assert.match(source, /commandHistory\.value = \[\]/);
assert.match(source, /t\("redis\.commandWelcome"\)/);
assert.match(source, /v-for="entry in commandHistory"/);
assert.match(source, /{{ commandPrompt }}/);
assert.match(source, /{{ entry\.prompt }}/);
assert.match(source, /{{ entry\.command }}/);
assert.match(source, /class="relative flex min-h-0 flex-1 flex-col bg-\[#090c10\] font-mono text-\[13px\] leading-5 text-slate-100"/);
assert.match(source, /class="flex shrink-0 items-center gap-2 border-t border-white\/10 bg-\[#090c10\] px-4 py-2"/);
assert.match(source, /class="min-w-0 flex-1 border-0 bg-transparent p-0 font-mono text-\[13px\] text-slate-100 caret-\[#d7ba7d\] outline-none/);
assert.doesNotMatch(source, /class="border-b border-slate-800 bg-slate-950 px-4 py-3 text-slate-100"/);
assert.doesNotMatch(source, /class="min-h-full whitespace-pre-wrap break-words rounded-md border border-slate-800 bg-slate-950/);
});
test("Redis browser uses a single thin shared splitter between panes", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /<Splitpanes class="redis-workspace-splitpanes h-full">/);
assert.doesNotMatch(source, /class="h-full min-w-0 border-l bg-background flex flex-col overflow-hidden"/);
assert.match(source, /\.redis-workspace-splitpanes :deep\(\.splitpanes--vertical > \.splitpanes__splitter\)/);
assert.match(source, /width: 1px !important;/);
});
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
test("Redis DB flush is exposed from the sidebar DB context menu", () => {
const source = readFileSync("apps/desktop/src/components/sidebar/TreeItem.vue", "utf8");
assert.match(source, /const showFlushRedisDbConfirm = ref\(false\)/);
assert.match(source, /function flushRedisDb\(\)/);
assert.match(source, /async function confirmFlushRedisDb\(\)/);
assert.match(source, /await api\.redisFlushDb\(node\.connectionId, Number\(node\.database\)\)/);
assert.match(source, /connectionStore\.updateRedisDbKeyStats\(node\.connectionId, Number\(node\.database\), \{ loaded: 0, total: 0 \}\)/);
assert.match(source, /node\.type === 'redis-db'/);
assert.match(source, /@click="flushRedisDb"/);
assert.match(source, /t\("redis\.flushDb"\)/);
assert.match(source, /t\('redis\.flushDbMessage'\)/);
assert.match(source, /t\('redis\.flushDbDetails', \{ db: node\.database \}\)/);
assert.match(source, /t\('redis\.flushDbConfirm'\)/);
});
test("Redis command panel no longer shows a flush DB button", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.doesNotMatch(source, /requestFlushDb/);
assert.doesNotMatch(source, /redisFlushDb/);
assert.doesNotMatch(source, /DatabaseZap/);
assert.doesNotMatch(source, /redis\.flushDb/);
});
@@ -3,7 +3,9 @@ import test from "node:test";
import { import {
canEditRedisMemberDetail, canEditRedisMemberDetail,
clampRedisMemberDetailSheetWidth, clampRedisMemberDetailSheetWidth,
formatRedisCommandResult,
formatRedisMemberDetail, formatRedisMemberDetail,
formatRedisStringValue,
getRedisMemberSelectionKey, getRedisMemberSelectionKey,
highlightRedisJsonDetail, highlightRedisJsonDetail,
} from "../../apps/desktop/src/lib/redisValuePresentation.ts"; } from "../../apps/desktop/src/lib/redisValuePresentation.ts";
@@ -22,6 +24,16 @@ test("keeps plain Redis member strings unchanged", () => {
assert.equal(detail.text, "plain long member value"); assert.equal(detail.text, "plain long member value");
}); });
test("formats JSON string values without changing plain strings", () => {
assert.equal(formatRedisStringValue('{"id":1,"name":"Ada"}'), '{\n "id": 1,\n "name": "Ada"\n}');
assert.equal(formatRedisStringValue("plain redis value"), "plain redis value");
});
test("formats Redis command results with JSON strings expanded", () => {
assert.equal(formatRedisCommandResult('{"balance":42,"unit":"USD"}'), '{\n "balance": 42,\n "unit": "USD"\n}');
assert.equal(formatRedisCommandResult(["a", 2]), '[\n "a",\n 2\n]');
});
test("formats non-string Redis member values as JSON", () => { test("formats non-string Redis member values as JSON", () => {
const detail = formatRedisMemberDetail({ field: "name", value: '{"nested":true}' }); const detail = formatRedisMemberDetail({ field: "name", value: '{"nested":true}' });
+15 -2
View File
@@ -12,12 +12,25 @@ test("Redis browser exposes key/value search modes", () => {
assert.match(source, /redis\.searchByValue/); assert.match(source, /redis\.searchByValue/);
}); });
test("Redis key search input starts blank while scanning all keys internally", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /searchPattern\s*=\s*ref\(""\)/);
assert.match(source, /searchPattern\.value\.trim\(\) \|\| "\*"/);
assert.doesNotMatch(source, /searchPattern\.value = "\*"/);
});
test("Redis command input is visually distinct from search", () => { test("Redis command input is visually distinct from search", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8"); const source = readFileSync("apps/desktop/src/components/redis/RedisKeyBrowser.vue", "utf8");
assert.match(source, /data-redis-command-input/); assert.match(source, /data-redis-command-input/);
assert.match(source, /redis\.commandPrefix/); assert.match(source, /t\("redis\.commandWelcome"\)/);
assert.match(source, /redis\.commandHint/); assert.match(source, /{{ commandPrompt }}/);
assert.match(source, /ref="commandTerminalRef"/);
assert.match(source, /@submit\.prevent="executeCommand"/);
assert.match(source, /@keydown\.enter\.prevent="executeCommand"/);
assert.match(source, /caret-\[#d7ba7d\]/);
assert.doesNotMatch(source, /redis\.commandPrefix/);
}); });
test("Redis value search streams incremental scan pages from the browser", () => { test("Redis value search streams incremental scan pages from the browser", () => {
@@ -0,0 +1,21 @@
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
import test from "node:test";
test("Redis value viewer uses a clearer two-line side panel header", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisValueViewer.vue", "utf8");
assert.match(source, /class="flex h-9 items-center gap-2 px-4"/);
assert.match(source, /class="flex min-h-7 flex-wrap items-center gap-2 px-4 pb-1"/);
assert.doesNotMatch(source, /class="h-9 flex items-center gap-2 px-4 border-b bg-muted\/30 shrink-0"/);
});
test("Redis collection headers avoid unclear raw loaded over total suffixes", () => {
const source = readFileSync("apps/desktop/src/components/redis/RedisValueViewer.vue", "utf8");
assert.match(source, /function collectionCountLabel/);
assert.doesNotMatch(source, /` \/ \$\{data\.total\}`/);
assert.match(source, /collectionCountLabel\("items", collectionItems\.length, data\.total\)/);
assert.match(source, /collectionCountLabel\("fields", collectionItems\.length, data\.total\)/);
assert.match(source, /collectionCountLabel\("members", collectionItems\.length, data\.total\)/);
});