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
This commit is contained in:
tiny-craft 2023-11-13 15:28:13 +08:00
parent a2ad85627e
commit a49d618288
16 changed files with 637 additions and 364 deletions

View File

@ -629,7 +629,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
case "string":
var str string
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.DecodeType, data.ViewAs = strutil.ConvertTo(str, param.DecodeType, param.ViewAs)
case "list":
loadListHandle := func() ([]string, bool, error) {
@ -839,184 +840,56 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
return
}
// GetKeyValue get value by key
func (b *browserService) GetKeyValue(connName string, db int, k any, viewAs, decodeType string) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db)
if err != nil {
resp.Msg = err.Error()
return
}
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
}
// ConvertValue convert value with decode method and format
// blank decodeType indicate auto decode
// blank viewAs indicate auto format
func (b *browserService) ConvertValue(value any, decode, format string) (resp types.JSResp) {
str := strutil.DecodeRedisKey(value)
value, decode, format = strutil.ConvertTo(str, decode, format)
resp.Success = true
resp.Data = map[string]any{
"type": keyType,
"ttl": ttl,
"value": value,
"size": size,
"length": length,
"viewAs": viewAs,
"decode": decodeType,
"decode": decode,
"format": format,
}
return
}
// SetKeyValue set value by key
// @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) {
item, err := b.getRedisClient(connName, db)
func (b *browserService) SetKeyValue(param types.SetKeyParam) (resp types.JSResp) {
item, err := b.getRedisClient(param.Server, param.DB)
if err != nil {
resp.Msg = err.Error()
return
}
client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k)
key := strutil.DecodeRedisKey(param.Key)
var expiration time.Duration
if ttl < 0 {
if param.TTL < 0 {
if expiration, err = client.PTTL(ctx, key).Result(); err != nil {
expiration = redis.KeepTTL
}
} 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.VIEWAS_PLAIN_TEXT
}
switch strings.ToLower(param.KeyType) {
case "string":
if str, ok := value.(string); !ok {
if str, ok := param.Value.(string); !ok {
resp.Msg = "invalid string value"
return
} else {
var saveStr string
if saveStr, err = strutil.SaveAs(str, viewAs, decode); err != nil {
resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, viewAs, err.Error())
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
}
_, err = client.Set(ctx, key, saveStr, 0).Result()
@ -1026,7 +899,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
}
case "list":
if strs, ok := value.([]any); !ok {
if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid list value"
return
} else {
@ -1036,7 +909,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
}
case "hash":
if strs, ok := value.([]any); !ok {
if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid hash value"
return
} else {
@ -1054,7 +927,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
}
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"
return
} else {
@ -1066,7 +939,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
}
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"
return
} else {
@ -1086,7 +959,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
}
case "stream":
if strs, ok := value.([]any); !ok {
if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid stream value"
return
} else {
@ -1109,46 +982,52 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
}
resp.Success = true
resp.Data = map[string]any{
"value": value,
"value": param.Value,
}
return
}
// SetHashValue set hash field
func (b *browserService) SetHashValue(connName string, db int, k any, field, newField, value string) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db)
func (b *browserService) SetHashValue(param types.SetHashParam) (resp types.JSResp) {
item, err := b.getRedisClient(param.Server, param.DB)
if err != nil {
resp.Msg = err.Error()
return
}
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
updatedField := map[string]string{}
replacedField := map[string]string{}
if len(field) <= 0 {
updatedField := map[string]any{}
replacedField := map[string]any{}
if len(param.Field) <= 0 {
// old filed is empty, add new field
_, err = client.HSet(ctx, key, newField, value).Result()
updatedField[newField] = value
} else if len(newField) <= 0 {
_, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
updatedField[param.NewField] = saveStr
} else if len(param.NewField) <= 0 {
// new field is empty, delete old field
_, err = client.HDel(ctx, key, field, value).Result()
removedField = append(removedField, field)
} else if field == newField {
// replace field
_, err = client.HSet(ctx, key, newField, value).Result()
updatedField[newField] = value
_, err = client.HDel(ctx, key, param.Field).Result()
removedField = append(removedField, param.Field)
} else if param.Field == param.NewField {
// update field value
_, err = client.HSet(ctx, key, param.Field, saveStr).Result()
updatedField[param.NewField] = saveStr
} else {
// 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()
return
}
_, err = client.HSet(ctx, key, newField, value).Result()
removedField = append(removedField, field)
updatedField[newField] = value
replacedField[field] = newField
_, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
removedField = append(removedField, param.Field)
updatedField[param.NewField] = saveStr
replacedField[param.Field] = param.NewField
}
if err != nil {
resp.Msg = err.Error()

View File

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

View File

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

View File

@ -2,7 +2,7 @@
import { computed, h, nextTick, reactive, ref } from 'vue'
import IconButton from '@/components/common/IconButton.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 Delete from '@/components/icons/Delete.vue'
import dayjs from 'dayjs'

View File

@ -0,0 +1,180 @@
<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', 'viewAs', '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.PLAIN_TEXT,
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) => {
// TODO: reconvert back to origin format
// emit('update:value', value)
viewAs.value = value
}
const onSave = () => {
// TODO: convert value by decode and format
// viewAs.decode, viewAs.format
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 ContentToolbar from './ContentToolbar.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 EditableTableColumn from '@/components/common/EditableTableColumn.vue'
import useDialogStore from 'stores/dialog.js'
@ -14,6 +14,8 @@ import useBrowserStore from 'stores/browser.js'
import LoadList from '@/components/icons/LoadList.vue'
import LoadAll from '@/components/icons/LoadAll.vue'
import IconButton from '@/components/common/IconButton.vue'
import ContentEntryEditor from '@/components/content_value/ContentEntryEditor.vue'
import Edit from '@/components/icons/Edit.vue'
const i18n = useI18n()
const themeVars = useThemeVars()
@ -33,7 +35,7 @@ const props = defineProps({
value: Object,
size: Number,
length: Number,
viewAs: {
format: {
type: String,
default: formatTypes.PLAIN_TEXT,
},
@ -74,31 +76,27 @@ const currentEditRow = ref({
no: 0,
key: '',
value: null,
format: formatTypes.PLAIN_TEXT,
decode: decodeTypes.NONE,
})
const inEdit = computed(() => {
return currentEditRow.value.no > 0
})
const tableRef = ref(null)
const fieldColumn = reactive({
key: 'key',
title: i18n.t('common.field'),
align: 'center',
titleAlign: 'center',
resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null,
filter(value, row) {
return !!~row.key.indexOf(value.toString())
},
// sorter: (row1, row2) => row1.key - row2.key,
render: (row) => {
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({
key: 'value',
@ -106,34 +104,58 @@ const valueColumn = reactive({
align: 'center',
titleAlign: 'center',
resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null,
filter(value, row) {
return !!~row.value.indexOf(value.toString())
},
// sorter: (row1, row2) => row1.value - row2.value,
// ellipsis: {
// 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 cancelEdit = () => {
const startEdit = async ({ no, key, value }) => {
currentEditRow.value.value = value
currentEditRow.value.no = no
currentEditRow.value.key = key
}
const saveEdit = async (field, value, decode, format) => {
try {
const row = tableData.value[currentEditRow.value.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.key,
newField: field,
value,
decode,
format,
})
if (success) {
row.key = field
row.value = updated[row.key] || ''
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
resetEdit()
}
}
const resetEdit = () => {
currentEditRow.value.no = 0
currentEditRow.value.key = ''
currentEditRow.value.value = null
currentEditRow.value.format = formatTypes.PLAIN_TEXT
currentEditRow.value.decode = decodeTypes.NONE
}
const actionColumn = {
@ -145,13 +167,9 @@ const actionColumn = {
fixed: 'right',
render: (row) => {
return h(EditableTableColumn, {
editing: currentEditRow.value.no === row.no,
editing: false,
bindKey: row.key,
onEdit: () => {
currentEditRow.value.no = row.no
currentEditRow.value.key = row.key
currentEditRow.value.value = row.value
},
onEdit: () => startEdit(row),
onDelete: async () => {
try {
const { success, msg } = await browserStore.removeHashField(
@ -169,32 +187,13 @@ const actionColumn = {
$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: cancelEdit,
})
},
}
const columns = reactive([
const columns = computed(() => {
if (!inEdit.value) {
return [
{
key: 'no',
title: '#',
@ -205,7 +204,28 @@ const columns = reactive([
fieldColumn,
valueColumn,
actionColumn,
])
]
} else {
return [
{
key: 'no',
title: '#',
width: 80,
align: 'center',
titleAlign: 'center',
render(row) {
if (row.no === currentEditRow.value.no) {
// editing row, show edit state
return h(NIcon, { size: 16, color: 'red' }, () => h(Edit, { strokeWidth: 5 }))
} else {
return row.no
}
},
},
fieldColumn,
]
}
})
const tableData = computed(() => {
const data = []
@ -220,6 +240,17 @@ const tableData = computed(() => {
return data
})
const rowProps = (row) => {
return {
onClick: () => {
// in edit mode, switch edit row by click
if (inEdit.value) {
startEdit(row)
}
},
}
}
const entries = computed(() => {
const len = size(tableData.value)
return `${len} / ${Math.max(len, props.length)}`
@ -232,12 +263,12 @@ const onAddRow = () => {
const filterValue = ref('')
const onFilterInput = (val) => {
switch (filterType.value) {
case filterOption[0].value:
case filterOption.value[0].value:
// filter field
valueColumn.filterOptionValue = null
fieldColumn.filterOptionValue = val
break
case filterOption[1].value:
case filterOption.value[1].value:
// filter value
fieldColumn.filterOptionValue = null
valueColumn.filterOptionValue = val
@ -256,10 +287,10 @@ const clearFilter = () => {
const onUpdateFilter = (filters, sourceColumn) => {
switch (filterType.value) {
case filterOption[0].value:
case filterOption.value[0].value:
fieldColumn.filterOptionValue = filters[sourceColumn.key]
break
case filterOption[1].value:
case filterOption.value[1].value:
valueColumn.filterOptionValue = filters[sourceColumn.key]
break
}
@ -268,7 +299,7 @@ const onUpdateFilter = (filters, sourceColumn) => {
defineExpose({
reset: () => {
clearFilter()
cancelEdit()
resetEdit()
},
})
</script>
@ -328,14 +359,17 @@ defineExpose({
{{ $t('interface.add_row') }}
</n-button>
</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
:key="(row) => row.no"
ref="tableRef"
:bordered="false"
:bottom-bordered="false"
:columns="columns"
:data="tableData"
:loading="props.loading"
:row-props="rowProps"
:single-column="true"
:single-line="false"
class="flex-item-expand"
@ -344,6 +378,20 @@ defineExpose({
striped
virtual-scroll
@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 class="value-footer flex-box-h">
<n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text>

View File

@ -1,5 +1,5 @@
<script setup>
import { computed, ref } from 'vue'
import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.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 { ClipboardSetText } from 'wailsjs/runtime/runtime.js'
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 bytes from 'bytes'
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 themeVars = useThemeVars()
@ -32,17 +31,9 @@ const props = defineProps({
type: Number,
default: -1,
},
value: String,
value: [String, Array],
size: Number,
length: Number,
viewAs: {
type: String,
default: formatTypes.PLAIN_TEXT,
},
decode: {
type: String,
default: decodeTypes.NONE,
},
loading: Boolean,
})
@ -58,7 +49,7 @@ const keyName = computed(() => {
const keyType = redisTypes.STRING
const viewLanguage = computed(() => {
switch (props.viewAs) {
switch (viewAs.format) {
case formatTypes.JSON:
return 'json'
default:
@ -66,31 +57,48 @@ const viewLanguage = computed(() => {
}
})
const onViewTypeUpdate = (viewType) => {
browserStore.loadKeyDetail({
server: props.name,
db: props.db,
key: keyName.value,
viewType,
decodeType: props.decode,
})
}
const viewAs = reactive({
value: '',
format: formatTypes.PLAIN_TEXT,
decode: decodeTypes.NONE,
})
const onDecodeTypeUpdate = (decodeType) => {
browserStore.loadKeyDetail({
server: props.name,
db: props.db,
key: keyName.value,
viewType: props.viewAs,
decodeType,
const displayValue = computed(() => {
if (props.loading) {
return ''
}
return viewAs.value || decodeRedisKey(props.value)
})
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
*/
const onCopyValue = () => {
ClipboardSetText(props.value)
ClipboardSetText(displayValue.value)
.then((succ) => {
if (succ) {
$message.success(i18n.t('dialogue.copy_succ'))
@ -104,7 +112,7 @@ const onCopyValue = () => {
const editValue = ref('')
const inEdit = ref(false)
const onEditValue = () => {
editValue.value = props.value
editValue.value = displayValue.value
inEdit.value = true
}
@ -120,16 +128,16 @@ const saving = ref(false)
const onSaveValue = async () => {
saving.value = true
try {
const { success, msg } = await browserStore.setKey(
props.name,
props.db,
keyName.value,
toLower(keyType),
editValue.value,
-1,
props.viewAs,
props.decode,
)
const { success, msg } = await browserStore.setKey({
server: props.name,
db: props.db,
key: keyName.value,
keyType: toLower(keyType),
value: editValue.value,
ttl: -1,
format: viewAs.format,
decode: viewAs.decode,
})
if (success) {
await browserStore.loadKeyDetail({ server: props.name, db: props.db, key: keyName.value })
$message.success(i18n.t('dialogue.save_value_succ'))
@ -146,8 +154,10 @@ const onSaveValue = async () => {
defineExpose({
reset: () => {
viewAs.value = ''
inEdit.value = false
},
beforeShow: () => onFormatChanged(),
})
</script>
@ -198,7 +208,7 @@ defineExpose({
</div>
<div class="value-wrapper value-item-part flex-item-expand flex-box-v">
<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-input
v-else
@ -213,19 +223,11 @@ defineExpose({
<n-divider v-if="!isNaN(props.length)" vertical />
<n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text>
<div class="flex-item-expand"></div>
<dropdown-selector
:icon="Code"
:options="formatTypes"
:tooltip="$t('interface.view_as')"
:value="props.viewAs"
@update:value="onViewTypeUpdate" />
<n-divider vertical />
<dropdown-selector
:icon="Conversion"
:options="decodeTypes"
:tooltip="$t('interface.decode_with')"
:value="props.decode"
@update:value="onDecodeTypeUpdate" />
<format-selector
:decode="viewAs.decode"
:disabled="inEdit"
:format="viewAs.format"
@format-changed="onFormatChanged" />
</div>
</div>
</template>

View File

@ -10,7 +10,6 @@ import { useThemeVars } from 'naive-ui'
import useBrowserStore from 'stores/browser.js'
import { computed, onMounted, ref, watch } from 'vue'
import { isEmpty } from 'lodash'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import useDialogStore from 'stores/dialog.js'
const themeVars = useThemeVars()
@ -45,6 +44,7 @@ const props = defineProps({
const data = computed(() => {
return props.content
})
const initializing = ref(false)
const binaryKey = computed(() => {
return !!data.value.keyCode
@ -116,22 +116,29 @@ const onLoadAll = () => {
loadData(false, true)
}
onMounted(() => {
// onReload()
loadData(false, false)
})
const contentRef = ref(null)
watch(
() => data.value?.keyPath,
() => {
const initContent = async () => {
// onReload()
try {
initializing.value = true
if (contentRef.value?.reset != null) {
contentRef.value?.reset()
}
loadData(false, false)
},
)
await loadData(false, false)
if (contentRef.value?.beforeShow != null) {
await contentRef.value?.beforeShow()
}
} finally {
initializing.value = false
}
}
onMounted(() => {
// onReload()
initContent()
})
const contentRef = ref(null)
watch(() => data.value?.keyPath, initContent)
</script>
<template>
@ -145,17 +152,15 @@ watch(
:is="valueComponents[data.type]"
ref="contentRef"
:db="data.db"
:decode="data.decode || decodeTypes.NONE"
:end="data.end"
:key-code="data.keyCode"
:key-path="data.keyPath"
:length="data.length"
:loading="data.loading === true"
:loading="data.loading === true || initializing"
:name="data.name"
:size="data.size"
:ttl="data.ttl"
:value="data.value"
:view-as="data.viewAs || formatTypes.PLAIN_TEXT"
@delete="onDelete"
@loadall="onLoadAll"
@loadmore="onLoadMore"

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

View File

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

View File

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

View File

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

View File

@ -22,6 +22,7 @@ import {
AddZSetValue,
CleanCmdHistory,
CloseConnection,
ConvertValue,
DeleteKey,
FlushDB,
GetCmdHistory,
@ -50,6 +51,7 @@ import { KeyViewType } from '@/consts/key_view_type.js'
import { ConnectionType } from '@/consts/connection_type.js'
import { types } from '@/consts/support_redis_type.js'
import useConnectionStore from 'stores/connections.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
const useBrowserStore = defineStore('browser', {
/**
@ -482,6 +484,24 @@ const useBrowserStore = defineStore('browser', {
}
},
/**
* 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
* @param {string} connName
@ -929,27 +949,50 @@ const useBrowserStore = defineStore('browser', {
/**
* set redis key
* @param {string} connName
* @param {string} server
* @param {number} db
* @param {string|number[]} key
* @param {string} keyType
* @param {any} value
* @param {number} ttl
* @param {string} [viewAs]
* @param {string} [format]
* @param {string} [decode]
* @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.PLAIN_TEXT,
decode = decodeTypes.NONE,
}) {
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) {
const { value } = 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) {
this._tidyNode(connName, db, key)
this._updateDBMaxKeys(connName, db, newKey)
this._tidyNode(server, db, key)
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 {
return { success, msg }
}
@ -959,30 +1002,54 @@ const useBrowserStore = defineStore('browser', {
},
/**
* update hash field
* update hash entry
* when field is set, newField is null, delete 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, delete field and add newField
* @param {string} connName
* @param {string} server
* @param {number} db
* @param {string|number[]} key
* @param {string} field
* @param {string} newField
* @param {string} value
* @param {string} [newField]
* @param {string} [value]
* @param {string} [decode]
* @param {string} [format]
* @param {boolean} [refresh]
* @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.PLAIN_TEXT,
refresh,
}) {
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) {
const { updated = {}, removed = [], replaced = {} } = data
if (refresh === true) {
const tab = useTabStore()
if (!isEmpty(removed)) {
tab.removeValueEntries({ server: connName, db, key, type: 'hash', entries: removed })
tab.removeValueEntries({ server, db, key, type: 'hash', entries: removed })
}
if (!isEmpty(updated)) {
tab.upsertValueEntries({ server: connName, db, key, type: 'hash', entries: updated })
tab.upsertValueEntries({ server, db, key, type: 'hash', entries: updated })
}
}
return { success, updated }
} else {

View File

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