Compare commits

..

4 Commits

Author SHA1 Message Date
tiny-craft 200b12cd51 refactor: rename "viewas" to "format", rename "plain text" to "raw" 2023-11-13 22:41:33 +08:00
tiny-craft a2c2ceb483 perf: hash value support format viewing #65 2023-11-13 22:31:18 +08:00
tiny-craft a49d618288 feat: add decode and format selection for Hash edit
perf: move decode and format state management into the component internally

perf: add component FormatSelector and ContentEntryEditor

refactor: modified functions with an excessive number of parameters to accept an object as a parameter
2023-11-13 16:03:24 +08:00
tiny-craft a2ad85627e fix: edit state does not revert when switching keys
fix: some digits are incorrectly recognized as base64-encoded text
2023-11-10 23:51:39 +08:00
25 changed files with 808 additions and 452 deletions

View File

@ -629,7 +629,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
case "string": case "string":
var str string var str string
str, err = client.Get(ctx, key).Result() str, err = client.Get(ctx, key).Result()
data.Value, data.DecodeType, data.ViewAs = strutil.ConvertTo(str, param.DecodeType, param.ViewAs) data.Value = strutil.EncodeRedisKey(str)
//data.Value, data.Decode, data.Format = strutil.ConvertTo(str, param.Decode, param.Format)
case "list": case "list":
loadListHandle := func() ([]string, bool, error) { loadListHandle := func() ([]string, bool, error) {
@ -658,11 +659,13 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
data.Value, data.End, err = loadListHandle() data.Value, data.End, err = loadListHandle()
case "hash": case "hash":
loadHashHandle := func() (map[string]string, bool, error) { loadHashHandle := func() ([]types.HashEntryItem, bool, error) {
items := map[string]string{} //items := map[string]string{}
scanSize := int64(Preferences().GetScanSize()) scanSize := int64(Preferences().GetScanSize())
items := make([]types.HashEntryItem, 0, scanSize)
var loadedVal []string var loadedVal []string
var cursor uint64 var cursor uint64
var doConvert = len(param.Decode) > 0 && len(param.Format) > 0
if param.Full { if param.Full {
// load all // load all
cursor = 0 cursor = 0
@ -671,8 +674,18 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
var v string
for i := 0; i < len(loadedVal); i += 2 { for i := 0; i < len(loadedVal); i += 2 {
items[loadedVal[i]] = loadedVal[i+1] if doConvert {
v, _, _ = strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format)
} else {
v = loadedVal[i+1]
}
items = append(items, types.HashEntryItem{
Key: loadedVal[i],
Value: strutil.EncodeRedisKey(loadedVal[i+1]),
DisplayValue: v,
})
} }
if cursor == 0 { if cursor == 0 {
break break
@ -684,8 +697,18 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
if err != nil { if err != nil {
return nil, false, err return nil, false, err
} }
var v string
for i := 0; i < len(loadedVal); i += 2 { for i := 0; i < len(loadedVal); i += 2 {
items[loadedVal[i]] = loadedVal[i+1] if doConvert {
v, _, _ = strutil.ConvertTo(loadedVal[i+1], param.Decode, param.Format)
} else {
v = loadedVal[i+1]
}
items = append(items, types.HashEntryItem{
Key: loadedVal[i],
Value: strutil.EncodeRedisKey(loadedVal[i+1]),
DisplayValue: v,
})
} }
} }
setEntryCursor(cursor) setEntryCursor(cursor)
@ -693,6 +716,7 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
} }
data.Value, data.End, err = loadHashHandle() data.Value, data.End, err = loadHashHandle()
data.Decode, data.Format = param.Decode, param.Format
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
@ -839,184 +863,56 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
return return
} }
// GetKeyValue get value by key // ConvertValue convert value with decode method and format
func (b *browserService) GetKeyValue(connName string, db int, k any, viewAs, decodeType string) (resp types.JSResp) { // blank decode indicate auto decode
item, err := b.getRedisClient(connName, db) // blank format indicate auto format
if err != nil { func (b *browserService) ConvertValue(value any, decode, format string) (resp types.JSResp) {
resp.Msg = err.Error() str := strutil.DecodeRedisKey(value)
return value, decode, format = strutil.ConvertTo(str, decode, format)
}
client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k)
var keyType string
var dur time.Duration
keyType, err = client.Type(ctx, key).Result()
if err != nil {
resp.Msg = err.Error()
return
}
if keyType == "none" {
resp.Msg = "key not exists"
return
}
var ttl int64
if dur, err = client.TTL(ctx, key).Result(); err != nil {
ttl = -1
} else {
if dur < 0 {
ttl = -1
} else {
ttl = int64(dur.Seconds())
}
}
var value any
var size, length int64
var cursor uint64
switch strings.ToLower(keyType) {
case "string":
var str string
str, err = client.Get(ctx, key).Result()
value, decodeType, viewAs = strutil.ConvertTo(str, decodeType, viewAs)
length, _ = client.StrLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "list":
value, err = client.LRange(ctx, key, 0, -1).Result()
length, _ = client.LLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "hash":
//value, err = client.HGetAll(ctx, key).Result()
items := map[string]string{}
scanSize := int64(Preferences().GetScanSize())
for {
var loadedVal []string
loadedVal, cursor, err = client.HScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
for i := 0; i < len(loadedVal); i += 2 {
items[loadedVal[i]] = loadedVal[i+1]
}
if cursor == 0 {
break
}
}
value = items
length, _ = client.HLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "set":
//value, err = client.SMembers(ctx, key).Result()
items := []string{}
scanSize := int64(Preferences().GetScanSize())
for {
var loadedKey []string
loadedKey, cursor, err = client.SScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
items = append(items, loadedKey...)
if cursor == 0 {
break
}
}
value = items
length, _ = client.SCard(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "zset":
//value, err = client.ZRangeWithScores(ctx, key, 0, -1).Result()
var items []types.ZSetItem
scanSize := int64(Preferences().GetScanSize())
for {
var loadedVal []string
loadedVal, cursor, err = client.ZScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
var score float64
for i := 0; i < len(loadedVal); i += 2 {
if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil {
items = append(items, types.ZSetItem{
Value: loadedVal[i],
Score: score,
})
}
}
if cursor == 0 {
break
}
}
value = items
length, _ = client.ZCard(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "stream":
var msgs []redis.XMessage
items := []types.StreamItem{}
msgs, err = client.XRevRange(ctx, key, "+", "-").Result()
if err != nil {
resp.Msg = err.Error()
return
}
for _, msg := range msgs {
items = append(items, types.StreamItem{
ID: msg.ID,
Value: msg.Values,
})
}
value = items
length, _ = client.XLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
}
if err != nil {
resp.Msg = err.Error()
return
}
resp.Success = true resp.Success = true
resp.Data = map[string]any{ resp.Data = map[string]any{
"type": keyType,
"ttl": ttl,
"value": value, "value": value,
"size": size, "decode": decode,
"length": length, "format": format,
"viewAs": viewAs,
"decode": decodeType,
} }
return return
} }
// SetKeyValue set value by key // SetKeyValue set value by key
// @param ttl <= 0 means keep current ttl // @param ttl <= 0 means keep current ttl
func (b *browserService) SetKeyValue(connName string, db int, k any, keyType string, value any, ttl int64, viewAs, decode string) (resp types.JSResp) { func (b *browserService) SetKeyValue(param types.SetKeyParam) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(param.Server, param.DB)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
client, ctx := item.client, item.ctx client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k) key := strutil.DecodeRedisKey(param.Key)
var expiration time.Duration var expiration time.Duration
if ttl < 0 { if param.TTL < 0 {
if expiration, err = client.PTTL(ctx, key).Result(); err != nil { if expiration, err = client.PTTL(ctx, key).Result(); err != nil {
expiration = redis.KeepTTL expiration = redis.KeepTTL
} }
} else { } else {
expiration = time.Duration(ttl) * time.Second expiration = time.Duration(param.TTL) * time.Second
} }
switch strings.ToLower(keyType) { // use default decode type and format
if len(param.Decode) <= 0 {
param.Decode = types.DECODE_NONE
}
if len(param.Format) <= 0 {
param.Format = types.FORMAT_RAW
}
switch strings.ToLower(param.KeyType) {
case "string": case "string":
if str, ok := value.(string); !ok { if str, ok := param.Value.(string); !ok {
resp.Msg = "invalid string value" resp.Msg = "invalid string value"
return return
} else { } else {
var saveStr string var saveStr string
if saveStr, err = strutil.SaveAs(str, viewAs, decode); err != nil { if saveStr, err = strutil.SaveAs(str, param.Format, param.Decode); err != nil {
resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, viewAs, err.Error()) resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, param.Format, err.Error())
return return
} }
_, err = client.Set(ctx, key, saveStr, 0).Result() _, err = client.Set(ctx, key, saveStr, 0).Result()
@ -1026,7 +922,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "list": case "list":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid list value" resp.Msg = "invalid list value"
return return
} else { } else {
@ -1036,7 +932,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "hash": case "hash":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid hash value" resp.Msg = "invalid hash value"
return return
} else { } else {
@ -1054,7 +950,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "set": case "set":
if strs, ok := value.([]any); !ok || len(strs) <= 0 { if strs, ok := param.Value.([]any); !ok || len(strs) <= 0 {
resp.Msg = "invalid set value" resp.Msg = "invalid set value"
return return
} else { } else {
@ -1066,7 +962,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "zset": case "zset":
if strs, ok := value.([]any); !ok || len(strs) <= 0 { if strs, ok := param.Value.([]any); !ok || len(strs) <= 0 {
resp.Msg = "invalid zset value" resp.Msg = "invalid zset value"
return return
} else { } else {
@ -1086,7 +982,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "stream": case "stream":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid stream value" resp.Msg = "invalid stream value"
return return
} else { } else {
@ -1109,46 +1005,52 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
resp.Success = true resp.Success = true
resp.Data = map[string]any{ resp.Data = map[string]any{
"value": value, "value": param.Value,
} }
return return
} }
// SetHashValue set hash field // SetHashValue set hash field
func (b *browserService) SetHashValue(connName string, db int, k any, field, newField, value string) (resp types.JSResp) { func (b *browserService) SetHashValue(param types.SetHashParam) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(param.Server, param.DB)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
client, ctx := item.client, item.ctx client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k) key := strutil.DecodeRedisKey(param.Key)
str := strutil.DecodeRedisKey(param.Value)
var saveStr string
if saveStr, err = strutil.SaveAs(str, param.Format, param.Decode); err != nil {
resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, param.Format, err.Error())
return
}
var removedField []string var removedField []string
updatedField := map[string]string{} updatedField := map[string]any{}
replacedField := map[string]string{} replacedField := map[string]any{}
if len(field) <= 0 { if len(param.Field) <= 0 {
// old filed is empty, add new field // old filed is empty, add new field
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
updatedField[newField] = value updatedField[param.NewField] = saveStr
} else if len(newField) <= 0 { } else if len(param.NewField) <= 0 {
// new field is empty, delete old field // new field is empty, delete old field
_, err = client.HDel(ctx, key, field, value).Result() _, err = client.HDel(ctx, key, param.Field).Result()
removedField = append(removedField, field) removedField = append(removedField, param.Field)
} else if field == newField { } else if param.Field == param.NewField {
// replace field // update field value
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.Field, saveStr).Result()
updatedField[newField] = value updatedField[param.NewField] = saveStr
} else { } else {
// remove old field and add new field // remove old field and add new field
if _, err = client.HDel(ctx, key, field).Result(); err != nil { if _, err = client.HDel(ctx, key, param.Field).Result(); err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
removedField = append(removedField, field) removedField = append(removedField, param.Field)
updatedField[newField] = value updatedField[param.NewField] = saveStr
replacedField[field] = newField replacedField[param.Field] = param.NewField
} }
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()

View File

@ -23,17 +23,45 @@ type KeyDetailParam struct {
Server string `json:"server"` Server string `json:"server"`
DB int `json:"db"` DB int `json:"db"`
Key any `json:"key"` Key any `json:"key"`
ViewAs string `json:"viewAs,omitempty"` Format string `json:"format,omitempty"`
DecodeType string `json:"decodeType,omitempty"` Decode string `json:"decode,omitempty"`
MatchPattern string `json:"matchPattern,omitempty"` MatchPattern string `json:"matchPattern,omitempty"`
Reset bool `json:"reset"` Reset bool `json:"reset"`
Full bool `json:"full"` Full bool `json:"full"`
} }
type KeyDetail struct { type HashEntryItem struct {
Value any `json:"value"` Key string `json:"k"`
Length int64 `json:"length,omitempty"` Value any `json:"v"`
ViewAs string `json:"viewAs,omitempty"` DisplayValue string `json:"dv"`
DecodeType string `json:"decodeType,omitempty"` }
End bool `json:"end"`
type KeyDetail struct {
Value any `json:"value"`
Length int64 `json:"length,omitempty"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
End bool `json:"end"`
}
type SetKeyParam struct {
Server string `json:"server"`
DB int `json:"db"`
Key any `json:"key"`
KeyType string `json:"keyType"`
Value any `json:"value"`
TTL int64 `json:"ttl"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
}
type SetHashParam struct {
Server string `json:"server"`
DB int `json:"db"`
Key any `json:"key"`
Field string `json:"field,omitempty"`
NewField string `json:"newField,omitempty"`
Value any `json:"value"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
} }

View File

@ -1,9 +1,9 @@
package types package types
const VIEWAS_PLAIN_TEXT = "Plain Text" const FORMAT_RAW = "Raw"
const VIEWAS_JSON = "JSON" const FORMAT_JSON = "JSON"
const VIEWAS_HEX = "Hex" const FORMAT_HEX = "Hex"
const VIEWAS_BINARY = "Binary" const FORMAT_BINARY = "Binary"
const DECODE_NONE = "None" const DECODE_NONE = "None"
const DECODE_BASE64 = "Base64" const DECODE_BASE64 = "Base64"

View File

@ -12,10 +12,10 @@ import (
"github.com/klauspost/compress/gzip" "github.com/klauspost/compress/gzip"
"github.com/klauspost/compress/zstd" "github.com/klauspost/compress/zstd"
"io" "io"
"regexp"
"strconv" "strconv"
"strings" "strings"
"tinyrdm/backend/types" "tinyrdm/backend/types"
"unicode/utf8"
) )
// ConvertTo convert string to specified type // ConvertTo convert string to specified type
@ -25,7 +25,7 @@ func ConvertTo(str, decodeType, formatType string) (value, resultDecode, resultF
if len(str) <= 0 { if len(str) <= 0 {
// empty content // empty content
if len(formatType) <= 0 { if len(formatType) <= 0 {
resultFormat = types.VIEWAS_PLAIN_TEXT resultFormat = types.FORMAT_RAW
} else { } else {
resultFormat = formatType resultFormat = formatType
} }
@ -142,12 +142,12 @@ func autoDecode(str string) (value, resultDecode string) {
func viewAs(str, formatType string) (value, resultFormat string) { func viewAs(str, formatType string) (value, resultFormat string) {
if len(formatType) > 0 { if len(formatType) > 0 {
switch formatType { switch formatType {
case types.VIEWAS_PLAIN_TEXT: case types.FORMAT_RAW:
value = str value = str
resultFormat = formatType resultFormat = formatType
return return
case types.VIEWAS_JSON: case types.FORMAT_JSON:
if jsonStr, ok := decodeJson(str); ok { if jsonStr, ok := decodeJson(str); ok {
value = jsonStr value = jsonStr
} else { } else {
@ -156,7 +156,7 @@ func viewAs(str, formatType string) (value, resultFormat string) {
resultFormat = formatType resultFormat = formatType
return return
case types.VIEWAS_HEX: case types.FORMAT_HEX:
if hexStr, ok := decodeToHex(str); ok { if hexStr, ok := decodeToHex(str); ok {
value = hexStr value = hexStr
} else { } else {
@ -165,7 +165,7 @@ func viewAs(str, formatType string) (value, resultFormat string) {
resultFormat = formatType resultFormat = formatType
return return
case types.VIEWAS_BINARY: case types.FORMAT_BINARY:
if binStr, ok := decodeBinary(str); ok { if binStr, ok := decodeBinary(str); ok {
value = binStr value = binStr
} else { } else {
@ -185,20 +185,20 @@ func autoViewAs(str string) (value, resultFormat string) {
if len(str) > 0 { if len(str) > 0 {
var ok bool var ok bool
if value, ok = decodeJson(str); ok { if value, ok = decodeJson(str); ok {
resultFormat = types.VIEWAS_JSON resultFormat = types.FORMAT_JSON
return return
} }
if containsBinary(str) { if containsBinary(str) {
if value, ok = decodeToHex(str); ok { if value, ok = decodeToHex(str); ok {
resultFormat = types.VIEWAS_HEX resultFormat = types.FORMAT_HEX
return return
} }
} }
} }
value = str value = str
resultFormat = types.VIEWAS_PLAIN_TEXT resultFormat = types.FORMAT_RAW
return return
} }
@ -215,9 +215,11 @@ func decodeJson(str string) (string, bool) {
} }
func decodeBase64(str string) (string, bool) { func decodeBase64(str string) (string, bool) {
if decodedStr, err := base64.StdEncoding.DecodeString(str); err == nil { if match, _ := regexp.MatchString(`^\d+$`, str); !match {
if s := string(decodedStr); utf8.ValidString(s) { if decodedStr, err := base64.StdEncoding.DecodeString(str); err == nil {
return s, true if s := string(decodedStr); !containsBinary(s) {
return s, true
}
} }
} }
return str, false return str, false
@ -282,7 +284,7 @@ func decodeBrotli(str string) (string, bool) {
func SaveAs(str, viewType, decodeType string) (value string, err error) { func SaveAs(str, viewType, decodeType string) (value string, err error) {
value = str value = str
switch viewType { switch viewType {
case types.VIEWAS_JSON: case types.FORMAT_JSON:
if jsonStr, ok := encodeJson(str); ok { if jsonStr, ok := encodeJson(str); ok {
value = jsonStr value = jsonStr
} else { } else {
@ -290,7 +292,7 @@ func SaveAs(str, viewType, decodeType string) (value string, err error) {
return return
} }
case types.VIEWAS_HEX: case types.FORMAT_HEX:
if hexStr, ok := encodeHex(str); ok { if hexStr, ok := encodeHex(str); ok {
value = hexStr value = hexStr
} else { } else {
@ -298,7 +300,7 @@ func SaveAs(str, viewType, decodeType string) (value string, err error) {
return return
} }
case types.VIEWAS_BINARY: case types.FORMAT_BINARY:
if binStr, ok := encodeBinary(str); ok { if binStr, ok := encodeBinary(str); ok {
value = binStr value = binStr
} else { } else {

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { computed, h, ref } from 'vue' import { computed, h, ref } from 'vue'
import { map } from 'lodash' import { get, map } from 'lodash'
import { NIcon, NText } from 'naive-ui' import { NIcon, NText } from 'naive-ui'
const props = defineProps({ const props = defineProps({
@ -16,6 +16,8 @@ const props = defineProps({
type: String, type: String,
}, },
icon: [String, Object], icon: [String, Object],
default: String,
disabled: Boolean,
}) })
const emit = defineEmits(['update:value']) const emit = defineEmits(['update:value'])
@ -56,7 +58,7 @@ const onDropdownSelect = (key) => {
} }
const buttonText = computed(() => { const buttonText = computed(() => {
return props.value || get(dropdownOption.value, [1, 'label'], 'None') return props.value || get(dropdownOption.value, [1, 'label'], props.default)
}) })
const showDropdown = ref(false) const showDropdown = ref(false)
@ -67,6 +69,7 @@ const onDropdownShow = (show) => {
<template> <template>
<n-dropdown <n-dropdown
:disabled="props.disabled"
:options="dropdownOption" :options="dropdownOption"
:render-label="renderLabel" :render-label="renderLabel"
:show-arrow="true" :show-arrow="true"
@ -78,7 +81,7 @@ const onDropdownShow = (show) => {
<n-tooltip :disabled="showDropdown" :show-arrow="false"> <n-tooltip :disabled="showDropdown" :show-arrow="false">
{{ props.tooltip }} {{ props.tooltip }}
<template #trigger> <template #trigger>
<n-button :focusable="false" quaternary> <n-button :disabled="disabled" :focusable="false" quaternary>
<template #icon> <template #icon>
<n-icon> <n-icon>
<component :is="icon" /> <component :is="icon" />

View File

@ -7,6 +7,7 @@ const emit = defineEmits(['click'])
const props = defineProps({ const props = defineProps({
tooltip: String, tooltip: String,
tTooltip: String, tTooltip: String,
type: String,
icon: [String, Object], icon: [String, Object],
size: { size: {
type: [Number, String], type: [Number, String],
@ -39,6 +40,7 @@ const hasTooltip = computed(() => {
:focusable="false" :focusable="false"
:loading="loading" :loading="loading"
:text="!border" :text="!border"
:type="type"
@click.prevent="emit('click')"> @click.prevent="emit('click')">
<template #icon> <template #icon>
<n-icon :color="props.color || 'currentColor'" :size="props.size"> <n-icon :color="props.color || 'currentColor'" :size="props.size">
@ -56,6 +58,7 @@ const hasTooltip = computed(() => {
:focusable="false" :focusable="false"
:loading="loading" :loading="loading"
:text="!border" :text="!border"
:type="type"
@click.prevent="emit('click')"> @click.prevent="emit('click')">
<template #icon> <template #icon>
<n-icon :color="props.color || 'currentColor'" :size="props.size"> <n-icon :color="props.color || 'currentColor'" :size="props.size">

View File

@ -2,7 +2,7 @@
import { computed, h, nextTick, reactive, ref } from 'vue' import { computed, h, nextTick, reactive, ref } from 'vue'
import IconButton from '@/components/common/IconButton.vue' import IconButton from '@/components/common/IconButton.vue'
import Refresh from '@/components/icons/Refresh.vue' import Refresh from '@/components/icons/Refresh.vue'
import { map, size, split, uniqBy } from 'lodash' import { map, size, uniqBy } from 'lodash'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import Delete from '@/components/icons/Delete.vue' import Delete from '@/components/icons/Delete.vue'
import dayjs from 'dayjs' import dayjs from 'dayjs'

View File

@ -14,6 +14,7 @@ import ContentCli from '@/components/content_value/ContentCli.vue'
import Monitor from '@/components/icons/Monitor.vue' import Monitor from '@/components/icons/Monitor.vue'
import Pub from '@/components/icons/Pub.vue' import Pub from '@/components/icons/Pub.vue'
import ContentSlog from '@/components/content_value/ContentSlog.vue' import ContentSlog from '@/components/content_value/ContentSlog.vue'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -54,9 +55,9 @@ const tabContent = computed(() => {
value: tab.value, value: tab.value,
size: tab.size || 0, size: tab.size || 0,
length: tab.length || 0, length: tab.length || 0,
viewAs: tab.viewAs, decode: tab.decode || decodeTypes.NONE,
decode: tab.decode, format: tab.format || formatTypes.RAW,
end: tab.end, end: tab.end === true,
loading: tab.loading === true, loading: tab.loading === true,
} }
}) })

View File

@ -0,0 +1,177 @@
<script setup>
import { computed, defineEmits, defineProps, reactive, ref, watch } from 'vue'
import { useThemeVars } from 'naive-ui'
import Save from '@/components/icons/Save.vue'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import { decodeRedisKey } from '@/utils/key_convert.js'
import useBrowserStore from 'stores/browser.js'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
const props = defineProps({
field: {
type: String,
},
value: {
type: String,
},
keyLabel: {
type: String,
},
valueLabel: {
type: String,
},
decode: {
type: String,
},
format: {
type: String,
},
})
const themeVars = useThemeVars()
const browserStore = useBrowserStore()
const emit = defineEmits(['update:field', 'update:value', 'update:decode', 'update:format', 'save', 'cancel'])
const model = reactive({
field: '',
value: '',
})
watch(
() => props.value,
(val) => {
if (val != null) {
onFormatChanged()
} else {
viewAs.value = ''
}
},
)
const loading = ref(false)
const viewAs = reactive({
field: '',
value: '',
format: formatTypes.RAW,
decode: decodeTypes.NONE,
})
const displayValue = computed(() => {
if (loading.value) {
return ''
}
return viewAs.value || decodeRedisKey(props.value)
})
/**
*
* @param {string} decode
* @param {string} format
* @return {Promise<void>}
*/
const onFormatChanged = async (decode = '', format = '') => {
try {
loading.value = true
const {
value,
decode: retDecode,
format: retFormat,
} = await browserStore.convertValue({
value: props.value,
decode,
format,
})
viewAs.field = props.field
viewAs.value = value
viewAs.decode = decode || retDecode
viewAs.format = format || retFormat
} finally {
loading.value = false
}
}
const onUpdateValue = (value) => {
// emit('update:value', value)
viewAs.value = value
}
const onSave = () => {
emit('save', viewAs.field, viewAs.value, viewAs.decode, viewAs.format)
}
</script>
<template>
<div class="entry-editor flex-box-v">
<n-card
:title="$t('interface.edit_row')"
autofocus
closable
size="small"
style="height: 100%"
@close="emit('cancel')">
<div class="editor-content flex-box-v" style="height: 100%">
<!-- field -->
<div class="editor-content-item flex-box-v">
<div class="editor-content-item-label">{{ props.keyLabel }}</div>
<n-input v-model:value="viewAs.field" class="editor-content-item-input" type="text" />
</div>
<!-- value -->
<div class="editor-content-item flex-box-v flex-item-expand">
<div class="editor-content-item-label">{{ props.valueLabel }}</div>
<n-input
:value="displayValue"
autofocus
class="flex-item-expand"
type="textarea"
@update:value="onUpdateValue" />
<format-selector
:decode="viewAs.decode"
:format="viewAs.format"
@format-changed="(d, f) => onFormatChanged(d, f)" />
</div>
</div>
<template #action>
<n-space :wrap="false" :wrap-item="false" justify="end">
<n-button ghost type="primary" @click="onSave">
<template #icon>
<n-icon :component="Save"></n-icon>
</template>
{{ $t('common.update') }}
</n-button>
</n-space>
</template>
</n-card>
</div>
</template>
<style lang="scss" scoped>
.entry-editor {
padding-left: 2px;
.editor-content {
&-item {
&:not(:last-child) {
margin-bottom: 18px;
}
&-label {
line-height: 1.25;
color: v-bind('themeVars.textColor3');
font-size: 13px;
padding: 5px 0;
}
&-input {
}
}
}
}
:deep(.n-card__action) {
padding: 5px 10px;
background-color: unset;
}
:deep(.n-card--bordered) {
border-radius: 0;
}
</style>

View File

@ -3,7 +3,7 @@ import { computed, h, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.vue' import ContentToolbar from './ContentToolbar.vue'
import AddLink from '@/components/icons/AddLink.vue' import AddLink from '@/components/icons/AddLink.vue'
import { NButton, NCode, NIcon, NInput, useThemeVars } from 'naive-ui' import { NButton, NIcon, NInput, useThemeVars } from 'naive-ui'
import { types, types as redisTypes } from '@/consts/support_redis_type.js' import { types, types as redisTypes } from '@/consts/support_redis_type.js'
import EditableTableColumn from '@/components/common/EditableTableColumn.vue' import EditableTableColumn from '@/components/common/EditableTableColumn.vue'
import useDialogStore from 'stores/dialog.js' import useDialogStore from 'stores/dialog.js'
@ -14,6 +14,10 @@ import useBrowserStore from 'stores/browser.js'
import LoadList from '@/components/icons/LoadList.vue' import LoadList from '@/components/icons/LoadList.vue'
import LoadAll from '@/components/icons/LoadAll.vue' import LoadAll from '@/components/icons/LoadAll.vue'
import IconButton from '@/components/common/IconButton.vue' import IconButton from '@/components/common/IconButton.vue'
import ContentEntryEditor from '@/components/content_value/ContentEntryEditor.vue'
import Edit from '@/components/icons/Edit.vue'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
import { decodeRedisKey } from '@/utils/key_convert.js'
const i18n = useI18n() const i18n = useI18n()
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -30,12 +34,15 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: Object, value: {
type: Array,
default: () => [],
},
size: Number, size: Number,
length: Number, length: Number,
viewAs: { format: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.RAW,
}, },
decode: { decode: {
type: String, type: String,
@ -70,34 +77,33 @@ const filterType = ref(1)
const browserStore = useBrowserStore() const browserStore = useBrowserStore()
const dialogStore = useDialogStore() const dialogStore = useDialogStore()
const keyType = redisTypes.HASH const keyType = redisTypes.HASH
const currentEditRow = ref({ const currentEditRow = reactive({
no: 0, no: 0,
key: '', key: '',
value: null, value: null,
format: formatTypes.RAW,
decode: decodeTypes.NONE,
}) })
const inEdit = computed(() => {
return currentEditRow.no > 0
})
const tableRef = ref(null)
const fieldColumn = reactive({ const fieldColumn = reactive({
key: 'key', key: 'key',
title: i18n.t('common.field'), title: i18n.t('common.field'),
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
resizable: true, resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
return !!~row.key.indexOf(value.toString()) return !!~row.k.indexOf(value.toString())
}, },
// sorter: (row1, row2) => row1.key - row2.key, render(row) {
render: (row) => { return decodeRedisKey(row.k)
const isEdit = currentEditRow.value.no === row.no
if (isEdit) {
return h(NInput, {
value: currentEditRow.value.key,
'onUpdate:value': (val) => {
currentEditRow.value.key = val
},
})
} else {
return row.key
}
}, },
}) })
const valueColumn = reactive({ const valueColumn = reactive({
@ -106,31 +112,69 @@ const valueColumn = reactive({
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
resizable: true, resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
return !!~row.value.indexOf(value.toString()) return !!~row.value.indexOf(value.toString())
}, },
// sorter: (row1, row2) => row1.value - row2.value, render(row) {
// ellipsis: { return row.dv
// tooltip: true
// },
render: (row) => {
const isEdit = currentEditRow.value.no === row.no
if (isEdit) {
return h(NInput, {
value: currentEditRow.value.value,
type: 'textarea',
autosize: { minRow: 2, maxRows: 5 },
style: 'text-align: left;',
'onUpdate:value': (val) => {
currentEditRow.value.value = val
},
})
} else {
return h(NCode, { language: 'plaintext', wordWrap: true }, { default: () => row.value })
}
}, },
}) })
const startEdit = async ({ no, key, value }) => {
currentEditRow.value = value
currentEditRow.no = no
currentEditRow.key = key
}
const saveEdit = async (field, value, decode, format) => {
try {
const row = props.value[currentEditRow.no - 1]
if (row == null) {
throw new Error('row not exists')
}
const { updated, success, msg } = await browserStore.setHash({
server: props.name,
db: props.db,
key: keyName.value,
field: row.k,
newField: field,
value,
decode,
format,
})
if (success) {
row.k = field
row.v = updated[row.k] || ''
const { value: displayVal } = await browserStore.convertValue({
value: row.v,
decode: props.decode,
format: props.format,
})
row.dv = displayVal
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
resetEdit()
}
}
const resetEdit = () => {
currentEditRow.no = 0
currentEditRow.key = ''
currentEditRow.value = null
currentEditRow.format = formatTypes.RAW
currentEditRow.decode = decodeTypes.NONE
}
const actionColumn = { const actionColumn = {
key: 'action', key: 'action',
title: i18n.t('interface.action'), title: i18n.t('interface.action'),
@ -138,25 +182,21 @@ const actionColumn = {
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
fixed: 'right', fixed: 'right',
render: (row) => { render: (row, index) => {
return h(EditableTableColumn, { return h(EditableTableColumn, {
editing: currentEditRow.value.no === row.no, editing: false,
bindKey: row.key, bindKey: row.k,
onEdit: () => { onEdit: () => startEdit({ no: index + 1, key: row.k, value: row.v }),
currentEditRow.value.no = row.no
currentEditRow.value.key = row.key
currentEditRow.value.value = row.value
},
onDelete: async () => { onDelete: async () => {
try { try {
const { success, msg } = await browserStore.removeHashField( const { success, msg } = await browserStore.removeHashField(
props.name, props.name,
props.db, props.db,
keyName.value, keyName.value,
row.key, row.k,
) )
if (success) { if (success) {
$message.success(i18n.t('dialogue.delete_key_succ', { key: row.key })) $message.success(i18n.t('dialogue.delete_key_succ', { key: row.k }))
} else { } else {
$message.error(msg) $message.error(msg)
} }
@ -164,61 +204,62 @@ const actionColumn = {
$message.error(e.message) $message.error(e.message)
} }
}, },
onSave: async () => {
try {
const { success, msg } = await browserStore.setHash(
props.name,
props.db,
keyName.value,
row.key,
currentEditRow.value.key,
currentEditRow.value.value,
)
if (success) {
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
currentEditRow.value.no = 0
}
},
onCancel: () => {
currentEditRow.value.no = 0
},
}) })
}, },
} }
const columns = reactive([
{
key: 'no',
title: '#',
width: 80,
align: 'center',
titleAlign: 'center',
},
fieldColumn,
valueColumn,
actionColumn,
])
const tableData = computed(() => { const columns = computed(() => {
const data = [] if (!inEdit.value) {
let index = 0 return [
for (const key in props.value) { {
data.push({ key: 'no',
no: ++index, title: '#',
key, width: 80,
value: props.value[key], align: 'center',
}) titleAlign: 'center',
render(row, index) {
return index + 1
},
},
fieldColumn,
valueColumn,
actionColumn,
]
} else {
return [
{
key: 'no',
title: '#',
width: 80,
align: 'center',
titleAlign: 'center',
render(row, index) {
if (index + 1 === currentEditRow.no) {
// editing row, show edit state
return h(NIcon, { size: 16, color: 'red' }, () => h(Edit, { strokeWidth: 5 }))
} else {
return index + 1
}
},
},
fieldColumn,
]
} }
return data
}) })
const rowProps = (row, index) => {
return {
onClick: () => {
// in edit mode, switch edit row by click
if (inEdit.value) {
startEdit({ no: index + 1, key: row.k, value: row.v })
}
},
}
}
const entries = computed(() => { const entries = computed(() => {
const len = size(tableData.value) const len = size(props.value)
return `${len} / ${Math.max(len, props.length)}` return `${len} / ${Math.max(len, props.length)}`
}) })
@ -229,12 +270,12 @@ const onAddRow = () => {
const filterValue = ref('') const filterValue = ref('')
const onFilterInput = (val) => { const onFilterInput = (val) => {
switch (filterType.value) { switch (filterType.value) {
case filterOption[0].value: case filterOption.value[0].value:
// filter field // filter field
valueColumn.filterOptionValue = null valueColumn.filterOptionValue = null
fieldColumn.filterOptionValue = val fieldColumn.filterOptionValue = val
break break
case filterOption[1].value: case filterOption.value[1].value:
// filter value // filter value
fieldColumn.filterOptionValue = null fieldColumn.filterOptionValue = null
valueColumn.filterOptionValue = val valueColumn.filterOptionValue = val
@ -253,18 +294,23 @@ const clearFilter = () => {
const onUpdateFilter = (filters, sourceColumn) => { const onUpdateFilter = (filters, sourceColumn) => {
switch (filterType.value) { switch (filterType.value) {
case filterOption[0].value: case filterOption.value[0].value:
fieldColumn.filterOptionValue = filters[sourceColumn.key] fieldColumn.filterOptionValue = filters[sourceColumn.key]
break break
case filterOption[1].value: case filterOption.value[1].value:
valueColumn.filterOptionValue = filters[sourceColumn.key] valueColumn.filterOptionValue = filters[sourceColumn.key]
break break
} }
} }
const onFormatChanged = (selDecode, selFormat) => {
emit('reload', selDecode, selFormat)
}
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
resetEdit()
}, },
}) })
</script> </script>
@ -324,14 +370,17 @@ defineExpose({
{{ $t('interface.add_row') }} {{ $t('interface.add_row') }}
</n-button> </n-button>
</div> </div>
<div class="value-wrapper value-item-part flex-box-v flex-item-expand"> <div id="content-table" class="value-wrapper value-item-part flex-box-h flex-item-expand">
<!-- table -->
<n-data-table <n-data-table
:key="(row) => row.no" :key="(row) => row.no"
ref="tableRef"
:bordered="false" :bordered="false"
:bottom-bordered="false" :bottom-bordered="false"
:columns="columns" :columns="columns"
:data="tableData" :data="props.value"
:loading="props.loading" :loading="props.loading"
:row-props="rowProps"
:single-column="true" :single-column="true"
:single-line="false" :single-line="false"
class="flex-item-expand" class="flex-item-expand"
@ -340,12 +389,32 @@ defineExpose({
striped striped
virtual-scroll virtual-scroll
@update:filters="onUpdateFilter" /> @update:filters="onUpdateFilter" />
<!-- edit pane -->
<content-entry-editor
v-show="inEdit"
:decode="currentEditRow.decode"
:field="currentEditRow.key"
:format="currentEditRow.format"
:key-label="$t('common.field')"
:value="currentEditRow.value"
:value-label="$t('common.value')"
class="flex-item-expand"
style="width: 100%"
@cancel="resetEdit"
@save="saveEdit" />
</div> </div>
<div class="value-footer flex-box-h"> <div class="value-footer flex-box-h">
<n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text> <n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text>
<n-divider v-if="!isNaN(props.length)" vertical /> <n-divider v-if="!isNaN(props.length)" vertical />
<n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text> <n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text>
<div class="flex-item-expand"></div> <div class="flex-item-expand"></div>
<format-selector
v-show="!inEdit"
:decode="props.decode"
:disabled="inEdit"
:format="props.format"
@format-changed="onFormatChanged" />
</div> </div>
</div> </div>
</template> </template>

View File

@ -35,7 +35,7 @@ const props = defineProps({
length: Number, length: Number,
viewAs: { viewAs: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.RAW,
}, },
decode: { decode: {
type: String, type: String,
@ -89,6 +89,10 @@ const valueColumn = reactive({
}, },
}) })
const cancelEdit = () => {
currentEditRow.value.no = 0
}
const actionColumn = { const actionColumn = {
key: 'action', key: 'action',
title: i18n.t('interface.action'), title: i18n.t('interface.action'),
@ -141,9 +145,7 @@ const actionColumn = {
currentEditRow.value.no = 0 currentEditRow.value.no = 0
} }
}, },
onCancel: () => { onCancel: cancelEdit,
currentEditRow.value.no = 0
},
}) })
}, },
} }
@ -198,6 +200,7 @@ const onUpdateFilter = (filters, sourceColumn) => {
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
cancelEdit()
}, },
}) })
</script> </script>

View File

@ -35,7 +35,7 @@ const props = defineProps({
length: Number, length: Number,
viewAs: { viewAs: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.RAW,
}, },
decode: { decode: {
type: String, type: String,
@ -89,6 +89,11 @@ const valueColumn = reactive({
} }
}, },
}) })
const cancelEdit = () => {
currentEditRow.value.no = 0
}
const actionColumn = { const actionColumn = {
key: 'action', key: 'action',
title: i18n.t('interface.action'), title: i18n.t('interface.action'),
@ -142,9 +147,7 @@ const actionColumn = {
currentEditRow.value.no = 0 currentEditRow.value.no = 0
} }
}, },
onCancel: () => { onCancel: cancelEdit,
currentEditRow.value.no = 0
},
}) })
}, },
} }
@ -199,6 +202,7 @@ const onUpdateFilter = (filters, sourceColumn) => {
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
cancelEdit()
}, },
}) })
</script> </script>

View File

@ -38,7 +38,7 @@ const props = defineProps({
length: Number, length: Number,
viewAs: { viewAs: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.RAW,
}, },
decode: { decode: {
type: String, type: String,

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed, ref } from 'vue' import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.vue' import ContentToolbar from './ContentToolbar.vue'
import Copy from '@/components/icons/Copy.vue' import Copy from '@/components/icons/Copy.vue'
@ -10,12 +10,11 @@ import Close from '@/components/icons/Close.vue'
import { types as redisTypes } from '@/consts/support_redis_type.js' import { types as redisTypes } from '@/consts/support_redis_type.js'
import { ClipboardSetText } from 'wailsjs/runtime/runtime.js' import { ClipboardSetText } from 'wailsjs/runtime/runtime.js'
import { isEmpty, toLower } from 'lodash' import { isEmpty, toLower } from 'lodash'
import DropdownSelector from '@/components/content_value/DropdownSelector.vue'
import Code from '@/components/icons/Code.vue'
import Conversion from '@/components/icons/Conversion.vue'
import EditFile from '@/components/icons/EditFile.vue' import EditFile from '@/components/icons/EditFile.vue'
import bytes from 'bytes' import bytes from 'bytes'
import useBrowserStore from 'stores/browser.js' import useBrowserStore from 'stores/browser.js'
import { decodeRedisKey } from '@/utils/key_convert.js'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
const i18n = useI18n() const i18n = useI18n()
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -32,17 +31,9 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: String, value: [String, Array],
size: Number, size: Number,
length: Number, length: Number,
viewAs: {
type: String,
default: formatTypes.PLAIN_TEXT,
},
decode: {
type: String,
default: decodeTypes.NONE,
},
loading: Boolean, loading: Boolean,
}) })
@ -58,7 +49,7 @@ const keyName = computed(() => {
const keyType = redisTypes.STRING const keyType = redisTypes.STRING
const viewLanguage = computed(() => { const viewLanguage = computed(() => {
switch (props.viewAs) { switch (viewAs.format) {
case formatTypes.JSON: case formatTypes.JSON:
return 'json' return 'json'
default: default:
@ -66,31 +57,48 @@ const viewLanguage = computed(() => {
} }
}) })
const onViewTypeUpdate = (viewType) => { const viewAs = reactive({
browserStore.loadKeyDetail({ value: '',
server: props.name, format: formatTypes.RAW,
db: props.db, decode: decodeTypes.NONE,
key: keyName.value, })
viewType,
decodeType: props.decode,
})
}
const onDecodeTypeUpdate = (decodeType) => { const displayValue = computed(() => {
browserStore.loadKeyDetail({ if (props.loading) {
server: props.name, return ''
db: props.db, }
key: keyName.value, return viewAs.value || decodeRedisKey(props.value)
viewType: props.viewAs, })
decodeType,
watch(
() => props.value,
(val, oldVal) => {
if (val !== undefined && oldVal !== undefined) {
onFormatChanged(viewAs.decode, viewAs.format)
}
},
)
const onFormatChanged = async (decode = '', format = '') => {
const {
value,
decode: retDecode,
format: retFormat,
} = await browserStore.convertValue({
value: props.value,
decode,
format,
}) })
viewAs.value = value
viewAs.decode = decode || retDecode
viewAs.format = format || retFormat
} }
/** /**
* Copy value * Copy value
*/ */
const onCopyValue = () => { const onCopyValue = () => {
ClipboardSetText(props.value) ClipboardSetText(displayValue.value)
.then((succ) => { .then((succ) => {
if (succ) { if (succ) {
$message.success(i18n.t('dialogue.copy_succ')) $message.success(i18n.t('dialogue.copy_succ'))
@ -104,7 +112,7 @@ const onCopyValue = () => {
const editValue = ref('') const editValue = ref('')
const inEdit = ref(false) const inEdit = ref(false)
const onEditValue = () => { const onEditValue = () => {
editValue.value = props.value editValue.value = displayValue.value
inEdit.value = true inEdit.value = true
} }
@ -120,16 +128,16 @@ const saving = ref(false)
const onSaveValue = async () => { const onSaveValue = async () => {
saving.value = true saving.value = true
try { try {
const { success, msg } = await browserStore.setKey( const { success, msg } = await browserStore.setKey({
props.name, server: props.name,
props.db, db: props.db,
keyName.value, key: keyName.value,
toLower(keyType), keyType: toLower(keyType),
editValue.value, value: editValue.value,
-1, ttl: -1,
props.viewAs, format: viewAs.format,
props.decode, decode: viewAs.decode,
) })
if (success) { if (success) {
await browserStore.loadKeyDetail({ server: props.name, db: props.db, key: keyName.value }) await browserStore.loadKeyDetail({ server: props.name, db: props.db, key: keyName.value })
$message.success(i18n.t('dialogue.save_value_succ')) $message.success(i18n.t('dialogue.save_value_succ'))
@ -143,6 +151,14 @@ const onSaveValue = async () => {
saving.value = false saving.value = false
} }
} }
defineExpose({
reset: () => {
viewAs.value = ''
inEdit.value = false
},
beforeShow: () => onFormatChanged(),
})
</script> </script>
<template> <template>
@ -192,7 +208,7 @@ const onSaveValue = async () => {
</div> </div>
<div class="value-wrapper value-item-part flex-item-expand flex-box-v"> <div class="value-wrapper value-item-part flex-item-expand flex-box-v">
<n-scrollbar v-if="!inEdit" class="flex-item-expand"> <n-scrollbar v-if="!inEdit" class="flex-item-expand">
<n-code :code="props.value" :language="viewLanguage" style="cursor: text" word-wrap /> <n-code :code="displayValue" :language="viewLanguage" style="cursor: text" word-wrap />
</n-scrollbar> </n-scrollbar>
<n-input <n-input
v-else v-else
@ -207,19 +223,11 @@ const onSaveValue = async () => {
<n-divider v-if="!isNaN(props.length)" vertical /> <n-divider v-if="!isNaN(props.length)" vertical />
<n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text> <n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text>
<div class="flex-item-expand"></div> <div class="flex-item-expand"></div>
<dropdown-selector <format-selector
:icon="Code" :decode="viewAs.decode"
:options="formatTypes" :disabled="inEdit"
:tooltip="$t('interface.view_as')" :format="viewAs.format"
:value="props.viewAs" @format-changed="onFormatChanged" />
@update:value="onViewTypeUpdate" />
<n-divider vertical />
<dropdown-selector
:icon="Conversion"
:options="decodeTypes"
:tooltip="$t('interface.decode_with')"
:value="props.decode"
@update:value="onDecodeTypeUpdate" />
</div> </div>
</div> </div>
</template> </template>

View File

@ -10,8 +10,8 @@ import { useThemeVars } from 'naive-ui'
import useBrowserStore from 'stores/browser.js' import useBrowserStore from 'stores/browser.js'
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { isEmpty } from 'lodash' import { isEmpty } from 'lodash'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import useDialogStore from 'stores/dialog.js' import useDialogStore from 'stores/dialog.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
const themeVars = useThemeVars() const themeVars = useThemeVars()
const browserStore = useBrowserStore() const browserStore = useBrowserStore()
@ -37,7 +37,7 @@ const props = defineProps({
* value: [String, Object], * value: [String, Object],
* size: Number, * size: Number,
* length: Number, * length: Number,
* viewAs: String, * format: String,
* decode: String, * decode: String,
* end: Boolean * end: Boolean
* }>} * }>}
@ -45,6 +45,7 @@ const props = defineProps({
const data = computed(() => { const data = computed(() => {
return props.content return props.content
}) })
const initializing = ref(false)
const binaryKey = computed(() => { const binaryKey = computed(() => {
return !!data.value.keyCode return !!data.value.keyCode
@ -65,7 +66,8 @@ const keyName = computed(() => {
const loadData = async (reset, full) => { const loadData = async (reset, full) => {
try { try {
const { name, db, view, decodeType, matchPattern } = data.value const { name, db, view, decodeType, matchPattern, decode, format } = data.value
reset = reset === true
await browserStore.loadKeyDetail({ await browserStore.loadKeyDetail({
server: name, server: name,
db: db, db: db,
@ -73,17 +75,31 @@ const loadData = async (reset, full) => {
viewType: view, viewType: view,
decodeType: decodeType, decodeType: decodeType,
matchPattern: matchPattern, matchPattern: matchPattern,
reset: reset === true, decode: reset ? decodeTypes.NONE : decode,
format: reset ? formatTypes.RAW : format,
reset,
full: full === true, full: full === true,
}) })
} finally { } finally {
} }
} }
const onReload = async () => { /**
* reload current key
* @param {string} [selDecode]
* @param {string} [selFormat]
* @return {Promise<void>}
*/
const onReload = async (selDecode, selFormat) => {
try { try {
const { name, db, keyCode, keyPath } = data.value const { name, db, keyCode, keyPath, decode, format } = data.value
await browserStore.reloadKey({ server: name, db, key: keyCode || keyPath }) await browserStore.reloadKey({
server: name,
db,
key: keyCode || keyPath,
decode: selDecode || decode,
format: selFormat || format,
})
} finally { } finally {
} }
} }
@ -116,22 +132,29 @@ const onLoadAll = () => {
loadData(false, true) loadData(false, true)
} }
onMounted(() => {
// onReload()
loadData(false, false)
})
const contentRef = ref(null) const contentRef = ref(null)
watch( const initContent = async () => {
() => data.value?.keyPath, // onReload()
() => { try {
// onReload() initializing.value = true
if (contentRef.value?.reset != null) { if (contentRef.value?.reset != null) {
contentRef.value?.reset() contentRef.value?.reset()
} }
loadData(false, false) await loadData(true, false)
}, if (contentRef.value?.beforeShow != null) {
) await contentRef.value?.beforeShow()
}
} finally {
initializing.value = false
}
}
onMounted(() => {
// onReload()
initContent()
})
watch(() => data.value?.keyPath, initContent)
</script> </script>
<template> <template>
@ -145,17 +168,17 @@ watch(
:is="valueComponents[data.type]" :is="valueComponents[data.type]"
ref="contentRef" ref="contentRef"
:db="data.db" :db="data.db"
:decode="data.decode || decodeTypes.NONE" :decode="data.decode"
:end="data.end" :end="data.end"
:format="data.format"
:key-code="data.keyCode" :key-code="data.keyCode"
:key-path="data.keyPath" :key-path="data.keyPath"
:length="data.length" :length="data.length"
:loading="data.loading === true" :loading="data.loading === true || initializing"
:name="data.name" :name="data.name"
:size="data.size" :size="data.size"
:ttl="data.ttl" :ttl="data.ttl"
:value="data.value" :value="data.value"
:view-as="data.viewAs || formatTypes.PLAIN_TEXT"
@delete="onDelete" @delete="onDelete"
@loadall="onLoadAll" @loadall="onLoadAll"
@loadmore="onLoadMore" @loadmore="onLoadMore"

View File

@ -135,6 +135,9 @@ const valueColumn = reactive({
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
resizable: true, resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
return !!~row.value.indexOf(value.toString()) return !!~row.value.indexOf(value.toString())
@ -160,6 +163,11 @@ const valueColumn = reactive({
} }
}, },
}) })
const cancelEdit = () => {
currentEditRow.value.no = 0
}
const actionColumn = { const actionColumn = {
key: 'action', key: 'action',
title: i18n.t('interface.action'), title: i18n.t('interface.action'),
@ -219,9 +227,7 @@ const actionColumn = {
currentEditRow.value.no = 0 currentEditRow.value.no = 0
} }
}, },
onCancel: () => { onCancel: cancelEdit,
currentEditRow.value.no = 0
},
}) })
}, },
} }
@ -303,6 +309,7 @@ const onUpdateFilter = (filters, sourceColumn) => {
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
cancelEdit()
}, },
}) })
</script> </script>

View File

@ -0,0 +1,60 @@
<script setup>
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import Code from '@/components/icons/Code.vue'
import Conversion from '@/components/icons/Conversion.vue'
import DropdownSelector from '@/components/common/DropdownSelector.vue'
import { some } from 'lodash'
const props = defineProps({
decode: {
type: String,
default: decodeTypes.NONE,
},
format: {
type: String,
default: formatTypes.RAW,
},
disabled: Boolean,
})
const emit = defineEmits(['formatChanged', 'update:decode', 'update:format'])
const onFormatChanged = (selDecode, selFormat) => {
if (!some(decodeTypes, (val) => val === selDecode)) {
selDecode = decodeTypes.NONE
}
if (!some(formatTypes, (val) => val === selFormat)) {
selFormat = formatTypes.RAW
}
emit('formatChanged', selDecode, selFormat)
if (selDecode !== props.decode) {
emit('update:decode', selDecode)
}
if (selFormat !== props.format) {
emit('update:format', selFormat)
}
}
</script>
<template>
<n-space :size="0" :wrap="false" :wrap-item="false" align="center" justify="start" style="margin-top: 5px">
<dropdown-selector
:default="formatTypes.RAW"
:disabled="props.disabled"
:icon="Code"
:options="formatTypes"
:tooltip="$t('interface.view_as')"
:value="props.format"
@update:value="(f) => onFormatChanged(props.decode, f)" />
<n-divider vertical />
<dropdown-selector
:default="decodeTypes.NONE"
:disabled="props.disabled"
:icon="Conversion"
:options="decodeTypes"
:tooltip="$t('interface.decode_with')"
:value="props.decode"
@update:value="(d) => onFormatChanged(d, props.format)" />
</n-space>
</template>
<style lang="scss" scoped></style>

View File

@ -1,7 +1,6 @@
<script setup> <script setup>
import { computed, h, reactive, ref, watch } from 'vue' import { computed, h, reactive, ref, watch } from 'vue'
import { types, typesColor } from '@/consts/support_redis_type.js' import { types, typesColor } from '@/consts/support_redis_type.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import useDialog from 'stores/dialog' import useDialog from 'stores/dialog'
import { isEmpty, keys, map } from 'lodash' import { isEmpty, keys, map } from 'lodash'
import NewStringValue from '@/components/new_value/NewStringValue.vue' import NewStringValue from '@/components/new_value/NewStringValue.vue'
@ -117,16 +116,14 @@ const onAdd = async () => {
if (value == null) { if (value == null) {
value = defaultValue[type] value = defaultValue[type]
} }
const { success, msg, nodeKey } = await browserStore.setKey( const { success, msg, nodeKey } = await browserStore.setKey({
server, server,
db, db,
key, key,
type, keyType: type,
value, value,
ttl, ttl,
formatTypes.PLAIN_TEXT, })
decodeTypes.NONE,
)
if (success) { if (success) {
// select current key // select current key
tabStore.setSelectedKeys(server, nodeKey) tabStore.setSelectedKeys(server, nodeKey)

View File

@ -3,7 +3,7 @@
* @enum {string} * @enum {string}
*/ */
export const formatTypes = { export const formatTypes = {
PLAIN_TEXT: 'Plain Text', RAW: 'Raw',
JSON: 'JSON', JSON: 'JSON',
// XML: 'XML', // XML: 'XML',
// YML: 'YML', // YML: 'YML',

View File

@ -7,6 +7,7 @@
"warning": "Warning", "warning": "Warning",
"error": "Error", "error": "Error",
"save": "Save", "save": "Save",
"update": "Update",
"none": "None", "none": "None",
"second": "Second(s)", "second": "Second(s)",
"unit_day": "D", "unit_day": "D",

View File

@ -7,6 +7,7 @@
"warning": "Aviso", "warning": "Aviso",
"error": "Erro", "error": "Erro",
"save": "Salvar", "save": "Salvar",
"update": "Atualizar",
"none": "Nenhum", "none": "Nenhum",
"second": "Segundo(s)", "second": "Segundo(s)",
"unit_day": "D", "unit_day": "D",

View File

@ -7,6 +7,7 @@
"warning": "警告", "warning": "警告",
"error": "错误", "error": "错误",
"save": "保存", "save": "保存",
"update": "更新",
"none": "无", "none": "无",
"second": "秒", "second": "秒",
"unit_day": "天", "unit_day": "天",

View File

@ -22,6 +22,7 @@ import {
AddZSetValue, AddZSetValue,
CleanCmdHistory, CleanCmdHistory,
CloseConnection, CloseConnection,
ConvertValue,
DeleteKey, DeleteKey,
FlushDB, FlushDB,
GetCmdHistory, GetCmdHistory,
@ -50,6 +51,7 @@ import { KeyViewType } from '@/consts/key_view_type.js'
import { ConnectionType } from '@/consts/connection_type.js' import { ConnectionType } from '@/consts/connection_type.js'
import { types } from '@/consts/support_redis_type.js' import { types } from '@/consts/support_redis_type.js'
import useConnectionStore from 'stores/connections.js' import useConnectionStore from 'stores/connections.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
const useBrowserStore = defineStore('browser', { const useBrowserStore = defineStore('browser', {
/** /**
@ -421,17 +423,19 @@ const useBrowserStore = defineStore('browser', {
/** /**
* reload key * reload key
* @param server * @param {string} server
* @param db * @param {number} db
* @param key * @param {string|number[]} key
* @param {string} [decode]
* @param {string} [format]
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async reloadKey({ server, db, key }) { async reloadKey({ server, db, key, decode, format }) {
const tab = useTabStore() const tab = useTabStore()
try { try {
tab.updateLoading({ server, db, loading: true }) tab.updateLoading({ server, db, loading: true })
await this.loadKeySummary({ server, db, key }) await this.loadKeySummary({ server, db, key })
await this.loadKeyDetail({ server, db, key, reset: true }) await this.loadKeyDetail({ server, db, key, decode, format, reset: true })
} finally { } finally {
tab.updateLoading({ server, db, loading: false }) tab.updateLoading({ server, db, loading: false })
} }
@ -442,14 +446,14 @@ const useBrowserStore = defineStore('browser', {
* @param {string} server * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} [viewType] * @param {string} [format]
* @param {string} [decodeType] * @param {string} [decode]
* @param {string} [matchPattern] * @param {string} [matchPattern]
* @param {boolean} [reset] * @param {boolean} [reset]
* @param {boolean} [full] * @param {boolean} [full]
* @return {Promise<void>} * @return {Promise<void>}
*/ */
async loadKeyDetail({ server, db, key, viewType, decodeType, matchPattern, reset, full }) { async loadKeyDetail({ server, db, key, format, decode, matchPattern, reset, full }) {
const tab = useTabStore() const tab = useTabStore()
try { try {
tab.updateLoading({ server, db, loading: true }) tab.updateLoading({ server, db, loading: true })
@ -457,31 +461,51 @@ const useBrowserStore = defineStore('browser', {
server, server,
db, db,
key, key,
viewAs: viewType, format,
decodeType, decode,
matchPattern, matchPattern,
full: full === true, full: full === true,
reset, reset,
lite: true, lite: true,
}) })
if (success) { if (success) {
const { value, viewAs, decodeType: decode, end } = data const { value, decode: retDecode, format: retFormat, end } = data
tab.updateValue({ tab.updateValue({
server, server,
db, db,
key: decodeRedisKey(key), key: decodeRedisKey(key),
value, value,
viewAs, decode: retDecode,
decode, format: retFormat,
reset: reset || full === true, reset: reset || full === true,
end, end,
}) })
} else {
$message.error('load key detail fail:' + msg)
} }
} finally { } finally {
tab.updateLoading({ server, db, loading: false }) tab.updateLoading({ server, db, loading: false })
} }
}, },
/**
* convert value by decode type or format
* @param {string|number[]} value
* @param {string} [decode]
* @param {string} [format]
* @return {Promise<{[format]: string, [decode]: string, value: string}>}
*/
async convertValue({ value, decode, format }) {
try {
const { data, success } = await ConvertValue(value, decode, format)
if (success) {
const { value: retVal, decode: retDecode, format: retFormat } = data
return { value: retVal, decode: retDecode, format: retFormat }
}
} catch (e) {}
return { value, decode, format }
},
/** /**
* scan keys with prefix * scan keys with prefix
* @param {string} connName * @param {string} connName
@ -929,27 +953,41 @@ const useBrowserStore = defineStore('browser', {
/** /**
* set redis key * set redis key
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} keyType * @param {string} keyType
* @param {any} value * @param {any} value
* @param {number} ttl * @param {number} ttl
* @param {string} [viewAs] * @param {string} [format]
* @param {string} [decode] * @param {string} [decode]
* @returns {Promise<{[msg]: string, success: boolean, [nodeKey]: {string}}>} * @returns {Promise<{[msg]: string, success: boolean, [nodeKey]: {string}}>}
*/ */
async setKey(connName, db, key, keyType, value, ttl, viewAs, decode) { async setKey({ server, db, key, keyType, value, ttl, format = formatTypes.RAW, decode = decodeTypes.NONE }) {
try { try {
const { data, success, msg } = await SetKeyValue(connName, db, key, keyType, value, ttl, viewAs, decode) const { data, success, msg } = await SetKeyValue({
server,
db,
key,
keyType,
value,
ttl,
format,
decode,
})
if (success) { if (success) {
const { value } = data
// update tree view data // update tree view data
const { newKey = 0 } = this._addKeyNodes(connName, db, [key], true) const { newKey = 0 } = this._addKeyNodes(server, db, [key], true)
if (newKey > 0) { if (newKey > 0) {
this._tidyNode(connName, db, key) this._tidyNode(server, db, key)
this._updateDBMaxKeys(connName, db, newKey) this._updateDBMaxKeys(server, db, newKey)
}
return {
success,
nodeKey: `${server}/db${db}#${ConnectionType.RedisValue}/${key}`,
updatedValue: value,
} }
return { success, nodeKey: `${connName}/db${db}#${ConnectionType.RedisValue}/${key}` }
} else { } else {
return { success, msg } return { success, msg }
} }
@ -959,30 +997,54 @@ const useBrowserStore = defineStore('browser', {
}, },
/** /**
* update hash field * update hash entry
* when field is set, newField is null, delete field * when field is set, newField is null, delete field
* when field is null, newField is set, add new field * when field is null, newField is set, add new field
* when both field and newField are set, and field === newField, update field * when both field and newField are set, and field === newField, update field
* when both field and newField are set, and field !== newField, delete field and add newField * when both field and newField are set, and field !== newField, delete field and add newField
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} field * @param {string} field
* @param {string} newField * @param {string} [newField]
* @param {string} value * @param {string} [value]
* @param {string} [decode]
* @param {string} [format]
* @param {boolean} [refresh]
* @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>} * @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>}
*/ */
async setHash(connName, db, key, field, newField, value) { async setHash({
server,
db,
key,
field,
newField = '',
value = '',
decode = decodeTypes.NONE,
format = formatTypes.RAW,
refresh,
}) {
try { try {
const { data, success, msg } = await SetHashValue(connName, db, key, field, newField || '', value || '') const { data, success, msg } = await SetHashValue({
server,
db,
key,
field,
newField,
value,
decode,
format,
})
if (success) { if (success) {
const { updated = {}, removed = [], replaced = {} } = data const { updated = {}, removed = [], replaced = {} } = data
const tab = useTabStore() if (refresh === true) {
if (!isEmpty(removed)) { const tab = useTabStore()
tab.removeValueEntries({ server: connName, db, key, type: 'hash', entries: removed }) if (!isEmpty(removed)) {
} tab.removeValueEntries({ server, db, key, type: 'hash', entries: removed })
if (!isEmpty(updated)) { }
tab.upsertValueEntries({ server: connName, db, key, type: 'hash', entries: updated }) if (!isEmpty(updated)) {
tab.upsertValueEntries({ server, db, key, type: 'hash', entries: updated })
}
} }
return { success, updated } return { success, updated }
} else { } else {

View File

@ -19,8 +19,8 @@ const useTabStore = defineStore('tab', {
* @param {number} [size] memory usage * @param {number} [size] memory usage
* @param {number} [length] length of content or entries * @param {number} [length] length of content or entries
* @property {int} [ttl] ttl of current key * @property {int} [ttl] ttl of current key
* @param {string} [viewAs]
* @param {string} [decode] * @param {string} [decode]
* @param {string} [format]
* @param {boolean} [end] * @param {boolean} [end]
* @param {boolean} [loading] * @param {boolean} [loading]
*/ */
@ -149,18 +149,18 @@ const useTabStore = defineStore('tab', {
* @param {number} db * @param {number} db
* @param {string} key * @param {string} key
* @param {*} value * @param {*} value
* @param {string} [viewAs] * @param {string} [format]
* @param {string] [decode] * @param {string] [decode]
* @param {boolean} reset * @param {boolean} reset
* @param {boolean} [end] keep end status if not set * @param {boolean} [end] keep end status if not set
*/ */
updateValue({ server, db, key, value, viewAs, decode, reset, end }) { updateValue({ server, db, key, value, format, decode, reset, end }) {
const tab = find(this.tabList, { name: server, db, key }) const tab = find(this.tabList, { name: server, db, key })
if (tab == null) { if (tab == null) {
return return
} }
tab.viewAs = viewAs || tab.viewAs tab.format = format || tab.format
tab.decode = decode || tab.decode tab.decode = decode || tab.decode
if (typeof end === 'boolean') { if (typeof end === 'boolean') {
tab.end = end tab.end = end

View File

@ -57,6 +57,10 @@ export const themeOverrides = {
Message: { Message: {
margin: '0 0 38px 0', margin: '0 0 38px 0',
}, },
DataTable: {
thPaddingSmall: '6px 8px',
tdPaddingSmall: '6px 8px',
},
} }
/** /**