Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(grid): add inline base64 binary preview with format picker

dbin01234c4341db96b5
diff --git a/apps/desktop/src/components/grid/DataGrid.vue b/apps/desktop/src/components/grid/DataGrid.vue
index fff84c59e0..ddde11e475 100644
--- a/apps/desktop/src/components/grid/DataGrid.vue
+++ b/apps/desktop/src/components/grid/DataGrid.vue
@@ -9329,7 +9329,11 @@ function openColumnDetailDialog(columnIndex: number) {
function openContextCellDetailDialog() {
const cell = contextCell.value;
if (!cell || cell.col < 0) return;
- openCellDetailDialog(cell.rowIndex, cell.col);
+ if (cellDetailDialogDefault.value) {
+ openCellDetailDialog(cell.rowIndex, cell.col);
+ } else {
+ showCellDetails(cell.rowIndex, cell.col);
+ }
}
function openContextColumnDetailDialog() {
@@ -15853,7 +15857,7 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
<DataGridCellDetailHexViewer v-if="activeCellDetailTabs.includes('hexViewer')" :rows="activeBinaryHexRows" :byte-count="activeBinaryHexByteCount" />
<TabsContent v-if="activeCellDetailTabs.includes('valueEditor')" value="valueEditor" class="m-0 min-h-0 min-w-0 flex-1 flex flex-col p-3 text-xs">
- <div class="min-w-0 flex min-h-0 flex-1 flex-col">
+ <div :style="detailTransformOpen ? { display: 'none' } : null" class="min-w-0 flex min-h-0 flex-1 flex-col">
<TemporalCellEditor
v-if="detailTemporalEditorConfig"
v-model="detailEditValue"
@@ -15874,6 +15878,8 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
:identity="`${activeCellDetail.rowId}:${activeCellDetail.colIndex}:${activeCellDetailTab}`"
:incomplete="activeCellDetail.isSourceTruncated"
:unsafe-number="typeof activeCellDetail.value === 'number' && Number.isInteger(activeCellDetail.value) && !Number.isSafeInteger(activeCellDetail.value) && detailEditValue === activeCellDetail.rawValue"
+ :column="activeCellDetail.column"
+ :row-number="activeCellDetail.rowNumber"
/>
<DropdownMenu v-if="activeCellDetail?.isEditable">
<DropdownMenuTrigger as-child>
diff --git a/apps/desktop/src/components/grid/DataGridCellDetailDialog.vue b/apps/desktop/src/components/grid/DataGridCellDetailDialog.vue
index 6bf52de5e3..91f4c289e2 100644
--- a/apps/desktop/src/components/grid/DataGridCellDetailDialog.vue
+++ b/apps/desktop/src/components/grid/DataGridCellDetailDialog.vue
@@ -40,6 +40,7 @@ const emit = defineEmits<{
const open = defineModel<boolean>("open", { default: false });
const geometryPreviewOpen = ref(false);
+const valueTransformOpen = ref(false);
const geometryCanvas = ref<HTMLCanvasElement | null>(null);
const jsonPreviewContainer = ref<HTMLElement>();
let jsonPreviewEditor: UseCellDetailEditorReturn | null = null;
@@ -73,7 +74,10 @@ function copyColumnName() {
}
watch(open, (isOpen) => {
- if (!isOpen) geometryPreviewOpen.value = false;
+ if (!isOpen) {
+ geometryPreviewOpen.value = false;
+ valueTransformOpen.value = false;
+ }
});
watch(
@@ -155,20 +159,23 @@ watch(
<div class="whitespace-pre-wrap break-words">{{ detail.comment || t("grid.noComment") }}</div>
</div>
- <div class="space-y-2">
- <div class="flex items-center justify-between gap-2">
+ <div :class="detail.imagePreviewUrl ? 'grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] items-start gap-2' : 'space-y-2'">
+ <div class="flex items-center justify-between gap-2" :class="detail.imagePreviewUrl ? 'col-span-2' : ''">
<div class="text-muted-foreground">{{ t("grid.cellValue") }}</div>
- <div class="flex items-center gap-1">
+ <div class="flex min-w-0 flex-1 flex-wrap items-center justify-end gap-1">
<!-- Binary cells keep `0x<hex>` as the canonical value; the transform kinds below
(timestamp/JSON/radix…) have text semantics and would misread hex. Offer the
explicit, read-only bytes decode instead. -->
<DataGridCellDetailTextPreview v-if="open && isBinaryCellColumnType(detail.type)" :identity="`${detail.rowId}:${detail.colIndex}`" :value="detail.value" :column-type="detail.type" :database-type="databaseType" :incomplete="detail.isSourceTruncated" />
<DataGridValueTransform
v-else-if="open"
+ v-model:open="valueTransformOpen"
:source="(detail.isNull ?? detail.value === null) ? null : detail.rawValue"
:identity="`${detail.rowId}:${detail.colIndex}`"
:incomplete="detail.isSourceTruncated"
:unsafe-number="typeof detail.value === 'number' && Number.isInteger(detail.value) && !Number.isSafeInteger(detail.value)"
+ :column="detail.column"
+ :row-number="detail.rowNumber"
/>
<Button v-if="detail.formattedJson" :variant="jsonView ? 'secondary' : 'ghost'" size="sm" class="h-6 gap-1 px-2 text-xs" :title="t('grid.formattedJson')" @click="toggleJsonFormatted">
<Code2 class="h-3 w-3" />
@@ -220,12 +227,32 @@ watch(
</Popover>
</div>
</div>
- <a v-if="detail.imagePreviewUrl" :href="detail.imagePreviewUrl" role="button" class="block max-h-72 overflow-hidden rounded border bg-muted/20" @click.prevent="openImagePreview(detail.imagePreviewUrl, detail.column)">
+ <a
+ v-if="detail.imagePreviewUrl"
+ :style="valueTransformOpen ? { display: 'none' } : null"
+ :href="detail.imagePreviewUrl"
+ role="button"
+ class="block max-h-72 overflow-hidden rounded border bg-muted/20"
+ :class="detail.imagePreviewUrl ? 'col-start-2 row-start-2' : ''"
+ @click.prevent="openImagePreview(detail.imagePreviewUrl, detail.column)"
+ >
<img :src="detail.imagePreviewUrl" :alt="detail.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-72 w-full object-contain" />
</a>
- <div v-if="jsonView && detail.formattedJson" ref="jsonPreviewContainer" data-cell-detail-editor-root class="h-[44vh] min-h-60 overflow-hidden rounded border bg-muted/20 p-3" />
- <pre v-else class="dbx-data-grid-value-font max-h-[44vh] overflow-auto rounded border bg-muted/20 p-3 text-xs whitespace-pre-wrap break-words" :class="{ 'italic text-muted-foreground': detail.value === null }">{{ presentedValuePreview }}</pre>
- <div v-if="detail.isValuePreviewTruncated && !jsonView" class="text-[11px] text-muted-foreground">
+ <div
+ v-if="jsonView && detail.formattedJson"
+ :style="valueTransformOpen ? { display: 'none' } : null"
+ :class="detail.imagePreviewUrl ? 'col-start-1 row-start-2' : ''"
+ ref="jsonPreviewContainer"
+ data-cell-detail-editor-root
+ class="h-[44vh] min-h-60 overflow-hidden rounded border bg-muted/20 p-3"
+ />
+ <pre
+ v-else
+ :style="valueTransformOpen ? { display: 'none' } : null"
+ class="dbx-data-grid-value-font max-h-[44vh] overflow-auto rounded border bg-muted/20 p-3 text-xs whitespace-pre-wrap break-words"
+ :class="[detail.value === null ? 'italic text-muted-foreground' : '', detail.imagePreviewUrl ? 'col-start-1 row-start-2' : '']"
+ >{{ presentedValuePreview }}</pre>
+ <div v-if="detail.isValuePreviewTruncated && !jsonView" :style="valueTransformOpen ? { display: 'none' } : null" :class="detail.imagePreviewUrl ? 'col-start-1' : ''" class="text-[11px] text-muted-foreground">
{{ t("grid.largeValuePreviewHint", { count: detail.rawValuePreview.length }) }}
</div>
</div>
diff --git a/apps/desktop/src/components/grid/DataGridCellDetailPanel.vue b/apps/desktop/src/components/grid/DataGridCellDetailPanel.vue
index c6be4209f5..1ac5be4ac4 100644
--- a/apps/desktop/src/components/grid/DataGridCellDetailPanel.vue
+++ b/apps/desktop/src/components/grid/DataGridCellDetailPanel.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import DataGridCellDetailTextPreview from "@/components/grid/DataGridCellDetailTextPreview.vue";
import DataGridValueTransform from "@/components/grid/DataGridValueTransform.vue";
-import { computed, toRef } from "vue";
+import { computed, ref, toRef } from "vue";
import { Code2, Copy, Download, Eye, FileDiff, FileUp, Pencil, X } from "@lucide/vue";
import { useI18n } from "vue-i18n";
import { Button } from "@/components/ui/button";
@@ -77,6 +77,9 @@ void sideJsonPreviewContainer;
const binaryTextPreview = computed(() => (isBlobCellColumnType(props.detail.type) ? binaryCellUtf8Text(props.detail.value, props.detail.type, props.databaseType) : null));
const presentedValuePreview = computed(() => (binaryTextPreview.value === null ? props.detail.rawValuePreview : props.detail.displayValuePreview));
+const transformOpen = ref(false);
+// 底部面板横向空间充足:有图片预览时与值文本左右并排,侧栏窄面板保持上下堆叠。
+const valueBesideImage = computed(() => props.panelIsBottom && !props.editing && !!props.detail.imagePreviewUrl);
function startJsonEditFromBlankArea(event: MouseEvent) {
const target = event.target as { closest?: (selector: string) => Element | null } | null;
@@ -151,18 +154,28 @@ defineExpose({ openSearch });
</div>
</template>
- <div class="space-y-1" :class="[{ 'min-h-0 flex flex-col': valueFillsHeight }, valueFillsHeight && !(detail.imagePreviewUrl && !editing) ? 'flex-1' : '', detail.imagePreviewUrl && !editing ? 'shrink-0' : '']">
- <div class="flex min-h-5 min-w-0 flex-wrap items-center justify-between gap-2">
+ <div
+ :class="[
+ { 'min-h-0 flex flex-col': valueFillsHeight && !valueBesideImage },
+ valueBesideImage ? 'grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] items-start gap-2' : 'space-y-1',
+ valueFillsHeight && !(detail.imagePreviewUrl && !editing) ? 'flex-1' : '',
+ detail.imagePreviewUrl && !editing ? 'shrink-0' : '',
+ ]"
+ >
+ <div class="flex min-h-5 min-w-0 flex-wrap items-center justify-between gap-2" :class="valueBesideImage ? 'col-span-2' : ''">
<div class="shrink-0 text-muted-foreground">{{ t("grid.cellValue") }}</div>
<div class="min-w-0 flex flex-1 flex-wrap items-center justify-end gap-1">
<!-- 与下载菜单同一道闸门:两者都读已提交的 `0x<hex>`,编辑中不对草稿做只读文本预览。 -->
<DataGridCellDetailTextPreview v-if="!editing && isBinaryCellColumnType(detail.type)" :identity="`${detail.rowId}:${detail.colIndex}`" :value="detail.value" :column-type="detail.type" :database-type="databaseType" :incomplete="detail.isSourceTruncated" />
<DataGridValueTransform
v-else-if="!isBinaryCellColumnType(detail.type)"
+ v-model:open="transformOpen"
:source="(detail.isNull ?? detail.value === null) && (!editing || !detailEditValue || detailEditValue === detail.rawValue) ? null : editing ? detailEditValue : detail.rawValue"
:identity="`${detail.rowId}:${detail.colIndex}:${editing}`"
:incomplete="detail.isSourceTruncated"
:unsafe-number="typeof detail.value === 'number' && Number.isInteger(detail.value) && !Number.isSafeInteger(detail.value) && (!editing || detailEditValue === detail.rawValue)"
+ :column="detail.column"
+ :row-number="detail.rowNumber"
/>
<Button v-if="editing && showCompareJson" variant="ghost" size="sm" class="h-5 gap-1 px-1.5 text-xs" :disabled="!canCompareJson" :title="t('grid.compareJson')" @mousedown.prevent @click="emit('compareJson')"><FileDiff class="h-3 w-3" />{{ t("grid.compareJson") }}</Button>
<!-- issue #9832:编辑中「压缩 JSON」作用于草稿,格式化入口不能再被 !editing 挡掉,否则压缩后就无法展开。 -->
@@ -186,14 +199,13 @@ defineExpose({ openSearch });
></Popover>
</div>
</div>
- <div v-if="detail.imagePreviewUrl && !editing" class="shrink-0 space-y-1.5">
- <div class="text-muted-foreground">{{ t("grid.imagePreview") }}</div>
- <a :href="detail.imagePreviewUrl" role="button" class="flex overflow-hidden rounded border bg-muted/20" :class="panelIsBottom ? 'max-h-28' : 'max-h-40'" @click.prevent="openImagePreview(detail.imagePreviewUrl, detail.column)"
- ><img :src="detail.imagePreviewUrl" :alt="detail.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="max-h-full w-full object-contain"
+ <div v-if="detail.imagePreviewUrl && !editing" :style="transformOpen ? { display: 'none' } : null" :class="valueBesideImage ? 'col-start-2 row-start-2' : ''" class="shrink-0">
+ <a :href="detail.imagePreviewUrl" role="button" class="flex overflow-hidden rounded border bg-muted/20" :class="valueBesideImage ? 'max-h-[44vh]' : panelIsBottom ? 'max-h-28' : 'max-h-40'" @click.prevent="openImagePreview(detail.imagePreviewUrl, detail.column)"
+ ><img :src="detail.imagePreviewUrl" :alt="detail.column" loading="lazy" decoding="async" referrerpolicy="no-referrer" class="w-full object-contain" :class="valueBesideImage ? 'max-h-[44vh]' : panelIsBottom ? 'max-h-28' : 'max-h-40'"
/></a>
</div>
<template v-if="editing"
- ><div class="dbx-data-grid-value-font min-h-0 min-w-0 flex-1" :style="editorStyle">
+ ><div class="dbx-data-grid-value-font min-h-0 min-w-0 flex-1" :style="transformOpen ? { display: 'none' } : editorStyle">
<TemporalCellEditor v-if="temporalEditorConfig" v-model="detailEditValue" :kind="temporalEditorConfig.kind" :fraction-precision="temporalEditorConfig.fractionPrecision" variant="inline" :commit-on-close="false" @cancel="emit('cancel')" @commit="emit('commit')" @save="emit('save')" />
<div v-else ref="detailsEditorContainer" data-cell-detail-editor-root class="min-h-0 h-full w-full rounded border overflow-hidden" />
</div>
@@ -204,20 +216,27 @@ defineExpose({ openSearch });
>
<div
v-else-if="detail.formattedJson"
+ :style="transformOpen ? { display: 'none' } : null"
ref="sideJsonPreviewContainer"
data-cell-detail-editor-root
data-cell-detail-json-preview
class="overflow-hidden rounded border bg-muted/20 p-2"
- :class="[{ 'cursor-text': detail.isEditable }, valueFillsHeight ? 'min-h-0 flex-1' : 'h-72 max-h-[42vh]']"
+ :class="[{ 'cursor-text': detail.isEditable }, valueBesideImage ? 'col-start-1 row-start-2' : '', valueFillsHeight ? 'min-h-0 flex-1' : 'h-72 max-h-[42vh]']"
@dblclick.capture="startJsonEditFromBlankArea"
/>
<pre
v-else
+ :style="transformOpen ? { display: 'none' } : null"
class="dbx-data-grid-value-font overflow-auto rounded border bg-muted/20 p-2 text-xs whitespace-pre-wrap break-words cursor-pointer hover:border-primary/50"
- :class="[{ 'cursor-text': detail.isEditable }, panelIsBottom && detail.imagePreviewUrl ? 'min-h-24 max-h-32 shrink-0' : '', valueFillsHeight && !detail.imagePreviewUrl ? 'min-h-0 flex-1' : '']"
+ :class="[
+ { 'cursor-text': detail.isEditable },
+ valueBesideImage ? 'col-start-1 row-start-2' : '',
+ panelIsBottom && detail.imagePreviewUrl ? (valueBesideImage ? 'min-h-24 max-h-[44vh]' : 'min-h-24 max-h-32 shrink-0') : '',
+ valueFillsHeight && !detail.imagePreviewUrl ? 'min-h-0 flex-1' : '',
+ ]"
@dblclick="emit('startEdit')"
>{{ presentedValuePreview }}</pre>
- <div v-if="detail.isValuePreviewTruncated && !sideJsonView" class="text-[11px] text-muted-foreground">{{ t("grid.largeValuePreviewHint", { count: detail.rawValuePreview.length }) }}</div>
+ <div v-if="detail.isValuePreviewTruncated && !sideJsonView" :style="transformOpen ? { display: 'none' } : null" :class="valueBesideImage ? 'col-start-1' : ''" class="text-[11px] text-muted-foreground">{{ t("grid.largeValuePreviewHint", { count: detail.rawValuePreview.length }) }}</div>
</div>
</div>
<div class="flex min-w-0 flex-wrap gap-1 overflow-hidden border-t bg-background p-1.5" :class="panelIsBottom ? 'shrink-0 items-center' : 'shrink-0 flex-col'">
diff --git a/apps/desktop/src/components/grid/DataGridValueTransform.vue b/apps/desktop/src/components/grid/DataGridValueTransform.vue
index a4b5650295..8cb0b97e19 100644
--- a/apps/desktop/src/components/grid/DataGridValueTransform.vue
+++ b/apps/desktop/src/components/grid/DataGridValueTransform.vue
@@ -1,11 +1,24 @@
<script setup lang="ts">
-import { computed, ref, useId, watch } from "vue";
+import { computed, onBeforeUnmount, ref, useId, watch } from "vue";
import { useI18n } from "vue-i18n";
+import { X } from "@lucide/vue";
import { copyToClipboard } from "@/lib/common/clipboard";
import { useToast } from "@/composables/useToast";
import { Button } from "@/components/ui/button";
-import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
-import { CELL_TRANSFORM_KINDS, CELL_TRANSFORM_MAX_INPUT, CELL_TRANSFORM_MAX_OUTPUT, CELL_TRANSFORM_MAX_RADIX_DIGITS, transformCellValue, type CellTransformKind, type CellTransformResult } from "@/lib/dataGrid/cellValueTransform";
+import {
+ BINARY_CELL_TRANSFORM_KINDS,
+ CELL_TRANSFORM_FORMAT_CHOICES,
+ CELL_TRANSFORM_KINDS,
+ CELL_TRANSFORM_MAX_BINARY_INPUT,
+ CELL_TRANSFORM_MAX_INPUT,
+ CELL_TRANSFORM_MAX_OUTPUT,
+ CELL_TRANSFORM_MAX_RADIX_DIGITS,
+ transformCellValue,
+ type CellTransformBinaryResult,
+ type CellTransformKind,
+ type CellTransformResult,
+} from "@/lib/dataGrid/cellValueTransform";
+import { binaryCellDownloadFileName, downloadBinaryCellPayload, formatBinaryCellByteSize } from "@/lib/dataGrid/binaryCellDownload";
import { DataGridDateTimePatterns, getSupportedTimeZoneOptions } from "@/lib/dataGrid/columnFormatter";
import { buildSafeHtmlPreview } from "@/lib/common/safeHtmlPreview";
@@ -14,6 +27,8 @@ const props = defineProps<{
identity: string;
incomplete?: boolean;
unsafeNumber?: boolean;
+ column?: string;
+ rowNumber?: number;
}>();
const { t } = useI18n();
const { toast } = useToast();
@@ -27,39 +42,25 @@ const pattern = ref("YYYY-MM-DD HH:mm:ss");
const fromBase = ref(10);
const toBase = ref(16);
const result = ref<CellTransformResult | null>(null);
-let previousEditorFocus: HTMLElement | null = null;
-let previousEditorIdentity = "";
+const formatOverride = ref("");
-function rememberEditorFocus() {
- const active = document.activeElement;
- previousEditorFocus = active instanceof HTMLElement && active.closest("[data-cell-detail-editor-root]") ? active : null;
- previousEditorIdentity = props.identity;
-}
-
-function restoreEditorFocus(event: Event) {
- const target = previousEditorFocus;
- previousEditorFocus = null;
- if (!target?.isConnected || previousEditorIdentity !== props.identity) return;
- // Opening the preview skips the editor's blur commit. Restore its focus so
- // the next deliberate departure still commits the untouched editing draft.
- event.preventDefault();
- target.focus({ preventScroll: true });
-}
+const isBinaryKind = computed(() => BINARY_CELL_TRANSFORM_KINDS.includes(kind.value));
+const inputLimit = computed(() => (isBinaryKind.value ? CELL_TRANSFORM_MAX_BINARY_INPUT : CELL_TRANSFORM_MAX_INPUT));
const blockedReason = computed(() => {
if (props.source === null) return "nullSource";
if (props.incomplete) return "incomplete";
if (props.unsafeNumber) return "unsafeNumber";
- if (props.source.length > CELL_TRANSFORM_MAX_INPUT) return "tooLarge";
+ if (props.source.length > inputLimit.value) return "tooLarge";
return "";
});
// Locale messages only interpolate the grouped limit digits, so translations keep their wording.
-const errorLimits = {
- maxInput: new Intl.NumberFormat("en-US").format(CELL_TRANSFORM_MAX_INPUT),
+const errorLimits = computed(() => ({
+ maxInput: new Intl.NumberFormat("en-US").format(inputLimit.value),
maxOutput: new Intl.NumberFormat("en-US").format(CELL_TRANSFORM_MAX_OUTPUT),
maxRadixDigits: new Intl.NumberFormat("en-US").format(CELL_TRANSFORM_MAX_RADIX_DIGITS),
-};
+}));
// Keep only options between cells. Results must always belong to the current source.
watch(
@@ -67,6 +68,7 @@ watch(
() => {
open.value = false;
result.value = null;
+ formatOverride.value = "";
},
{ flush: "sync" },
);
@@ -74,93 +76,165 @@ watch(
[() => props.source, () => props.incomplete, () => props.unsafeNumber, kind, unit, timezone, pattern, fromBase, toBase, open],
() => {
result.value = null;
+ formatOverride.value = "";
},
{ flush: "sync" },
);
+// Binary kinds decode to bytes, so the UTF-8-text wording of invalidBase64 does not apply.
+const resultErrorKey = computed(() => {
+ if (!result.value || result.value.ok) return "";
+ return result.value.error === "invalidBase64" && isBinaryKind.value ? "invalidBase64Binary" : result.value.error;
+});
+
function convert() {
if (blockedReason.value || props.source === null) return;
result.value = transformCellValue(props.source, { kind: kind.value, unit: unit.value, timezone: timezone.value, pattern: pattern.value, fromBase: fromBase.value, toBase: toBase.value });
}
-const htmlPreviewDocument = computed(() => (kind.value === "html" && result.value?.ok ? buildSafeHtmlPreview(result.value.text) : ""));
+
+const textResult = computed(() => (result.value?.ok && "text" in result.value ? result.value.text : null));
+const binaryResult = computed<CellTransformBinaryResult | null>(() => (result.value?.ok && "binary" in result.value ? result.value.binary : null));
+
+// When auto-detection fails the user picks a format; apply it to preview, label, and save alike.
+const effectiveBinary = computed<CellTransformBinaryResult | null>(() => {
+ const binary = binaryResult.value;
+ if (!binary) return null;
+ if (binary.recognized || !formatOverride.value) return binary;
+ const choice = CELL_TRANSFORM_FORMAT_CHOICES.find((format) => format.mimeType === formatOverride.value);
+ if (!choice) return binary;
+ return { ...binary, mimeType: choice.mimeType, extension: choice.extension, isImage: choice.mimeType.startsWith("image/") };
+});
+
+const imageUrl = ref<string | null>(null);
+function releaseImageUrl() {
+ if (imageUrl.value) URL.revokeObjectURL(imageUrl.value);
+ imageUrl.value = null;
+}
+watch(
+ [effectiveBinary, open],
+ ([binary, isOpen]) => {
+ releaseImageUrl();
+ if (isOpen && binary?.isImage) imageUrl.value = URL.createObjectURL(new Blob([new Uint8Array(binary.bytes)], { type: binary.mimeType }));
+ },
+ { flush: "sync" },
+);
+onBeforeUnmount(releaseImageUrl);
+
+const htmlPreviewDocument = computed(() => (kind.value === "html" && textResult.value !== null ? buildSafeHtmlPreview(textResult.value) : ""));
+const binarySizeText = computed(() => (binaryResult.value ? formatBinaryCellByteSize(binaryResult.value.bytes.length) : ""));
async function copyResult() {
- if (!result.value?.ok) return;
+ if (textResult.value === null) return;
try {
- await copyToClipboard(result.value.text);
+ await copyToClipboard(textResult.value);
toast(t("grid.cellValueCopied"), 2000);
} catch (error) {
toast(error instanceof Error ? error.message : String(error), 5000);
}
}
+
+async function saveResult() {
+ const binary = effectiveBinary.value;
+ if (!binary) return;
+ const fileName = binaryCellDownloadFileName({ column: props.column ?? "cell", rowNumber: props.rowNumber ?? 0, mode: "binary", extension: binary.extension });
+ try {
+ const saved = await downloadBinaryCellPayload({ data: binary.bytes, mimeType: binary.mimeType, extension: binary.extension }, fileName);
+ if (saved.kind === "saved" && saved.path) toast(t("grid.downloadSaved", { path: saved.path }));
+ else if (saved.kind === "browser-download") toast(t("grid.downloadStarted", { fileName: saved.fileName ?? fileName }));
+ } catch (error) {
+ toast(error instanceof Error ? error.message : String(error), 5000);
+ }
+}
</script>
<template>
- <Dialog v-model:open="open">
- <DialogTrigger as-child>
- <Button variant="outline" size="sm" class="h-6 px-2 text-xs" @mousedown.prevent>{{ t("cellTransform.title") }}</Button>
- </DialogTrigger>
- <DialogContent class="flex max-h-[85vh] flex-col overflow-y-auto sm:max-w-2xl" data-native-clipboard @open-auto-focus="rememberEditorFocus" @close-auto-focus="restoreEditorFocus">
- <DialogHeader>
- <DialogTitle>{{ t("cellTransform.title") }}</DialogTitle>
- <DialogDescription>{{ t("cellTransform.description") }}</DialogDescription>
- </DialogHeader>
- <div class="flex flex-wrap items-end gap-3 text-xs">
- <label class="flex flex-col gap-1">
- {{ t("cellTransform.format") }}
- <select v-model="kind" class="h-8 rounded border bg-background px-2">
- <option v-for="item in CELL_TRANSFORM_KINDS" :key="item" :value="item">{{ t(`cellTransform.kinds.${item}`) }}</option>
- </select>
- </label>
- <template v-if="kind === 'timestamp'">
- <label class="flex flex-col gap-1">
- {{ t("cellTransform.unit") }}
- <select v-model="unit" class="h-8 rounded border bg-background px-2">
- <option v-for="item in ['auto', 'seconds', 'milliseconds']" :key="item" :value="item">{{ t(`cellTransform.units.${item}`) }}</option>
- </select>
- </label>
- <label class="flex flex-col gap-1">
- {{ t("cellTransform.timezone") }}
- <input v-model="timezone" :list="`${id}-zones`" class="h-8 rounded border bg-background px-2" />
- <datalist :id="`${id}-zones`"><option v-for="zone in zones" :key="zone" :value="zone" /></datalist>
- </label>
- <label class="flex min-w-0 flex-col gap-1">
- {{ t("cellTransform.pattern") }}
- <select v-model="pattern" class="h-8 max-w-full rounded border bg-background px-2">
- <option v-for="item in DataGridDateTimePatterns" :key="item" :value="item">{{ item }}</option>
+ <Button v-if="!open" variant="outline" size="sm" class="h-6 px-2 text-xs" @mousedown.prevent @click="open = true">{{ t("cellTransform.title") }}</Button>
+ <section v-else data-native-clipboard class="basis-full min-w-0 space-y-2 rounded border bg-muted/20 p-2 text-xs">
+ <div class="flex min-h-5 items-center justify-between gap-2">
+ <div class="min-w-0 truncate font-medium">{{ t("cellTransform.title") }}</div>
+ <Button variant="ghost" size="icon" class="h-5 w-5 shrink-0" :title="t('cellTransform.exitPreview')" @mousedown.prevent @click="open = false"><X class="h-3 w-3" /></Button>
+ </div>
+ <div class="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] items-start gap-2">
+ <div class="flex min-w-0 flex-col gap-1">
+ <div class="text-muted-foreground">{{ t("cellTransform.sourceValue") }}</div>
+ <textarea :value="source ?? ''" :aria-label="t('cellTransform.sourceValue')" readonly class="dbx-data-grid-value-font h-72 min-h-24 w-full resize-y rounded border bg-background p-2" spellcheck="false" />
+ </div>
+ <div class="flex min-w-0 flex-col gap-2">
+ <div class="flex flex-wrap items-end gap-2">
+ <label class="flex min-w-0 basis-full flex-col gap-1">
+ {{ t("cellTransform.format") }}
+ <select v-model="kind" class="h-7 w-full rounded border bg-background px-2">
+ <option v-for="item in CELL_TRANSFORM_KINDS" :key="item" :value="item">{{ t(`cellTransform.kinds.${item}`) }}</option>
</select>
</label>
+ <template v-if="kind === 'timestamp'">
+ <label class="flex flex-col gap-1">
+ {{ t("cellTransform.unit") }}
+ <select v-model="unit" class="h-7 rounded border bg-background px-2">
+ <option v-for="item in ['auto', 'seconds', 'milliseconds']" :key="item" :value="item">{{ t(`cellTransform.units.${item}`) }}</option>
+ </select>
+ </label>
+ <label class="flex flex-col gap-1">
+ {{ t("cellTransform.timezone") }}
+ <input v-model="timezone" :list="`${id}-zones`" class="h-7 w-28 rounded border bg-background px-2" />
+ <datalist :id="`${id}-zones`"><option v-for="zone in zones" :key="zone" :value="zone" /></datalist>
+ </label>
+ <label class="flex min-w-0 flex-col gap-1">
+ {{ t("cellTransform.pattern") }}
+ <select v-model="pattern" class="h-7 max-w-full rounded border bg-background px-2">
+ <option v-for="item in DataGridDateTimePatterns" :key="item" :value="item">{{ item }}</option>
+ </select>
+ </label>
+ </template>
+ <template v-if="kind === 'radix'">
+ <label class="flex flex-col gap-1">
+ {{ t("cellTransform.fromBase") }}
+ <select v-model="fromBase" class="h-7 rounded border bg-background px-2">
+ <option v-for="base in [2, 8, 10, 16]" :key="base" :value="base">{{ base }}</option>
+ </select>
+ </label>
+ <label class="flex flex-col gap-1">
+ {{ t("cellTransform.toBase") }}
+ <select v-model="toBase" class="h-7 rounded border bg-background px-2">
+ <option v-for="base in [2, 8, 10, 16]" :key="base" :value="base">{{ base }}</option>
+ </select>
+ </label>
+ </template>
+ <Button size="sm" class="h-7" :disabled="!!blockedReason" @click="convert">{{ t("cellTransform.convert") }}</Button>
+ </div>
+ <p v-if="kind === 'radix'" class="text-xs text-muted-foreground">{{ t("cellTransform.radixHint") }}</p>
+ <p v-if="kind === 'urlEncode' || kind === 'urlDecode'" class="text-xs text-muted-foreground">{{ t("cellTransform.urlHint") }}</p>
+ <p v-if="kind === 'base64File'" class="text-xs text-muted-foreground">{{ t("cellTransform.fileHint") }}</p>
+ <p v-if="blockedReason" role="status" class="text-xs text-muted-foreground">{{ t(`cellTransform.errors.${blockedReason}`, errorLimits) }}</p>
+ <p v-else-if="result && !result.ok" role="alert" class="text-xs text-destructive">{{ t(`cellTransform.errors.${resultErrorKey}`, errorLimits) }}</p>
+ <template v-if="textResult !== null">
+ <div class="flex items-center justify-between gap-2 text-xs">
+ <span
+ >{{ t("cellTransform.result") }}<template v-if="result?.ok && 'unit' in result && result.unit"> · {{ t(`cellTransform.units.${result.unit}`) }}</template></span
+ >
+ <Button variant="outline" size="sm" class="h-6 text-xs" @click="copyResult">{{ t("cellTransform.copy") }}</Button>
+ </div>
+ <iframe v-if="kind === 'html'" :srcdoc="htmlPreviewDocument" sandbox="" :title="t('cellTransform.htmlPreview')" class="h-56 min-h-24 w-full rounded border bg-white" />
+ <textarea :value="textResult" :aria-label="t('cellTransform.result')" readonly class="dbx-data-grid-value-font h-56 min-h-24 w-full resize-y rounded border bg-background p-2 text-xs" spellcheck="false" />
</template>
- <template v-if="kind === 'radix'">
- <label class="flex flex-col gap-1">
- {{ t("cellTransform.fromBase") }}
- <select v-model="fromBase" class="h-8 rounded border bg-background px-2">
- <option v-for="base in [2, 8, 10, 16]" :key="base" :value="base">{{ base }}</option>
- </select>
- </label>
- <label class="flex flex-col gap-1">
- {{ t("cellTransform.toBase") }}
- <select v-model="toBase" class="h-8 rounded border bg-background px-2">
- <option v-for="base in [2, 8, 10, 16]" :key="base" :value="base">{{ base }}</option>
- </select>
- </label>
+ <template v-else-if="binaryResult && effectiveBinary">
+ <div v-if="!binaryResult.recognized" class="flex flex-col gap-1">
+ <p class="text-xs text-muted-foreground">{{ t("cellTransform.unrecognizedHint") }}</p>
+ <label class="flex flex-col gap-1">
+ {{ t("cellTransform.pickFormat") }}
+ <select v-model="formatOverride" class="h-7 w-full rounded border bg-background px-2">
+ <option value="">{{ t("cellTransform.pickFormatPlaceholder") }}</option>
+ <option v-for="format in CELL_TRANSFORM_FORMAT_CHOICES" :key="format.mimeType" :value="format.mimeType">{{ format.extension.toUpperCase() }} · {{ format.mimeType }}</option>
+ </select>
+ </label>
+ </div>
+ <div class="flex items-center justify-between gap-2 text-xs">
+ <span class="min-w-0 truncate">{{ effectiveBinary.extension.toUpperCase() }} · {{ binarySizeText }}</span>
+ <Button variant="outline" size="sm" class="h-6 shrink-0 text-xs" @click="saveResult">{{ t("cellTransform.save") }}</Button>
+ </div>
+ <img v-if="imageUrl" :src="imageUrl" :alt="t('grid.imagePreview')" loading="lazy" decoding="async" class="max-h-56 min-h-16 w-full rounded border bg-white object-contain" />
</template>
- <Button size="sm" class="h-8" :disabled="!!blockedReason" @click="convert">{{ t("cellTransform.convert") }}</Button>
</div>
- <p v-if="kind === 'radix'" class="text-xs text-muted-foreground">{{ t("cellTransform.radixHint") }}</p>
- <p v-if="kind === 'urlEncode' || kind === 'urlDecode'" class="text-xs text-muted-foreground">{{ t("cellTransform.urlHint") }}</p>
- <p v-if="blockedReason" role="status" class="text-xs text-muted-foreground">{{ t(`cellTransform.errors.${blockedReason}`, errorLimits) }}</p>
- <p v-else-if="result && !result.ok" role="alert" class="text-xs text-destructive">{{ t(`cellTransform.errors.${result.error}`, errorLimits) }}</p>
- <template v-if="result?.ok">
- <div class="flex items-center justify-between gap-2 text-xs">
- <span
- >{{ t("cellTransform.result") }}<template v-if="result.unit"> · {{ t(`cellTransform.units.${result.unit}`) }}</template></span
- >
- <Button variant="outline" size="sm" class="h-6 text-xs" @click="copyResult">{{ t("cellTransform.copy") }}</Button>
- </div>
- <iframe v-if="kind === 'html'" :srcdoc="htmlPreviewDocument" sandbox="" :title="t('cellTransform.htmlPreview')" class="h-64 min-h-24 w-full rounded border bg-white" />
- <textarea :value="result.text" :aria-label="t('cellTransform.result')" readonly class="dbx-data-grid-value-font h-64 min-h-24 w-full resize-y rounded border bg-muted/20 p-3 text-xs" spellcheck="false" />
- </template>
- </DialogContent>
- </Dialog>
+ </div>
+ </section>
</template>
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index aed2dcb290..772041bc99 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -127,6 +127,13 @@ export default withEnglishFallback({
result: "Nəticə",
copy: "Nəticəni köçür",
htmlPreview: "HTML preview",
+ sourceValue: "Mənbə dəyəri",
+ exitPreview: "Önizləmədən çıx",
+ save: "Faylı saxla",
+ fileHint: "İkili məzmun baytlara çevrilir; tanınan formatlar adlanır, digərləri .bin kimi saxlanılır.",
+ unrecognizedHint: "Format tanınmadı. Önizləmək və uyğun uzantı ilə saxlamaq üçün əl ilə seçin.",
+ pickFormat: "Format seçin",
+ pickFormatPlaceholder: "Format seçin…",
radixHint: "Yalnız tam ədədlər. 0x, 0o və ya 0b prefiksi olmadan rəqəmlər daxil edin; işarə istifadə oluna bilər.",
urlHint: "URL komponentləri UTF-8 ilə kodlanır və ya dekodlaşdırılır. Dekodlaşdırma + işarəsini boşluğa çevirmir.",
kinds: {
@@ -137,6 +144,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Mətn → Base64 (UTF-8)",
base64Decode: "Base64 → mətn (UTF-8)",
+ base64Image: "Base64 → şəkil",
+ base64File: "Base64 → fayl (istənilən format)",
urlEncode: "URL komponentini kodla",
urlDecode: "URL komponentini dekodlaşdır",
radix: "Tam ədədin say sistemini çevir",
@@ -155,7 +164,8 @@ export default withEnglishFallback({
invalidTimestamp: "Dəstəklənən tarix aralığında tam ədəd zaman damğası daxil edin.",
ambiguousUnit: "Vahidi müəyyən etmək mümkün deyil. Saniyə və ya millisaniyə seçin.",
invalidInteger: "Mənbə say sisteminə uyğun tam ədədi prefikssiz daxil edin.",
- invalidBase64: "Etibarlı UTF-8 mətni olan standart doldurmalı Base64 daxil edin.",
+ invalidBase64: "Düzgün Base64 daxil edin; dekodlanmış mətn UTF-8 olmalıdır.",
+ invalidBase64Binary: "Base64 məzmunu yanlıştır: məlumat kəsilib və ya Base64-dən kənar simvollar ehtiva edir.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index 59a54022a4..bc42152d6d 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -388,6 +388,13 @@ export default {
result: "Result",
copy: "Copy result",
htmlPreview: "HTML preview",
+ sourceValue: "Source value",
+ exitPreview: "Exit preview",
+ save: "Save file",
+ fileHint: "Binary content is decoded as raw bytes; recognized formats are labeled, everything else saves as .bin.",
+ unrecognizedHint: "Format not recognized. Choose one manually to preview it and save with the matching extension.",
+ pickFormat: "Choose format",
+ pickFormatPlaceholder: "Select a format…",
radixHint: "Integers only. Enter digits without a 0x, 0o or 0b prefix; an optional sign is supported.",
urlHint: "URL component encoding (UTF-8). Decoding preserves + as a literal plus sign.",
kinds: {
@@ -398,6 +405,8 @@ export default {
html: "HTML preview",
base64Encode: "Text → Base64 (UTF-8)",
base64Decode: "Base64 → text (UTF-8)",
+ base64Image: "Base64 → image",
+ base64File: "Base64 → file (any format)",
urlEncode: "URL component encode",
urlDecode: "URL component decode",
radix: "Integer base conversion",
@@ -416,7 +425,8 @@ export default {
invalidTimestamp: "Enter an integer timestamp within the supported date range.",
ambiguousUnit: "Cannot determine the timestamp unit. Select seconds or milliseconds explicitly.",
invalidInteger: "Enter an integer with digits valid for the selected source base, without a base prefix.",
- invalidBase64: "Enter standard padded Base64 containing valid UTF-8 text.",
+ invalidBase64: "Enter valid Base64 whose decoded bytes form valid UTF-8 text.",
+ invalidBase64Binary: "Invalid Base64 content: the data may be truncated or contain characters outside the Base64 alphabet.",
},
},
redisGrouping,
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 60a3cdca34..69898317bb 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -247,6 +247,13 @@ export default withEnglishFallback({
result: "Resultado",
copy: "Copiar resultado",
htmlPreview: "HTML preview",
+ sourceValue: "Valor de origen",
+ exitPreview: "Salir de la vista previa",
+ save: "Guardar archivo",
+ fileHint: "El contenido binario se decodifica a bytes sin procesar; los formatos reconocidos se etiquetan y el resto se guarda como .bin.",
+ unrecognizedHint: "Formato no reconocido. Elígelo manualmente para previsualizarlo y guardarlo con la extensión adecuada.",
+ pickFormat: "Elegir formato",
+ pickFormatPlaceholder: "Selecciona un formato…",
radixHint: "Solo enteros. Introduce dígitos sin los prefijos 0x, 0o o 0b; se admite un signo opcional.",
urlHint: "Codificación de componentes URL en UTF-8. La decodificación conserva + como signo más.",
kinds: {
@@ -257,6 +264,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Texto → Base64 (UTF-8)",
base64Decode: "Base64 → texto (UTF-8)",
+ base64Image: "Base64 → imagen",
+ base64File: "Base64 → archivo (cualquier formato)",
urlEncode: "Codificar componente URL",
urlDecode: "Decodificar componente URL",
radix: "Conversión de base de enteros",
@@ -275,7 +284,8 @@ export default withEnglishFallback({
invalidTimestamp: "Introduce una marca de tiempo entera dentro del intervalo de fechas admitido.",
ambiguousUnit: "No se puede determinar la unidad. Selecciona segundos o milisegundos.",
invalidInteger: "Introduce un entero válido para la base de origen, sin prefijo.",
- invalidBase64: "Introduce Base64 estándar con relleno que contenga texto UTF-8 válido.",
+ invalidBase64: "Introduce un Base64 válido cuyo contenido decodificado sea texto UTF-8 válido.",
+ invalidBase64Binary: "Contenido Base64 no válido: los datos pueden estar truncados o contener caracteres no admitidos.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index b6214f701c..a40b3414b7 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -22,6 +22,13 @@ export default withEnglishFallback({
result: "Hasil",
copy: "Salin hasil",
htmlPreview: "Pratinjau HTML",
+ sourceValue: "Nilai sumber",
+ exitPreview: "Keluar dari pratinjau",
+ save: "Simpan file",
+ fileHint: "Konten biner didekodekan menjadi byte mentah; format yang dikenali diberi label, lainnya disimpan sebagai .bin.",
+ unrecognizedHint: "Format tidak dikenali. Pilih manual untuk melihat pratinjau dan menyimpan dengan ekstensi yang sesuai.",
+ pickFormat: "Pilih format",
+ pickFormatPlaceholder: "Pilih format…",
radixHint: "Hanya bilangan bulat. Masukkan digit tanpa awalan 0x, 0o, atau 0b; tanda opsional didukung.",
urlHint: "Encoding komponen URL (UTF-8). Dekode mempertahankan + sebagai tanda plus literal.",
kinds: {
@@ -32,6 +39,8 @@ export default withEnglishFallback({
html: "Pratinjau HTML",
base64Encode: "Teks → Base64 (UTF-8)",
base64Decode: "Base64 → teks (UTF-8)",
+ base64Image: "Base64 → gambar",
+ base64File: "Base64 → file (format apa pun)",
urlEncode: "Encode komponen URL",
urlDecode: "Decode komponen URL",
radix: "Konversi basis bilangan bulat",
@@ -50,7 +59,8 @@ export default withEnglishFallback({
invalidTimestamp: "Masukkan timestamp bilangan bulat dalam rentang tanggal yang didukung.",
ambiguousUnit: "Tidak dapat menentukan satuan timestamp. Pilih detik atau milidetik secara eksplisit.",
invalidInteger: "Masukkan bilangan bulat dengan digit yang valid untuk basis sumber yang dipilih, tanpa awalan basis.",
- invalidBase64: "Masukkan Base64 berpadding standar yang berisi teks UTF-8 yang valid.",
+ invalidBase64: "Masukkan Base64 valid yang hasil dekodeannya berupa teks UTF-8.",
+ invalidBase64Binary: "Konten Base64 tidak valid: data mungkin terpotong atau berisi karakter di luar Base64.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 18bdcb468d..0765a7993a 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -245,6 +245,13 @@ export default withEnglishFallback({
result: "Risultato",
copy: "Copia risultato",
htmlPreview: "HTML preview",
+ sourceValue: "Valore sorgente",
+ exitPreview: "Esci dall'anteprima",
+ save: "Salva file",
+ fileHint: "Il contenuto binario viene decodificato in byte grezzi; i formati riconosciuti sono etichettati, gli altri vengono salvati come .bin.",
+ unrecognizedHint: "Formato non riconosciuto. Scegli manualmente per l’anteprima e il salvataggio con l’estensione corretta.",
+ pickFormat: "Scegli formato",
+ pickFormatPlaceholder: "Seleziona un formato…",
radixHint: "Solo interi. Inserisci cifre senza prefissi 0x, 0o o 0b; è ammesso un segno facoltativo.",
urlHint: "Codifica dei componenti URL in UTF-8. La decodifica mantiene + come segno più.",
kinds: {
@@ -255,6 +262,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Testo → Base64 (UTF-8)",
base64Decode: "Base64 → testo (UTF-8)",
+ base64Image: "Base64 → immagine",
+ base64File: "Base64 → file (qualunque formato)",
urlEncode: "Codifica componente URL",
urlDecode: "Decodifica componente URL",
radix: "Conversione di base degli interi",
@@ -273,7 +282,8 @@ export default withEnglishFallback({
invalidTimestamp: "Inserisci un timestamp intero nell’intervallo di date supportato.",
ambiguousUnit: "Impossibile determinare l’unità. Seleziona secondi o millisecondi.",
invalidInteger: "Inserisci un intero valido per la base di origine, senza prefisso.",
- invalidBase64: "Inserisci Base64 standard con padding contenente testo UTF-8 valido.",
+ invalidBase64: "Inserisci un Base64 valido il cui contenuto decodificato sia testo UTF-8 valido.",
+ invalidBase64Binary: "Contenuto Base64 non valido: i dati potrebbero essere troncati o contenere caratteri non consentiti.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 935214585c..42f5c1d397 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -246,6 +246,13 @@ export default withEnglishFallback({
result: "変換結果",
copy: "結果をコピー",
htmlPreview: "HTML preview",
+ sourceValue: "ソース値",
+ exitPreview: "プレビューを終了",
+ save: "ファイルを保存",
+ fileHint: "バイナリ内容はバイト単位でデコードします。認識できる形式はラベルを表示し、それ以外は .bin として保存します。",
+ unrecognizedHint: "形式を認識できません。手動で選択するとプレビュー表示でき、対応する拡張子で保存できます。",
+ pickFormat: "形式を選択",
+ pickFormatPlaceholder: "形式を選択…",
radixHint: "整数のみ対応します。0x、0o、0b 接頭辞は不要です。正負の符号を使用できます。",
urlHint: "URL コンポーネントを UTF-8 でエンコード・デコードします。デコード時に + は空白に変換されません。",
kinds: {
@@ -256,6 +263,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "テキスト → Base64(UTF-8)",
base64Decode: "Base64 → テキスト(UTF-8)",
+ base64Image: "Base64 → 画像",
+ base64File: "Base64 → ファイル(任意形式)",
urlEncode: "URL コンポーネントのエンコード",
urlDecode: "URL コンポーネントのデコード",
radix: "整数の基数変換",
@@ -274,7 +283,8 @@ export default withEnglishFallback({
invalidTimestamp: "対応する日付範囲内の整数タイムスタンプを入力してください。",
ambiguousUnit: "単位を判定できません。秒またはミリ秒を選択してください。",
invalidInteger: "選択した基数に対応する整数を、接頭辞なしで入力してください。",
- invalidBase64: "有効な UTF-8 テキストを含む、標準のパディング付き Base64 を入力してください。",
+ invalidBase64: "有効な Base64 を入力してください。デコード結果は UTF-8 テキストである必要があります。",
+ invalidBase64Binary: "Base64 内容が無効です。データが切り詰められているか、Base64 以外の文字が含まれています。",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index dc827462ad..5d564960e0 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -244,6 +244,13 @@ export default withEnglishFallback({
result: "변환 결과",
copy: "결과 복사",
htmlPreview: "HTML preview",
+ sourceValue: "원본 값",
+ exitPreview: "미리보기 종료",
+ save: "파일 저장",
+ fileHint: "바이너리 내용은 바이트로 디코딩됩니다. 인식 가능한 형식은 라벨을 표시하고 나머지는 .bin으로 저장합니다.",
+ unrecognizedHint: "형식을 인식할 수 없습니다. 수동으로 선택하면 미리보기와 알맞은 확장자 저장이 가능합니다.",
+ pickFormat: "형식 선택",
+ pickFormatPlaceholder: "형식을 선택하세요…",
radixHint: "정수만 지원합니다. 0x, 0o, 0b 접두사 없이 입력하세요. 부호는 사용할 수 있습니다.",
urlHint: "URL 구성 요소를 UTF-8로 인코딩하거나 디코딩합니다. 디코딩 시 +를 공백으로 바꾸지 않습니다.",
kinds: {
@@ -254,6 +261,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "텍스트 → Base64(UTF-8)",
base64Decode: "Base64 → 텍스트(UTF-8)",
+ base64Image: "Base64 → 이미지",
+ base64File: "Base64 → 파일(임의 형식)",
urlEncode: "URL 구성 요소 인코딩",
urlDecode: "URL 구성 요소 디코딩",
radix: "정수 진법 변환",
@@ -272,7 +281,8 @@ export default withEnglishFallback({
invalidTimestamp: "지원하는 날짜 범위 내의 정수 타임스탬프를 입력하세요.",
ambiguousUnit: "단위를 확인할 수 없습니다. 초 또는 밀리초를 선택하세요.",
invalidInteger: "선택한 원본 진법에 맞는 정수를 접두사 없이 입력하세요.",
- invalidBase64: "유효한 UTF-8 텍스트를 포함하는 표준 패딩 Base64를 입력하세요.",
+ invalidBase64: "유효한 Base64를 입력하세요. 디코딩 결과는 UTF-8 텍스트여야 합니다.",
+ invalidBase64Binary: "Base64 내용이 유효하지 않습니다. 데이터가 잘려 있거나 Base64 문자가 아닌 문자가 포함되어 있습니다.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 92d33090a1..a00d4e31b1 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -246,6 +246,13 @@ export default withEnglishFallback({
result: "Resultado",
copy: "Copiar resultado",
htmlPreview: "HTML preview",
+ sourceValue: "Valor de origem",
+ exitPreview: "Sair da pré-visualização",
+ save: "Salvar arquivo",
+ fileHint: "O conteúdo binário é decodificado em bytes brutos; formatos reconhecidos são rotulados e os demais são salvos como .bin.",
+ unrecognizedHint: "Formato não reconhecido. Escolha manualmente para visualizar e salvar com a extensão adequada.",
+ pickFormat: "Escolher formato",
+ pickFormatPlaceholder: "Selecione um formato…",
radixHint: "Somente inteiros. Insira dígitos sem os prefixos 0x, 0o ou 0b; um sinal opcional é permitido.",
urlHint: "Codificação de componentes URL em UTF-8. A decodificação preserva + como sinal de adição.",
kinds: {
@@ -256,6 +263,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Texto → Base64 (UTF-8)",
base64Decode: "Base64 → texto (UTF-8)",
+ base64Image: "Base64 → imagem",
+ base64File: "Base64 → arquivo (qualquer formato)",
urlEncode: "Codificar componente URL",
urlDecode: "Decodificar componente URL",
radix: "Conversão de base de inteiros",
@@ -274,7 +283,8 @@ export default withEnglishFallback({
invalidTimestamp: "Insira um timestamp inteiro dentro do intervalo de datas compatível.",
ambiguousUnit: "Não foi possível determinar a unidade. Selecione segundos ou milissegundos.",
invalidInteger: "Insira um inteiro válido para a base de origem, sem prefixo.",
- invalidBase64: "Insira Base64 padrão com preenchimento contendo texto UTF-8 válido.",
+ invalidBase64: "Insira um Base64 válido cujo conteúdo decodificado seja texto UTF-8 válido.",
+ invalidBase64Binary: "Conteúdo Base64 inválido: os dados podem estar truncados ou conter caracteres não permitidos.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 94872defe5..15f555dc2c 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -188,6 +188,13 @@ export default withEnglishFallback({
result: "Результат",
copy: "Копировать результат",
htmlPreview: "HTML preview",
+ sourceValue: "Исходное значение",
+ exitPreview: "Выйти из предпросмотра",
+ save: "Сохранить файл",
+ fileHint: "Двоичное содержимое декодируется в байты; распознанные форматы подписываются, остальные сохраняются как .bin.",
+ unrecognizedHint: "Формат не распознан. Выберите его вручную, чтобы просмотреть и сохранить с подходящим расширением.",
+ pickFormat: "Выбрать формат",
+ pickFormatPlaceholder: "Выберите формат…",
radixHint: "Только целые числа. Вводите цифры без префикса 0x, 0o или 0b; допускается необязательный знак.",
urlHint: "Кодирование компонента URL (UTF-8). При декодировании + сохраняется как знак плюс.",
kinds: {
@@ -198,6 +205,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Текст → Base64 (UTF-8)",
base64Decode: "Base64 → текст (UTF-8)",
+ base64Image: "Base64 → изображение",
+ base64File: "Base64 → файл (любой формат)",
urlEncode: "Кодировать компонент URL",
urlDecode: "Декодировать компонент URL",
radix: "Преобразование систем счисления",
@@ -216,7 +225,8 @@ export default withEnglishFallback({
invalidTimestamp: "Введите целочисленный timestamp в пределах поддерживаемого диапазона дат.",
ambiguousUnit: "Не удалось определить единицу времени. Укажите секунды или миллисекунды явно.",
invalidInteger: "Введите целое число с цифрами, допустимыми для выбранной исходной системы счисления, без префикса основания.",
- invalidBase64: "Введите стандартный Base64 с дополнением, содержащий корректный текст UTF-8.",
+ invalidBase64: "Введите корректный Base64; декодированное содержимое должно быть допустимым текстом UTF-8.",
+ invalidBase64Binary: "Недопустимое содержимое Base64: данные могут быть обрезаны или содержать посторонние символы.",
},
},
redisGrouping: {
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index c5374a53a1..8a9806be84 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -213,6 +213,13 @@ export default withEnglishFallback({
result: "ผลลัพธ์",
copy: "คัดลอกผลลัพธ์",
htmlPreview: "ตัวอย่าง HTML",
+ sourceValue: "ค่าต้นทาง",
+ exitPreview: "ออกจากตัวอย่าง",
+ save: "บันทึกไฟล์",
+ fileHint: "เนื้อหาไบนารีถูกถอดรหัสเป็นไบต์ รูปแบบที่รับรู้จะแสดงป้ายกำกับ ส่วนอื่นบันทึกเป็น .bin",
+ unrecognizedHint: "จำรูปแบบไม่ได้ เลือกด้วยตนเองเพื่อดูตัวอย่างและบันทึกพร้อมนามสกุลที่เหมาะสม",
+ pickFormat: "เลือกรูปแบบ",
+ pickFormatPlaceholder: "เลือกรูปแบบ…",
radixHint: "ใช้จำนวนเต็มเท่านั้น ป้อนตัวเลขโดยไม่ใส่ 0x, 0o หรือ 0b นำหน้า จะใส่เครื่องหมาย + หรือ - นำหน้าก็ได้",
urlHint: "การเข้ารหัสส่วนประกอบ URL (UTF-8) การถอดรหัสจะเก็บ + เป็นเครื่องหมายบวกตามตัวอักษร",
kinds: {
@@ -223,6 +230,8 @@ export default withEnglishFallback({
html: "ตัวอย่าง HTML",
base64Encode: "ข้อความ → Base64 (UTF-8)",
base64Decode: "Base64 → ข้อความ (UTF-8)",
+ base64Image: "Base64 → ภาพ",
+ base64File: "Base64 → ไฟล์ (ทุกรูปแบบ)",
urlEncode: "เข้ารหัสส่วนประกอบ URL",
urlDecode: "ถอดรหัสส่วนประกอบ URL",
radix: "การแปลงฐานจำนวนเต็ม",
@@ -241,7 +250,8 @@ export default withEnglishFallback({
invalidTimestamp: "ป้อน Timestamp จำนวนเต็มที่อยู่ในช่วงวันที่ที่รองรับ",
ambiguousUnit: "ไม่สามารถระบุหน่วย Timestamp ได้ เลือกวินาทีหรือมิลลิวินาทีอย่างชัดเจน",
invalidInteger: "ป้อนจำนวนเต็มที่มีตัวเลขถูกต้องตามฐานต้นทางที่เลือก โดยไม่มีคำนำหน้าฐาน",
- invalidBase64: "ป้อน Base64 มาตรฐานที่มี padding และมีข้อความ UTF-8 ที่ถูกต้อง",
+ invalidBase64: "ป้อน Base64 ที่ถูกต้อง และเนื้อหาที่ถอดรหัสต้องเป็นข้อความ UTF-8 ที่ถูกต้อง",
+ invalidBase64Binary: "เนื้อหา Base64 ไม่ถูกต้อง ข้อมูลอาจถูกตัดจบหรือมีอักขระที่ไม่ใช่ Base64",
},
},
redisGrouping: {
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 994747ed6f..fa9dfc4f9d 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -127,6 +127,13 @@ export default withEnglishFallback({
result: "Sonuç",
copy: "Sonucu kopyala",
htmlPreview: "HTML preview",
+ sourceValue: "Kaynak değer",
+ exitPreview: "Önizlemeden çık",
+ save: "Dosyayı kaydet",
+ fileHint: "İkili içerik ham baytlara çözülür; tanınan biçimler etiketlenir, diğerleri .bin olarak kaydedilir.",
+ unrecognizedHint: "Biçim tanınmadı. Önizlemek ve uygun uzantıyla kaydetmek için elle seçin.",
+ pickFormat: "Biçim seç",
+ pickFormatPlaceholder: "Bir biçim seçin…",
radixHint: "Yalnızca tam sayılar. 0x, 0o veya 0b öneki olmadan rakam girin; isteğe bağlı işaret kullanılabilir.",
urlHint: "URL bileşenleri UTF-8 ile kodlanır veya çözülür. Çözme işlemi + işaretini boşluğa dönüştürmez.",
kinds: {
@@ -137,6 +144,8 @@ export default withEnglishFallback({
html: "HTML preview",
base64Encode: "Metin → Base64 (UTF-8)",
base64Decode: "Base64 → metin (UTF-8)",
+ base64Image: "Base64 → görüntü",
+ base64File: "Base64 → dosya (herhangi bir biçim)",
urlEncode: "URL bileşenini kodla",
urlDecode: "URL bileşeninin kodunu çöz",
radix: "Tam sayı taban dönüşümü",
@@ -155,7 +164,8 @@ export default withEnglishFallback({
invalidTimestamp: "Desteklenen tarih aralığında bir tam sayı zaman damgası girin.",
ambiguousUnit: "Birim belirlenemiyor. Saniye veya milisaniyeyi seçin.",
invalidInteger: "Kaynak tabana uygun bir tam sayıyı öneksiz girin.",
- invalidBase64: "Geçerli UTF-8 metni içeren standart dolgulu Base64 girin.",
+ invalidBase64: "Geçerli bir Base64 girin; çözülen içerik geçerli UTF-8 metni olmalıdır.",
+ invalidBase64Binary: "Geçersiz Base64 içeriği: veri kesilmiş olabilir veya Base64 dışı karakterler içeriyor.",
},
},
customType: {
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index b0f3f6dca6..a527201f53 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -333,6 +333,13 @@ export default withEnglishFallback({
result: "转换结果",
copy: "复制结果",
htmlPreview: "HTML 渲染预览",
+ sourceValue: "现有值",
+ exitPreview: "退出预览",
+ save: "保存文件",
+ fileHint: "二进制内容按原始字节解码;可识别的格式会标注类型,其余按 .bin 保存。",
+ unrecognizedHint: "无法识别格式。手动选择后可预览,并按对应扩展名保存。",
+ pickFormat: "选择格式",
+ pickFormatPlaceholder: "请选择格式…",
radixHint: "仅支持整数,请勿输入 0x、0o 或 0b 前缀,可使用正负号。",
urlHint: "按 URL 组件进行 UTF-8 编解码,解码时保留加号,不将其替换为空格。",
kinds: {
@@ -343,6 +350,8 @@ export default withEnglishFallback({
html: "HTML 渲染预览",
base64Encode: "文本 → Base64(UTF-8)",
base64Decode: "Base64 → 文本(UTF-8)",
+ base64Image: "Base64 → 图片",
+ base64File: "Base64 → 文件(任意格式)",
urlEncode: "URL 组件编码",
urlDecode: "URL 组件解码",
radix: "整数进制转换",
@@ -361,7 +370,8 @@ export default withEnglishFallback({
invalidTimestamp: "请输入有效日期范围内的整数时间戳。",
ambiguousUnit: "无法确定时间戳单位,请手动选择秒或毫秒。",
invalidInteger: "请输入符合原进制的整数,不要包含进制前缀。",
- invalidBase64: "请输入带标准填充的 Base64,且解码内容必须为有效 UTF-8 文本。",
+ invalidBase64: "请输入有效的 Base64,且解码内容必须是合法的 UTF-8 文本。",
+ invalidBase64Binary: "Base64 内容无效:数据可能被截断,或包含 Base64 字符表以外的字符。",
},
},
redisGrouping,
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 56ccd97ade..eb394dfd7d 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -246,6 +246,13 @@ export default withEnglishFallback({
result: "轉換結果",
copy: "複製結果",
htmlPreview: "HTML 渲染預覽",
+ sourceValue: "現有值",
+ exitPreview: "退出預覽",
+ save: "儲存檔案",
+ fileHint: "二進位內容以原始位元組解碼;可辨識的格式會標註類型,其餘以 .bin 儲存。",
+ unrecognizedHint: "無法辨識格式。手動選擇後可預覽,並依對應副檔名儲存。",
+ pickFormat: "選擇格式",
+ pickFormatPlaceholder: "請選擇格式…",
radixHint: "僅支援整數,請勿輸入 0x、0o 或 0b 前綴,可使用正負號。",
urlHint: "按 URL 元件進行 UTF-8 編解碼,解碼時保留加號,不將其替換為空格。",
kinds: {
@@ -256,6 +263,8 @@ export default withEnglishFallback({
html: "HTML 渲染預覽",
base64Encode: "文字 → Base64(UTF-8)",
base64Decode: "Base64 → 文字(UTF-8)",
+ base64Image: "Base64 → 圖片",
+ base64File: "Base64 → 檔案(任意格式)",
urlEncode: "URL 元件編碼",
urlDecode: "URL 元件解碼",
radix: "整數進位轉換",
@@ -274,7 +283,8 @@ export default withEnglishFallback({
invalidTimestamp: "請輸入有效日期範圍內的整數時間戳記。",
ambiguousUnit: "無法確定時間戳記單位,請手動選擇秒或毫秒。",
invalidInteger: "請輸入符合原進位的整數,不要包含進位前綴。",
- invalidBase64: "請輸入帶標準填補的 Base64,且解碼內容必須為有效 UTF-8 文字。",
+ invalidBase64: "請輸入有效的 Base64,且解碼內容必須是合法的 UTF-8 文字。",
+ invalidBase64Binary: "Base64 內容無效:資料可能被截斷,或包含 Base64 字元表以外的字元。",
},
},
redisGrouping,
diff --git a/apps/desktop/src/lib/dataGrid/__tests__/cellValueTransformBinary.spec.ts b/apps/desktop/src/lib/dataGrid/__tests__/cellValueTransformBinary.spec.ts
new file mode 100644
index 0000000000..9150d4094a
--- /dev/null
+++ b/apps/desktop/src/lib/dataGrid/__tests__/cellValueTransformBinary.spec.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from "vitest";
+import { CELL_TRANSFORM_FORMAT_CHOICES, CELL_TRANSFORM_MAX_BINARY_INPUT, CELL_TRANSFORM_MAX_INPUT, transformCellValue } from "@/lib/dataGrid/cellValueTransform";
+
+function base64Of(bytes: number[]): string {
+ return btoa(String.fromCharCode(...bytes));
+}
+
+const PNG_HEADER = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3];
+const JPEG_HEADER = [0xff, 0xd8, 0xff, 0xe0, 1, 2];
+const PDF_HEADER = [0x25, 0x50, 0x44, 0x46, 0x2d];
+
+describe("transformCellValue base64Image", () => {
+ it("decodes a png payload and labels its format", () => {
+ const result = transformCellValue(base64Of(PNG_HEADER), { kind: "base64Image" });
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect("binary" in result && result.binary).toMatchObject({ mimeType: "image/png", extension: "png", isImage: true, recognized: true });
+ expect("binary" in result && Array.from(result.binary.bytes)).toEqual(PNG_HEADER);
+ });
+
+ it("accepts jpeg and webp via magic bytes", () => {
+ const webp = [0x52, 0x49, 0x46, 0x46, 4, 0, 0, 0, 0x57, 0x45, 0x42, 0x50, 9];
+ expect(transformCellValue(base64Of(JPEG_HEADER), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "jpg", recognized: true } });
+ expect(transformCellValue(base64Of(webp), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "webp", recognized: true } });
+ });
+
+ it("labels any detected format instead of rejecting non-image bytes", () => {
+ expect(transformCellValue(base64Of(PDF_HEADER), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { mimeType: "application/pdf", extension: "pdf", isImage: false, recognized: true } });
+ });
+
+ it("marks undetectable payloads unrecognized with a bin fallback", () => {
+ expect(transformCellValue(base64Of([1, 2, 3, 4]), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { mimeType: "application/octet-stream", extension: "bin", isImage: false, recognized: false } });
+ });
+
+ it("rejects malformed base64", () => {
+ expect(transformCellValue("not base64!!", { kind: "base64Image" })).toEqual({ ok: false, error: "invalidBase64" });
+ });
+
+ it("normalizes unpadded, base64url, and whitespace-wrapped payloads", () => {
+ const payload = base64Of(PNG_HEADER);
+ expect(transformCellValue(payload.replace(/=+$/, ""), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "png" } });
+ expect(transformCellValue(payload.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""), { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "png" } });
+ const wrapped = `${payload.slice(0, 8)}\n ${payload.slice(8, 20)}\t${payload.slice(20)}`;
+ expect(transformCellValue(wrapped, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "png" } });
+ const odd = base64Of([0xff, 0xd8, 0xff, 0xe0]).replace(/=+$/, "");
+ expect(transformCellValue(odd, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "jpg" } });
+ });
+
+ it("tolerates a truncated payload ending in one orphan character", () => {
+ const result = transformCellValue(`${base64Of(PNG_HEADER)}A`, { kind: "base64Image" });
+ expect(result).toMatchObject({ ok: true, binary: { extension: "png" } });
+ if (result.ok && "binary" in result) expect(Array.from(result.binary.bytes)).toEqual(PNG_HEADER);
+ });
+
+ it("applies the binary input gate instead of the text gate", () => {
+ expect(transformCellValue("A".repeat(CELL_TRANSFORM_MAX_BINARY_INPUT + 4), { kind: "base64Image" })).toEqual({ ok: false, error: "tooLarge" });
+ // Past the text gate but within the binary gate: text kinds reject, binary kinds decode.
+ const overTextInput = "AAAA".repeat(CELL_TRANSFORM_MAX_INPUT / 4 + 1);
+ expect(transformCellValue(overTextInput, { kind: "json" })).toEqual({ ok: false, error: "tooLarge" });
+ expect(transformCellValue(overTextInput, { kind: "base64File" }).ok).toBe(true);
+ });
+});
+
+describe("transformCellValue base64File", () => {
+ it("labels recognized non-image formats", () => {
+ expect(transformCellValue(base64Of(PDF_HEADER), { kind: "base64File" })).toMatchObject({ ok: true, binary: { mimeType: "application/pdf", extension: "pdf", isImage: false, recognized: true } });
+ const zip = [0x50, 0x4b, 0x03, 0x04, 20];
+ expect(transformCellValue(base64Of(zip), { kind: "base64File" })).toMatchObject({ ok: true, binary: { extension: "zip", recognized: true } });
+ });
+
+ it("falls back to bin for unknown bytes and keeps images", () => {
+ expect(transformCellValue(base64Of([1, 2, 3, 4]), { kind: "base64File" })).toMatchObject({ ok: true, binary: { mimeType: "application/octet-stream", extension: "bin", recognized: false } });
+ expect(transformCellValue(base64Of(PNG_HEADER), { kind: "base64File" })).toMatchObject({ ok: true, binary: { extension: "png", isImage: true, recognized: true } });
+ });
+});
+
+describe("transformCellValue format choices", () => {
+ it("offers every detected format plus txt and bin for manual selection", () => {
+ expect(CELL_TRANSFORM_FORMAT_CHOICES.map((format) => format.extension)).toEqual(["png", "jpg", "gif", "webp", "bmp", "ico", "pdf", "zip", "gz", "txt", "bin"]);
+ });
+});
+
+describe("transformCellValue text kinds unchanged", () => {
+ it("base64Decode still rejects binary payloads", () => {
+ expect(transformCellValue(base64Of(PNG_HEADER), { kind: "base64Decode" })).toEqual({ ok: false, error: "invalidBase64" });
+ const utf8Base64 = btoa(String.fromCharCode(...new TextEncoder().encode("héllo")));
+ expect(transformCellValue(utf8Base64, { kind: "base64Decode" })).toMatchObject({ ok: true, text: "héllo" });
+ });
+
+ it("base64Decode accepts unpadded and base64url payloads", () => {
+ const utf8Base64 = btoa(String.fromCharCode(...new TextEncoder().encode("héllo")));
+ expect(transformCellValue(utf8Base64.replace(/=+$/, ""), { kind: "base64Decode" })).toMatchObject({ ok: true, text: "héllo" });
+ expect(transformCellValue(` ${utf8Base64.slice(0, 4)}\n${utf8Base64.slice(4)} `, { kind: "base64Decode" })).toMatchObject({ ok: true, text: "héllo" });
+ });
+});
+
+describe("transformCellValue data URI prefixes", () => {
+ it("strips data:image/...;base64, before decoding for image and text kinds", () => {
+ const png = base64Of(PNG_HEADER);
+ expect(transformCellValue(`data:image/png;base64,${png}`, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "png", isImage: true, recognized: true } });
+ expect(transformCellValue(`data:;base64,AA==`, { kind: "base64File" })).toMatchObject({ ok: true, binary: { extension: "bin", recognized: false } });
+ const utf8Base64 = btoa(String.fromCharCode(...new TextEncoder().encode("hello")));
+ expect(transformCellValue(`data:text/plain;charset=utf-8;base64,${utf8Base64}`, { kind: "base64Decode" })).toMatchObject({ ok: true, text: "hello" });
+ });
+
+ it("labels unknown magic bytes from the declared mime", () => {
+ const weird = base64Of([1, 2, 3, 4, 5, 6]);
+ const result = transformCellValue(`data:application/pdf;base64,${weird}`, { kind: "base64File" });
+ expect(result).toMatchObject({ ok: true, binary: { mimeType: "application/pdf", extension: "pdf", isImage: false, recognized: true } });
+ expect(transformCellValue(`data:image/png;base64,${weird}`, { kind: "base64File" })).toMatchObject({ ok: true, binary: { extension: "png", isImage: true, recognized: true } });
+ expect(transformCellValue(`data:image/png;base64,${weird}`, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "png", isImage: true, recognized: true } });
+ // Unknown declared mime keeps the unrecognized .bin fallback for both binary kinds.
+ expect(transformCellValue(`data:application/x-unknown;base64,${weird}`, { kind: "base64File" })).toMatchObject({ ok: true, binary: { extension: "bin", recognized: false } });
+ expect(transformCellValue(`data:application/x-unknown;base64,${weird}`, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "bin", recognized: false } });
+ });
+
+ it("reports the detected format for base64Image when bytes are a known non-image", () => {
+ expect(transformCellValue(`data:image/png;base64,${base64Of(PDF_HEADER)}`, { kind: "base64Image" })).toMatchObject({ ok: true, binary: { extension: "pdf", isImage: false, recognized: true } });
+ });
+});
diff --git a/apps/desktop/src/lib/dataGrid/cellValueTransform.ts b/apps/desktop/src/lib/dataGrid/cellValueTransform.ts
index 30c685117f..636b80b99d 100644
--- a/apps/desktop/src/lib/dataGrid/cellValueTransform.ts
+++ b/apps/desktop/src/lib/dataGrid/cellValueTransform.ts
@@ -5,8 +5,11 @@ import { applyColumnFormatter, DataGridDateTimePatterns } from "@/lib/dataGrid/c
export const CELL_TRANSFORM_MAX_INPUT = 50_000;
export const CELL_TRANSFORM_MAX_OUTPUT = 200_000;
export const CELL_TRANSFORM_MAX_RADIX_DIGITS = 4_096;
-export const CELL_TRANSFORM_KINDS = ["timestamp", "json", "jsonCompact", "xml", "html", "base64Encode", "base64Decode", "urlEncode", "urlDecode", "radix"] as const;
+/** Base64 二进制转换的输入字符上限(约 7.5MB 解码字节),与 BLOB 下载路径的量级一致。 */
+export const CELL_TRANSFORM_MAX_BINARY_INPUT = 10_000_000;
+export const CELL_TRANSFORM_KINDS = ["timestamp", "json", "jsonCompact", "xml", "html", "base64Encode", "base64Decode", "base64Image", "base64File", "urlEncode", "urlDecode", "radix"] as const;
export type CellTransformKind = (typeof CELL_TRANSFORM_KINDS)[number];
+export const BINARY_CELL_TRANSFORM_KINDS: readonly CellTransformKind[] = ["base64Image", "base64File"];
export type CellTransformError = "tooLarge" | "invalid" | "invalidTimestamp" | "ambiguousUnit" | "invalidInteger" | "invalidBase64";
export interface CellTransformOptions {
kind: CellTransformKind;
@@ -16,7 +19,15 @@ export interface CellTransformOptions {
fromBase?: number;
toBase?: number;
}
-export type CellTransformResult = { ok: true; text: string; unit?: "seconds" | "milliseconds" } | { ok: false; error: CellTransformError };
+export interface CellTransformBinaryResult {
+ bytes: Uint8Array;
+ mimeType: string;
+ extension: string;
+ isImage: boolean;
+ /** False when neither magic bytes nor a declared data-URI MIME identified the payload; the UI lets the user pick a format. */
+ recognized: boolean;
+}
+export type CellTransformResult = { ok: true; text: string; unit?: "seconds" | "milliseconds" } | { ok: true; binary: CellTransformBinaryResult } | { ok: false; error: CellTransformError };
function fail(error: CellTransformError): never {
throw new TransformError(error);
@@ -27,9 +38,79 @@ class TransformError extends Error {
}
}
+const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
+
+// Cells often store `data:image/png;base64,...` instead of bare base64; strip the URI prefix before decoding.
+const DATA_URI_RE = /^data:([^,]*);base64,/i;
+
+function splitDataUri(source: string): { payload: string; declaredMime: string | null } {
+ const match = DATA_URI_RE.exec(source);
+ if (!match) return { payload: source, declaredMime: null };
+ const mime = (match[1] ?? "").split(";")[0].trim().toLowerCase();
+ return { payload: source.slice(match[0].length), declaredMime: mime || null };
+}
+
+function decodeBase64Bytes(source: string): Uint8Array {
+ // Auto-normalize the ways base64 shows up in cells: leading/trailing whitespace, an optional
+ // data URI prefix, MIME-style line wrapping, base64url alphabets, and omitted `=` padding.
+ let input = splitDataUri(source.trim()).payload.replace(/\s/g, "").replace(/-/g, "+").replace(/_/g, "/");
+ const remainder = input.length % 4;
+ // Truncated cell payloads often end in one orphan character that cannot encode a byte; drop it.
+ if (remainder === 1) input = input.slice(0, -1);
+ else if (remainder > 1) input += "=".repeat(4 - remainder);
+ if (!BASE64_RE.test(input)) fail("invalidBase64");
+ const binary = atob(input);
+ if (btoa(binary) !== input) fail("invalidBase64");
+ return Uint8Array.from(binary, (character) => character.charCodeAt(0));
+}
+
+interface BinaryFormat {
+ mimeType: string;
+ extension: string;
+}
+
+function startsWithBytes(bytes: Uint8Array, prefix: readonly number[], offset = 0): boolean {
+ return prefix.every((byte, index) => bytes[offset + index] === byte);
+}
+
+const IMAGE_FORMATS: { format: BinaryFormat; match: (bytes: Uint8Array) => boolean }[] = [
+ { format: { mimeType: "image/png", extension: "png" }, match: (bytes) => startsWithBytes(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) },
+ { format: { mimeType: "image/jpeg", extension: "jpg" }, match: (bytes) => startsWithBytes(bytes, [0xff, 0xd8, 0xff]) },
+ { format: { mimeType: "image/gif", extension: "gif" }, match: (bytes) => startsWithBytes(bytes, [0x47, 0x49, 0x46, 0x38]) },
+ { format: { mimeType: "image/webp", extension: "webp" }, match: (bytes) => startsWithBytes(bytes, [0x52, 0x49, 0x46, 0x46]) && startsWithBytes(bytes, [0x57, 0x45, 0x42, 0x50], 8) },
+ { format: { mimeType: "image/bmp", extension: "bmp" }, match: (bytes) => startsWithBytes(bytes, [0x42, 0x4d]) },
+ { format: { mimeType: "image/x-icon", extension: "ico" }, match: (bytes) => startsWithBytes(bytes, [0x00, 0x00, 0x01, 0x00]) },
+];
+
+const OTHER_FILE_FORMATS: { format: BinaryFormat; match: (bytes: Uint8Array) => boolean }[] = [
+ { format: { mimeType: "application/pdf", extension: "pdf" }, match: (bytes) => startsWithBytes(bytes, [0x25, 0x50, 0x44, 0x46]) },
+ { format: { mimeType: "application/zip", extension: "zip" }, match: (bytes) => startsWithBytes(bytes, [0x50, 0x4b, 0x03, 0x04]) },
+ { format: { mimeType: "application/gzip", extension: "gz" }, match: (bytes) => startsWithBytes(bytes, [0x1f, 0x8b]) },
+];
+
+/** Formats the user can pick manually when auto-detection fails. */
+export const CELL_TRANSFORM_FORMAT_CHOICES: readonly BinaryFormat[] = [...IMAGE_FORMATS.map((entry) => entry.format), ...OTHER_FILE_FORMATS.map((entry) => entry.format), { mimeType: "text/plain", extension: "txt" }, { mimeType: "application/octet-stream", extension: "bin" }];
+
+function detectImageFormat(bytes: Uint8Array): BinaryFormat | null {
+ return IMAGE_FORMATS.find((candidate) => candidate.match(bytes))?.format ?? null;
+}
+
+function detectFileFormat(bytes: Uint8Array): { format: BinaryFormat; isImage: boolean } {
+ const image = detectImageFormat(bytes);
+ if (image) return { format: image, isImage: true };
+ const other = OTHER_FILE_FORMATS.find((candidate) => candidate.match(bytes));
+ return { format: other?.format ?? { mimeType: "application/octet-stream", extension: "bin" }, isImage: false };
+}
+
+function formatFromMime(mimeType: string | null): BinaryFormat | null {
+ if (!mimeType) return null;
+ return [...IMAGE_FORMATS, ...OTHER_FILE_FORMATS].find((candidate) => candidate.format.mimeType === mimeType)?.format ?? null;
+}
+
/** Pure, opt-in text conversion. Never feed this result into the cell commit path. */
export function transformCellValue(source: string, options: CellTransformOptions): CellTransformResult {
- if (source.length > CELL_TRANSFORM_MAX_INPUT) return { ok: false, error: "tooLarge" };
+ const maxInput = BINARY_CELL_TRANSFORM_KINDS.includes(options.kind) ? CELL_TRANSFORM_MAX_BINARY_INPUT : CELL_TRANSFORM_MAX_INPUT;
+ if (source.length > maxInput) return { ok: false, error: "tooLarge" };
try {
let text: string;
let unit: "seconds" | "milliseconds" | undefined;
@@ -82,17 +163,29 @@ export function transformCellValue(source: string, options: CellTransformOptions
break;
}
case "base64Decode": {
- const input = source.replace(/\s/g, "");
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(input)) fail("invalidBase64");
- const binary = atob(input);
- if (btoa(binary) !== input) fail("invalidBase64");
+ const bytes = decodeBase64Bytes(source);
try {
- text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(Uint8Array.from(binary, (character) => character.charCodeAt(0)));
+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
} catch {
fail("invalidBase64");
}
break;
}
+ case "base64Image":
+ case "base64File": {
+ const bytes = decodeBase64Bytes(source);
+ const detected = detectFileFormat(bytes);
+ let format = detected.format;
+ let isImage = detected.isImage;
+ if (format.extension === "bin") {
+ const declared = formatFromMime(splitDataUri(source).declaredMime);
+ if (declared) {
+ format = declared;
+ isImage = IMAGE_FORMATS.some((candidate) => candidate.format.mimeType === declared.mimeType);
+ }
+ }
+ return { ok: true, binary: { bytes, ...format, isImage, recognized: format.extension !== "bin" } };
+ }
case "radix": {
const from = options.fromBase ?? 10;
const to = options.toBase ?? 16;
diff --git a/packages/app-tests/cellValueTransform.test.ts b/packages/app-tests/cellValueTransform.test.ts
index 12d1b82aee..9b92f160b9 100644
--- a/packages/app-tests/cellValueTransform.test.ts
+++ b/packages/app-tests/cellValueTransform.test.ts
@@ -105,9 +105,11 @@ test("base64Decode tolerates whitespace inside the alphabet", () => {
assert.deepEqual(transformCellValue("5L2g\n 5aW9", { kind: "base64Decode" }), { ok: true, text: "你好" });
});
-test("base64Decode rejects unpadded, url-safe, and non-UTF-8 input", () => {
+test("base64Decode normalizes url-safe input and rejects truncated or non-UTF-8 payloads", () => {
+ // The decoder auto-normalizes cell payloads: "-" and "_" map back to the standard alphabet, so this decodes.
+ assert.deepEqual(transformCellValue("5L2g5aW-", { kind: "base64Decode" }), { ok: true, text: "你奾" });
+ // Missing padding alone is accepted, but the padded bytes must still form valid UTF-8.
assert.deepEqual(transformCellValue("5L2g5aW", { kind: "base64Decode" }), { ok: false, error: "invalidBase64" });
- assert.deepEqual(transformCellValue("5L2g5aW-", { kind: "base64Decode" }), { ok: false, error: "invalidBase64" });
assert.deepEqual(transformCellValue("5L2g5a_9", { kind: "base64Decode" }), { ok: false, error: "invalidBase64" });
// "/w==" decodes to the single byte 0xFF, which is not valid UTF-8.
assert.deepEqual(transformCellValue("/w==", { kind: "base64Decode" }), { ok: false, error: "invalidBase64" });